1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use tor_hscrypto::{pk::HsBlindId, RevisionCounter, Subcredential};
use tor_llcrypto::cipher::aes::Aes256Ctr as Cipher;
use tor_llcrypto::d::Sha3_256 as Hash;
use tor_llcrypto::d::Shake256 as KDF;
use arrayref::array_ref;
use cipher::{KeyIvInit, StreamCipher};
use digest::{ExtendableOutput, FixedOutput, Update, XofReader};
use rand::{CryptoRng, Rng};
use tor_llcrypto::util::ct::CtByteArray;
use zeroize::Zeroizing as Z;
pub(super) struct HsDescEncryption<'a> {
pub(super) blinded_id: &'a HsBlindId,
pub(super) desc_enc_nonce: Option<&'a HsDescEncNonce>,
pub(super) subcredential: &'a Subcredential,
pub(super) revision: RevisionCounter,
pub(super) string_const: &'a [u8],
}
pub(crate) const HS_DESC_CLIENT_ID_LEN: usize = 8;
pub(crate) const HS_DESC_IV_LEN: usize = 16;
pub(crate) const HS_DESC_ENC_NONCE_LEN: usize = 16;
#[derive(derive_more::AsRef, derive_more::From)]
pub(super) struct HsDescEncNonce([u8; HS_DESC_ENC_NONCE_LEN]);
const SALT_LEN: usize = 16;
const MAC_LEN: usize = 32;
type Salt = [u8; SALT_LEN];
impl<'a> HsDescEncryption<'a> {
const MAC_KEY_LEN: usize = 32;
const CIPHER_KEY_LEN: usize = 32;
const IV_LEN: usize = 16;
pub(super) fn encrypt<R: Rng + CryptoRng>(&self, rng: &mut R, data: &[u8]) -> Vec<u8> {
let output_len = data.len() + SALT_LEN + MAC_LEN;
let mut output = Vec::with_capacity(output_len);
let salt: [u8; SALT_LEN] = rng.gen();
let (mut cipher, mut mac) = self.init(&salt);
output.extend_from_slice(&salt[..]);
output.extend_from_slice(data);
cipher.apply_keystream(&mut output[SALT_LEN..]);
mac.update(&output[SALT_LEN..]);
let mut mac_val = Default::default();
let mac = mac.finalize_into(&mut mac_val);
output.extend_from_slice(&mac_val);
debug_assert_eq!(output.len(), output_len);
output
}
pub(super) fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, DecryptionError> {
if data.len() < SALT_LEN + MAC_LEN {
return Err(DecryptionError::default());
}
let msg_len = data.len() - SALT_LEN - MAC_LEN;
let salt = *array_ref![data, 0, SALT_LEN];
let ciphertext = &data[SALT_LEN..(SALT_LEN + msg_len)];
let expected_mac = CtByteArray::from(*array_ref![data, SALT_LEN + msg_len, MAC_LEN]);
let (mut cipher, mut mac) = self.init(&salt);
mac.update(ciphertext);
let mut received_mac = CtByteArray::from([0_u8; MAC_LEN]);
mac.finalize_into(received_mac.as_mut().into());
if received_mac != expected_mac {
return Err(DecryptionError::default());
}
let mut decrypted = ciphertext.to_vec();
cipher.apply_keystream(&mut decrypted[..]);
Ok(decrypted)
}
fn init(&self, salt: &[u8; 16]) -> (Cipher, Hash) {
let mut key_stream = self.get_kdf(salt).finalize_xof();
let mut key = Z::new([0_u8; Self::CIPHER_KEY_LEN]);
let mut iv = Z::new([0_u8; Self::IV_LEN]);
let mut mac_key = Z::new([0_u8; Self::MAC_KEY_LEN]); key_stream.read(&mut key[..]);
key_stream.read(&mut iv[..]);
key_stream.read(&mut mac_key[..]);
let cipher = Cipher::new(key.as_ref().into(), iv.as_ref().into());
let mut mac = Hash::default();
mac.update(&(Self::MAC_KEY_LEN as u64).to_be_bytes());
mac.update(&mac_key[..]);
mac.update(&(salt.len() as u64).to_be_bytes());
mac.update(&salt[..]);
(cipher, mac)
}
fn get_kdf(&self, salt: &[u8; 16]) -> KDF {
let mut kdf = KDF::default();
kdf.update(self.blinded_id.as_ref());
if let Some(cookie) = self.desc_enc_nonce {
kdf.update(cookie.as_ref());
}
kdf.update(self.subcredential.as_ref());
kdf.update(&u64::from(self.revision).to_be_bytes());
kdf.update(salt);
kdf.update(self.string_const);
kdf
}
}
#[non_exhaustive]
#[derive(Clone, Debug, Default, thiserror::Error)]
#[error("Unable to decrypt onion service descriptor.")]
pub struct DecryptionError {}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_duration_subtraction)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn roundtrip_basics() {
let blinded_id = [7; 32].into();
let subcredential = [11; 32].into();
let revision = 13.into();
let string_const = "greetings puny humans";
let params = HsDescEncryption {
blinded_id: &blinded_id,
desc_enc_nonce: None,
subcredential: &subcredential,
revision,
string_const: string_const.as_bytes(),
};
let mut rng = testing_rng();
let bigmsg: Vec<u8> = (1..123).cycle().take(1021).collect();
for message in [&b""[..], &b"hello world"[..], &bigmsg[..]] {
let mut encrypted = params.encrypt(&mut rng, message);
assert_eq!(encrypted.len(), message.len() + 48);
let decrypted = params.decrypt(&encrypted[..]).unwrap();
assert_eq!(message, &decrypted);
let decryption_err = params.decrypt(&encrypted[..encrypted.len() - 1]);
assert!(decryption_err.is_err());
encrypted[7] ^= 3;
let decryption_err = params.decrypt(&encrypted[..]);
assert!(decryption_err.is_err());
}
}
#[test]
fn too_short() {
let blinded_id = [7; 32].into();
let subcredential = [11; 32].into();
let revision = 13.into();
let string_const = "greetings puny humans";
let params = HsDescEncryption {
blinded_id: &blinded_id,
desc_enc_nonce: None,
subcredential: &subcredential,
revision,
string_const: string_const.as_bytes(),
};
assert!(params.decrypt(b"").is_err());
assert!(params.decrypt(&[0_u8; 47]).is_err());
}
}