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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use digest::XofReader;
use once_cell::sync::Lazy;
use tor_hscrypto::pk::{HsBlindId, HsClientDescEncSecretKey, HsSvcDescEncKey};
use tor_hscrypto::{RevisionCounter, Subcredential};
use tor_llcrypto::pk::curve25519;
use tor_llcrypto::util::ct::CtByteArray;
use crate::parse::tokenize::{Item, NetDocReader};
use crate::parse::{keyword::Keyword, parser::SectionRules};
use crate::types::misc::B64;
use crate::{Pos, Result};
use super::desc_enc::{HsDescEncNonce, HsDescEncryption};
use super::DecryptionError;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
pub(super) struct HsDescMiddle {
svc_desc_enc_key: HsSvcDescEncKey,
auth_clients: Vec<AuthClient>,
encrypted: Vec<u8>,
}
impl HsDescMiddle {
#[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
pub(super) fn decrypt_inner(
&self,
blinded_id: &HsBlindId,
revision: RevisionCounter,
subcredential: &Subcredential,
key: Option<&HsClientDescEncSecretKey>,
) -> std::result::Result<Vec<u8>, DecryptionError> {
let desc_enc_nonce = key.and_then(|k| self.find_cookie(subcredential, k));
let decrypt = HsDescEncryption {
blinded_id,
desc_enc_nonce: desc_enc_nonce.as_ref(),
subcredential,
revision,
string_const: b"hsdir-encrypted-data",
};
decrypt.decrypt(&self.encrypted)
}
fn find_cookie(
&self,
subcredential: &Subcredential,
ks_hsc_desc_enc: &HsClientDescEncSecretKey,
) -> Option<HsDescEncNonce> {
use cipher::{KeyIvInit, StreamCipher};
use digest::{ExtendableOutput, Update};
use tor_llcrypto::cipher::aes::Aes256Ctr as Cipher;
use tor_llcrypto::d::Shake256 as KDF;
let secret_seed = ks_hsc_desc_enc
.as_ref()
.diffie_hellman(&self.svc_desc_enc_key);
let mut kdf = KDF::default();
kdf.update(subcredential.as_ref());
kdf.update(secret_seed.as_bytes());
let mut keys = kdf.finalize_xof();
let mut client_id = CtByteArray::from([0_u8; 8]);
let mut cookie_key = [0_u8; 32];
keys.read(client_id.as_mut());
keys.read(&mut cookie_key);
let auth_client = self
.auth_clients
.iter()
.find(|c| c.client_id == client_id)?;
let mut cookie = auth_client.encrypted_cookie;
let mut cipher = Cipher::new(&cookie_key.into(), &auth_client.iv.into());
cipher.apply_keystream(&mut cookie);
Some(cookie.into())
}
}
#[derive(Debug, Clone)]
struct AuthClient {
client_id: CtByteArray<8>,
iv: [u8; 16],
encrypted_cookie: [u8; 16],
}
impl AuthClient {
fn from_item(item: &Item<'_, HsMiddleKwd>) -> Result<Self> {
use crate::ParseErrorKind as EK;
if item.kwd() != HsMiddleKwd::AUTH_CLIENT {
return Err(EK::Internal.with_msg("called with invalid argument."));
}
let client_id = item.parse_arg::<B64>(0)?.into_array()?.into();
let iv = item.parse_arg::<B64>(1)?.into_array()?;
let encrypted_cookie = item.parse_arg::<B64>(2)?.into_array()?;
Ok(AuthClient {
client_id,
iv,
encrypted_cookie,
})
}
}
decl_keyword! {
HsMiddleKwd {
"desc-auth-type" => DESC_AUTH_TYPE,
"desc-auth-ephemeral-key" => DESC_AUTH_EPHEMERAL_KEY,
"auth-client" => AUTH_CLIENT,
"encrypted" => ENCRYPTED,
}
}
static HS_MIDDLE_RULES: Lazy<SectionRules<HsMiddleKwd>> = Lazy::new(|| {
use HsMiddleKwd::*;
let mut rules = SectionRules::builder();
rules.add(DESC_AUTH_TYPE.rule().required().args(1..));
rules.add(DESC_AUTH_EPHEMERAL_KEY.rule().required().args(1..));
rules.add(AUTH_CLIENT.rule().required().may_repeat().args(3..));
rules.add(ENCRYPTED.rule().required().obj_required());
rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
rules.build()
});
impl HsDescMiddle {
#[cfg_attr(feature = "hsdesc-inner-docs", visibility::make(pub))]
pub(super) fn parse(s: &str) -> Result<HsDescMiddle> {
let mut reader = NetDocReader::new(s);
let result = HsDescMiddle::take_from_reader(&mut reader).map_err(|e| e.within(s))?;
Ok(result)
}
fn take_from_reader(reader: &mut NetDocReader<'_, HsMiddleKwd>) -> Result<HsDescMiddle> {
use crate::ParseErrorKind as EK;
use HsMiddleKwd::*;
let body = HS_MIDDLE_RULES.parse(reader)?;
{
let auth_type = body.required(DESC_AUTH_TYPE)?.required_arg(0)?;
if auth_type != "x25519" {
return Err(EK::BadDocumentVersion
.at_pos(Pos::at(auth_type))
.with_msg(format!("Unrecognized desc-auth-type {auth_type:?}")));
}
}
let ephemeral_key: HsSvcDescEncKey = {
let token = body.required(DESC_AUTH_EPHEMERAL_KEY)?;
let key = curve25519::PublicKey::from(token.parse_arg::<B64>(0)?.into_array()?);
key.into()
};
let auth_clients: Vec<AuthClient> = body
.slice(AUTH_CLIENT)
.iter()
.map(AuthClient::from_item)
.collect::<Result<Vec<_>>>()?;
let encrypted_body: Vec<u8> = body.required(ENCRYPTED)?.obj("MESSAGE")?;
Ok(HsDescMiddle {
svc_desc_enc_key: ephemeral_key,
auth_clients,
encrypted: encrypted_body,
})
}
}
#[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 tor_checkable::{SelfSigned, Timebound};
use super::*;
use crate::doc::hsdesc::{
outer::HsDescOuter,
test::{TEST_DATA, TEST_SUBCREDENTIAL},
};
#[test]
fn parse_good() -> Result<()> {
let desc = HsDescOuter::parse(TEST_DATA)?
.dangerously_assume_wellsigned()
.dangerously_assume_timely();
let subcred = TEST_SUBCREDENTIAL.into();
let body = desc.decrypt_body(&subcred).unwrap();
let body = std::str::from_utf8(&body[..]).unwrap();
let middle = HsDescMiddle::parse(body)?;
let inner_body = middle
.decrypt_inner(&desc.blinded_id(), desc.revision_counter(), &subcred, None)
.unwrap();
Ok(())
}
}