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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use rand::Rng;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use crate::path::{dirpath::DirPathBuilder, exitpath::ExitPathBuilder, TorPath};
use tor_guardmgr::{GuardMgr, GuardMonitor, GuardUsable};
use tor_netdir::Relay;
use tor_netdoc::types::policy::PortPolicy;
use tor_rtcompat::Runtime;
use crate::{Error, Result};
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ExitPolicy {
v4: Arc<PortPolicy>,
v6: Arc<PortPolicy>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TargetPort {
ipv6: bool,
port: u16,
}
impl TargetPort {
pub fn ipv4(port: u16) -> TargetPort {
TargetPort { ipv6: false, port }
}
pub fn ipv6(port: u16) -> TargetPort {
TargetPort { ipv6: true, port }
}
pub fn is_supported_by(&self, r: &tor_netdir::Relay<'_>) -> bool {
if self.ipv6 {
r.supports_exit_port_ipv6(self.port)
} else {
r.supports_exit_port_ipv4(self.port)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IsolationToken(u64);
#[allow(clippy::new_without_default)]
impl IsolationToken {
pub fn new() -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(1);
let token = COUNTER.fetch_add(1, Ordering::Relaxed);
assert!(token < u64::MAX);
IsolationToken(token)
}
pub fn no_isolation() -> Self {
IsolationToken(0)
}
}
#[derive(Copy, Clone, Eq, Debug, PartialEq, derive_builder::Builder)]
pub struct StreamIsolation {
#[builder(default = "IsolationToken::no_isolation()")]
stream_token: IsolationToken,
#[builder(default = "IsolationToken::no_isolation()")]
owner_token: IsolationToken,
}
impl StreamIsolation {
pub fn no_isolation() -> Self {
StreamIsolationBuilder::new()
.build()
.expect("Bug constructing StreamIsolation")
}
pub fn builder() -> StreamIsolationBuilder {
StreamIsolationBuilder::new()
}
}
impl StreamIsolationBuilder {
pub fn new() -> Self {
StreamIsolationBuilder::default()
}
}
impl ExitPolicy {
pub(crate) fn from_relay(relay: &Relay<'_>) -> Self {
Self {
v4: relay.ipv4_policy(),
v6: relay.ipv6_policy(),
}
}
fn allows_port(&self, p: TargetPort) -> bool {
let policy = if p.ipv6 { &self.v6 } else { &self.v4 };
policy.allows_port(p.port)
}
fn allows_some_port(&self) -> bool {
self.v4.allows_some_port() || self.v6.allows_some_port()
}
}
#[derive(Clone, Debug)]
pub(crate) enum TargetCircUsage {
Dir,
Exit {
ports: Vec<TargetPort>,
isolation: StreamIsolation,
},
TimeoutTesting,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum SupportedCircUsage {
Dir,
Exit {
policy: ExitPolicy,
isolation: Option<StreamIsolation>,
},
NoUsage,
}
impl TargetCircUsage {
pub(crate) fn build_path<'a, R: Rng, RT: Runtime>(
&self,
rng: &mut R,
netdir: crate::DirInfo<'a>,
guards: Option<&GuardMgr<RT>>,
config: &crate::PathConfig,
) -> Result<(
TorPath<'a>,
SupportedCircUsage,
Option<GuardMonitor>,
Option<GuardUsable>,
)> {
match self {
TargetCircUsage::Dir => {
let (path, mon, usable) = DirPathBuilder::new().pick_path(rng, netdir, guards)?;
Ok((path, SupportedCircUsage::Dir, mon, usable))
}
TargetCircUsage::Exit {
ports: p,
isolation,
} => {
let (path, mon, usable) = ExitPathBuilder::from_target_ports(p.clone())
.pick_path(rng, netdir, guards, config)?;
let policy = path
.exit_policy()
.expect("ExitPathBuilder gave us a one-hop circuit?");
Ok((
path,
SupportedCircUsage::Exit {
policy,
isolation: Some(*isolation),
},
mon,
usable,
))
}
TargetCircUsage::TimeoutTesting => {
let (path, mon, usable) = ExitPathBuilder::for_timeout_testing()
.pick_path(rng, netdir, guards, config)?;
let policy = path.exit_policy();
let usage = match policy {
Some(policy) if policy.allows_some_port() => SupportedCircUsage::Exit {
policy,
isolation: None,
},
_ => SupportedCircUsage::NoUsage,
};
Ok((path, usage, mon, usable))
}
}
}
}
impl crate::mgr::AbstractSpec for SupportedCircUsage {
type Usage = TargetCircUsage;
fn supports(&self, target: &TargetCircUsage) -> bool {
use SupportedCircUsage::*;
match (self, target) {
(Dir, TargetCircUsage::Dir) => true,
(
Exit {
policy: p1,
isolation: i1,
},
TargetCircUsage::Exit {
ports: p2,
isolation: i2,
},
) => {
i1.map(|i1| i1 == *i2).unwrap_or(true)
&& p2.iter().all(|port| p1.allows_port(*port))
}
(Exit { .. } | NoUsage, TargetCircUsage::TimeoutTesting) => true,
(_, _) => false,
}
}
fn restrict_mut(&mut self, usage: &TargetCircUsage) -> Result<()> {
use SupportedCircUsage::*;
match (self, usage) {
(Dir, TargetCircUsage::Dir) => Ok(()),
(
Exit {
isolation: ref mut i1,
..
},
TargetCircUsage::Exit { isolation: i2, .. },
) if i1.map(|i1| i1 == *i2).unwrap_or(true) => {
*i1 = Some(*i2);
Ok(())
}
(Exit { .. }, TargetCircUsage::Exit { .. }) => {
Err(Error::UsageNotSupported("Bad isolation".into()))
}
(Exit { .. } | NoUsage, TargetCircUsage::TimeoutTesting) => Ok(()),
(_, _) => Err(Error::UsageNotSupported("Incompatible usage".into())),
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::test::OptDummyGuardMgr;
use tor_netdir::testnet;
#[test]
fn exit_policy() {
let network = testnet::construct_netdir()
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let id_noexit = [0x05; 32].into();
let id_webexit = [0x11; 32].into();
let id_fullexit = [0x20; 32].into();
let not_exit = network.by_id(&id_noexit).unwrap();
let web_exit = network.by_id(&id_webexit).unwrap();
let full_exit = network.by_id(&id_fullexit).unwrap();
let ep_none = ExitPolicy::from_relay(¬_exit);
let ep_web = ExitPolicy::from_relay(&web_exit);
let ep_full = ExitPolicy::from_relay(&full_exit);
assert!(!ep_none.allows_port(TargetPort::ipv4(80)));
assert!(!ep_none.allows_port(TargetPort::ipv4(9999)));
assert!(ep_web.allows_port(TargetPort::ipv4(80)));
assert!(ep_web.allows_port(TargetPort::ipv4(443)));
assert!(!ep_web.allows_port(TargetPort::ipv4(9999)));
assert!(ep_full.allows_port(TargetPort::ipv4(80)));
assert!(ep_full.allows_port(TargetPort::ipv4(443)));
assert!(ep_full.allows_port(TargetPort::ipv4(9999)));
assert!(!ep_none.allows_port(TargetPort::ipv6(80)));
assert!(!ep_web.allows_port(TargetPort::ipv6(80)));
assert!(!ep_full.allows_port(TargetPort::ipv6(80)));
assert!(TargetPort::ipv4(80).is_supported_by(&web_exit));
assert!(!TargetPort::ipv6(80).is_supported_by(&web_exit));
}
#[test]
fn usage_ops() {
use crate::mgr::AbstractSpec;
let policy = ExitPolicy {
v4: Arc::new("accept 80,443".parse().unwrap()),
v6: Arc::new("accept 23".parse().unwrap()),
};
let tok1 = IsolationToken::new();
let tok2 = IsolationToken::new();
let isolation = StreamIsolationBuilder::new()
.owner_token(tok1)
.build()
.unwrap();
let isolation2 = StreamIsolationBuilder::new()
.owner_token(tok2)
.build()
.unwrap();
let supp_dir = SupportedCircUsage::Dir;
let targ_dir = TargetCircUsage::Dir;
let supp_exit = SupportedCircUsage::Exit {
policy: policy.clone(),
isolation: Some(isolation),
};
let supp_exit_iso2 = SupportedCircUsage::Exit {
policy: policy.clone(),
isolation: Some(isolation2),
};
let supp_exit_no_iso = SupportedCircUsage::Exit {
policy,
isolation: None,
};
let targ_80_v4 = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80)],
isolation,
};
let targ_80_v4_iso2 = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80)],
isolation: isolation2,
};
let targ_80_23_v4 = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80), TargetPort::ipv4(23)],
isolation,
};
let targ_80_23_mixed = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80), TargetPort::ipv6(23)],
isolation,
};
let targ_999_v6 = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv6(999)],
isolation,
};
assert!(supp_dir.supports(&targ_dir));
assert!(!supp_dir.supports(&targ_80_v4));
assert!(!supp_exit.supports(&targ_dir));
assert!(supp_exit.supports(&targ_80_v4));
assert!(!supp_exit.supports(&targ_80_v4_iso2));
assert!(supp_exit.supports(&targ_80_23_mixed));
assert!(!supp_exit.supports(&targ_80_23_v4));
assert!(!supp_exit.supports(&targ_999_v6));
assert!(!supp_exit_iso2.supports(&targ_80_v4));
assert!(supp_exit_iso2.supports(&targ_80_v4_iso2));
assert!(supp_exit_no_iso.supports(&targ_80_v4));
assert!(supp_exit_no_iso.supports(&targ_80_v4_iso2));
assert!(!supp_exit_no_iso.supports(&targ_80_23_v4));
}
#[test]
fn restrict_mut() {
use crate::mgr::AbstractSpec;
let policy = ExitPolicy {
v4: Arc::new("accept 80,443".parse().unwrap()),
v6: Arc::new("accept 23".parse().unwrap()),
};
let tok1 = IsolationToken::new();
let tok2 = IsolationToken::new();
let isolation = StreamIsolationBuilder::new()
.owner_token(tok1)
.build()
.unwrap();
let isolation2 = StreamIsolationBuilder::new()
.owner_token(tok2)
.build()
.unwrap();
let supp_dir = SupportedCircUsage::Dir;
let targ_dir = TargetCircUsage::Dir;
let supp_exit = SupportedCircUsage::Exit {
policy: policy.clone(),
isolation: Some(isolation),
};
let supp_exit_iso2 = SupportedCircUsage::Exit {
policy: policy.clone(),
isolation: Some(isolation2),
};
let supp_exit_no_iso = SupportedCircUsage::Exit {
policy,
isolation: None,
};
let targ_exit = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80)],
isolation,
};
let targ_exit_iso2 = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(80)],
isolation: isolation2,
};
let mut supp_dir_c = supp_dir.clone();
assert!(supp_dir_c.restrict_mut(&targ_exit).is_err());
assert_eq!(supp_dir, supp_dir_c);
let mut supp_exit_c = supp_exit.clone();
assert!(supp_exit_c.restrict_mut(&targ_dir).is_err());
assert_eq!(supp_exit, supp_exit_c);
let mut supp_exit_c = supp_exit.clone();
assert!(supp_exit_c.restrict_mut(&targ_exit_iso2).is_err());
assert_eq!(supp_exit, supp_exit_c);
let mut supp_exit_iso2_c = supp_exit_iso2.clone();
assert!(supp_exit_iso2_c.restrict_mut(&targ_exit).is_err());
assert_eq!(supp_exit_iso2, supp_exit_iso2_c);
let mut supp_dir_c = supp_dir.clone();
supp_dir_c.restrict_mut(&targ_dir).unwrap();
assert_eq!(supp_dir, supp_dir_c);
let mut supp_exit_c = supp_exit.clone();
supp_exit_c.restrict_mut(&targ_exit).unwrap();
assert_eq!(supp_exit, supp_exit_c);
let mut supp_exit_iso2_c = supp_exit_iso2.clone();
supp_exit_iso2_c.restrict_mut(&targ_exit_iso2).unwrap();
assert_eq!(supp_exit_iso2, supp_exit_iso2_c);
let mut supp_exit_no_iso_c = supp_exit_no_iso.clone();
supp_exit_no_iso_c.restrict_mut(&targ_exit).unwrap();
assert!(supp_exit_no_iso_c.supports(&targ_exit));
assert!(!supp_exit_no_iso_c.supports(&targ_exit_iso2));
let mut supp_exit_no_iso_c = supp_exit_no_iso;
supp_exit_no_iso_c.restrict_mut(&targ_exit_iso2).unwrap();
assert!(!supp_exit_no_iso_c.supports(&targ_exit));
assert!(supp_exit_no_iso_c.supports(&targ_exit_iso2));
}
#[test]
fn buildpath() {
use crate::mgr::AbstractSpec;
let mut rng = rand::thread_rng();
let netdir = testnet::construct_netdir()
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let di = (&netdir).into();
let config = crate::PathConfig::default();
let guards: OptDummyGuardMgr<'_> = None;
let (p_dir, u_dir, _, _) = TargetCircUsage::Dir
.build_path(&mut rng, di, guards, &config)
.unwrap();
assert!(matches!(u_dir, SupportedCircUsage::Dir));
assert_eq!(p_dir.len(), 1);
let tok1 = IsolationToken::new();
let isolation = StreamIsolationBuilder::new()
.owner_token(tok1)
.build()
.unwrap();
let exit_usage = TargetCircUsage::Exit {
ports: vec![TargetPort::ipv4(995)],
isolation,
};
let (p_exit, u_exit, _, _) = exit_usage
.build_path(&mut rng, di, guards, &config)
.unwrap();
assert!(matches!(
u_exit,
SupportedCircUsage::Exit {
isolation: iso,
..
} if iso == Some(isolation)
));
assert!(u_exit.supports(&exit_usage));
assert_eq!(p_exit.len(), 3);
}
}