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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
mod inner;
mod middle;
mod outer;
use crate::doc::hsdesc::IntroAuthType;
use crate::NetdocBuilder;
use rand::{CryptoRng, RngCore};
use tor_bytes::EncodeError;
use tor_error::into_bad_api_usage;
use tor_hscrypto::pk::{HsBlindKeypair, HsSvcDescEncKey};
use tor_hscrypto::{RevisionCounter, Subcredential};
use tor_llcrypto::pk::ed25519::{self, Ed25519PublicKey};
use tor_units::IntegerMinutes;
use derive_builder::Builder;
use smallvec::SmallVec;
use std::borrow::{Borrow, Cow};
use std::time::SystemTime;
use self::inner::{HsDescInner, IntroPointDesc};
use self::middle::HsDescMiddle;
use self::outer::HsDescOuter;
use super::desc_enc::{HsDescEncNonce, HsDescEncryption, HS_DESC_ENC_NONCE_LEN};
use super::middle::AuthClient;
#[derive(Builder)]
#[builder(public, derive(Debug), pattern = "owned", build_fn(vis = ""))]
struct HsDesc<'a> {
blinded_id: &'a HsBlindKeypair,
hs_desc_sign: &'a ed25519::Keypair,
hs_desc_sign_cert_expiry: SystemTime,
create2_formats: &'a [u32],
auth_required: Option<SmallVec<[IntroAuthType; 2]>>,
is_single_onion_service: bool,
intro_points: &'a [IntroPointDesc],
intro_auth_key_cert_expiry: SystemTime,
intro_enc_key_cert_expiry: SystemTime,
client_auth: Option<&'a ClientAuth>,
lifetime: IntegerMinutes<u16>,
revision_counter: RevisionCounter,
subcredential: Subcredential,
}
#[derive(Clone, Debug)]
pub struct ClientAuth {
pub ephemeral_key: HsSvcDescEncKey,
pub auth_clients: Vec<AuthClient>,
pub descriptor_cookie: [u8; HS_DESC_ENC_NONCE_LEN],
}
impl<'a> NetdocBuilder for HsDescBuilder<'a> {
fn build_sign<R: RngCore + CryptoRng>(self, rng: &mut R) -> Result<String, EncodeError> {
const SUPERENCRYPTED_ALIGN: usize = 10 * (1 << 10);
let hs_desc = self
.build()
.map_err(into_bad_api_usage!("the HsDesc could not be built"))?;
let inner_plaintext = HsDescInner {
hs_desc_sign: hs_desc.hs_desc_sign,
create2_formats: hs_desc.create2_formats,
auth_required: hs_desc.auth_required.as_ref(),
is_single_onion_service: hs_desc.is_single_onion_service,
intro_points: hs_desc.intro_points,
intro_auth_key_cert_expiry: hs_desc.intro_auth_key_cert_expiry,
intro_enc_key_cert_expiry: hs_desc.intro_enc_key_cert_expiry,
}
.build_sign(rng)?;
let desc_enc_nonce = hs_desc
.client_auth
.as_ref()
.map(|client_auth| client_auth.descriptor_cookie.into());
let inner_encrypted = hs_desc.encrypt_field(
rng,
inner_plaintext.as_bytes(),
desc_enc_nonce.as_ref(),
b"hsdir-encrypted-data",
);
let middle_plaintext = HsDescMiddle {
client_auth: hs_desc.client_auth,
encrypted: inner_encrypted,
}
.build_sign(rng)?;
let middle_plaintext =
pad_with_zero_to_align(middle_plaintext.as_bytes(), SUPERENCRYPTED_ALIGN);
let middle_encrypted = hs_desc.encrypt_field(
rng,
middle_plaintext.borrow(),
None,
b"hsdir-superencrypted-data",
);
HsDescOuter {
blinded_id: hs_desc.blinded_id,
hs_desc_sign: hs_desc.hs_desc_sign,
hs_desc_sign_cert_expiry: hs_desc.hs_desc_sign_cert_expiry,
lifetime: hs_desc.lifetime,
revision_counter: hs_desc.revision_counter,
superencrypted: middle_encrypted,
}
.build_sign(rng)
}
}
impl<'a> HsDesc<'a> {
fn encrypt_field<R: RngCore + CryptoRng>(
&self,
rng: &mut R,
plaintext: &[u8],
desc_enc_nonce: Option<&HsDescEncNonce>,
string_const: &[u8],
) -> Vec<u8> {
let encrypt = HsDescEncryption {
blinded_id: &ed25519::Ed25519Identity::from(self.blinded_id.public_key()).into(),
desc_enc_nonce,
subcredential: &self.subcredential,
revision: self.revision_counter,
string_const,
};
encrypt.encrypt(rng, plaintext)
}
}
fn pad_with_zero_to_align(v: &[u8], alignment: usize) -> Cow<[u8]> {
let padding = (alignment - (v.len() % alignment)) % alignment;
if padding > 0 {
let padded = v
.iter()
.copied()
.chain(std::iter::repeat(0).take(padding))
.collect::<Vec<_>>();
Cow::Owned(padded)
} else {
Cow::Borrowed(v)
}
}
#[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 std::net::Ipv4Addr;
use std::time::Duration;
use super::*;
use crate::doc::hsdesc::{EncryptedHsDesc, HsDesc as HsDescDecoder};
use tor_basic_utils::test_rng::Config;
use tor_checkable::{SelfSigned, Timebound};
use tor_hscrypto::pk::HsIdSecretKey;
use tor_hscrypto::time::TimePeriod;
use tor_linkspec::LinkSpec;
use tor_llcrypto::pk::curve25519;
use tor_llcrypto::pk::keymanip::ExpandedSecretKey;
use tor_llcrypto::util::rand_compat::RngCompatExt;
pub(super) const TEST_DESCRIPTOR_COOKIE: [u8; HS_DESC_ENC_NONCE_LEN] =
[1; HS_DESC_ENC_NONCE_LEN];
pub(super) fn expect_bug(err: EncodeError) -> String {
match err {
EncodeError::Bug(b) => b.to_string(),
EncodeError::BadLengthValue => panic!("expected Bug, got BadLengthValue"),
_ => panic!("expected Bug, got unknown error"),
}
}
pub(super) fn create_intro_point_descriptor<R: RngCore + CryptoRng>(
rng: &mut R,
link_specifiers: Vec<LinkSpec>,
) -> IntroPointDesc {
IntroPointDesc {
link_specifiers,
ipt_ntor_key: create_curve25519_pk(rng),
ipt_sid_key: ed25519::Keypair::generate(&mut rng.rng_compat())
.public
.into(),
svc_ntor_key: create_curve25519_pk(rng).into(),
}
}
pub(super) fn create_curve25519_pk<R: RngCore + CryptoRng>(
rng: &mut R,
) -> curve25519::PublicKey {
let ephemeral_key = curve25519::EphemeralSecret::new(rng);
(&ephemeral_key).into()
}
#[test]
fn encode_decode() {
let mut rng = Config::Deterministic.into_rng().rng_compat();
let hs_id = ed25519::Keypair::generate(&mut rng);
let hs_desc_sign = ed25519::Keypair::generate(&mut rng);
let period = TimePeriod::new(
humantime::parse_duration("24 hours").unwrap(),
humantime::parse_rfc3339("2023-02-09T12:00:00Z").unwrap(),
humantime::parse_duration("12 hours").unwrap(),
)
.unwrap();
let (public, secret, subcredential) =
HsIdSecretKey::from(ExpandedSecretKey::from(&hs_id.secret))
.compute_blinded_key(period)
.unwrap();
let blinded_id = HsBlindKeypair { public, secret };
let create2_formats = &[1, 2];
let expiry = SystemTime::now() + Duration::from_secs(60 * 60);
let mut rng = Config::Deterministic.into_rng().rng_compat();
let intro_points = vec![IntroPointDesc {
link_specifiers: vec![LinkSpec::OrPort(Ipv4Addr::LOCALHOST.into(), 9999)],
ipt_ntor_key: create_curve25519_pk(&mut rng),
ipt_sid_key: ed25519::Keypair::generate(&mut rng).public.into(),
svc_ntor_key: create_curve25519_pk(&mut rng).into(),
}];
let encoded_desc = HsDescBuilder::default()
.blinded_id(&blinded_id)
.hs_desc_sign(&hs_desc_sign)
.hs_desc_sign_cert_expiry(expiry)
.create2_formats(create2_formats)
.auth_required(None)
.is_single_onion_service(true)
.intro_points(&intro_points)
.intro_auth_key_cert_expiry(expiry)
.intro_enc_key_cert_expiry(expiry)
.client_auth(None)
.lifetime(100.into())
.revision_counter(2.into())
.subcredential(subcredential)
.build_sign(&mut Config::Deterministic.into_rng())
.unwrap();
let id = ed25519::Ed25519Identity::from(blinded_id.public_key());
let enc_desc: EncryptedHsDesc = HsDescDecoder::parse(&encoded_desc, &id.into())
.unwrap()
.check_signature()
.unwrap()
.check_valid_at(&humantime::parse_rfc3339("2023-01-23T15:00:00Z").unwrap())
.unwrap();
let desc = enc_desc
.decrypt(&subcredential, None)
.unwrap()
.check_valid_at(&humantime::parse_rfc3339("2023-01-23T15:00:00Z").unwrap())
.unwrap()
.check_signature()
.unwrap();
let reencoded_desc = HsDescBuilder::default()
.blinded_id(&blinded_id)
.hs_desc_sign(&hs_desc_sign)
.hs_desc_sign_cert_expiry(expiry)
.create2_formats(create2_formats)
.auth_required(None)
.is_single_onion_service(desc.is_single_onion_service)
.intro_points(&intro_points)
.intro_auth_key_cert_expiry(expiry)
.intro_enc_key_cert_expiry(expiry)
.client_auth(None)
.lifetime(desc.idx_info.lifetime)
.revision_counter(desc.idx_info.revision)
.subcredential(subcredential)
.build_sign(&mut Config::Deterministic.into_rng())
.unwrap();
assert_eq!(&*encoded_desc, &*reencoded_desc);
}
}