-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathsim_slim.py
3649 lines (3242 loc) · 182 KB
/
pathsim_slim.py
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import os
import os.path
from stem import Flag
from pathsim_metrics_nsf import *
from as_inference import *
from random import random, randint, choice
import sys
import collections
import cPickle as pickle
import argparse
from models import *
import congestion_aware_pathsim
import process_consensuses_slim
import re
import network_modifiers_slim
from network_modifiers_slim import *
import event_callbacks
import importlib
import logging
import pdb
import multiprocessing
import itertools
import urllib
import requests
import json
import operator
from as_customer_cone import compute_customer_cone
from subprocess import call
import numpy as np
logger = logging.getLogger(__name__)
_testing = False#True
class TorOptions:
"""Stores parameters set by Tor."""
# given by #define ROUTER_MAX_AGE (60*60*48) in or.h
router_max_age = 60*60*48
num_guards = 3
min_num_guards = 2
guard_expiration_min = 60*24*3600 # min time until guard removed from list
guard_expiration_max = 90*24*3600 # max time until guard removed from list
default_bwweightscale = 10000
# max age of a dirty circuit to which new streams can be assigned
# set by MaxCircuitDirtiness option in Tor (default: 10 min.)
max_circuit_dirtiness = 10*60
# max age of a clean circuit
# set by CircuitIdleTimeout in Tor (default: 60 min.)
circuit_idle_timeout = 60*60
# max number of preemptive clean circuits
# given with "#define MAX_UNUSED_OPEN_CIRCUITS 14" in Tor's circuituse.c
max_unused_open_circuits = 14
# long-lived ports (taken from path-spec.txt)
# including 6523, which was added in 0.2.4.12-alpha
long_lived_ports = [21, 22, 706, 1863, 5050, 5190, 5222, 5223, 6523, 6667,
6697, 8300]
# observed port creates a need active for a limited amount of time
# given with "#define PREDICTED_CIRCS_RELEVANCE_TIME 60*60" in rephist.c
# need expires after an hour
port_need_lifetime = 60*60
# time a guard can stay down until it is removed from list
# set by #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60) in entrynodes.c
guard_down_time = 30*24*60*60 # time guard can be down until is removed
# needs that apply to all samples
# min coverage given with "#define MIN_CIRCUITS_HANDLING_STREAM 2" in or.h
port_need_cover_num = 2
# number of times to attempt to find circuit with at least one NTor hop
# from #define MAX_POPULATE_ATTEMPTS 32 in circuicbuild.c
max_populate_attempts = 32
class NetworkState:
"""Contains Tor network state in a consensus period needed to run
simulation."""
def __init__(self, cons_valid_after, cons_fresh_until, cons_bw_weights,
cons_bwweightscale, cons_rel_stats, hibernating_statuses, descriptors):
self.cons_valid_after = cons_valid_after
self.cons_fresh_until = cons_fresh_until
self.cons_bw_weights = cons_bw_weights
self.cons_bwweightscale = cons_bwweightscale
self.cons_rel_stats = cons_rel_stats
self.hibernating_statuses = hibernating_statuses
self.descriptors = descriptors
class RouterStatusEntry:
"""
Represents a relay entry in a consensus document.
Slim version of stem.descriptor.router_status_entry.RouterStatusEntry.
"""
def __init__(self, fingerprint, flags, bandwidth, water_filling=False):
self.fingerprint = fingerprint
self.flags = flags
self.bandwidth = bandwidth
if water_filling:
self.wf_bw_weights = {} #contains water-filling weights
class NetworkStatusDocument:
"""
Represents a consensus document.
Slim version of stem.descriptor.networkstatus.NetworkStatusDocument.
"""
def __init__(self, valid_after, fresh_until, bandwidth_weights, \
bwweightscale, relays):
self.valid_after = valid_after
self.fresh_until = fresh_until
self.bandwidth_weights = bandwidth_weights
self.bwweightscale = bwweightscale
self.relays = relays
class ServerDescriptor:
"""
Represents a server descriptor.
Slim version of stem.descriptor.server_descriptor.ServerDescriptor combined
with stem.descriptor.server_descriptor.RelayDescriptor.
"""
def __init__(self, fingerprint, hibernating, address):
self.fingerprint = fingerprint
self.hibernating = hibernating
self.address = address
def __getstate__(self):
"""Used for headache-free pickling. Turns ExitPolicy into its string
representation, rather than using the repeatedly problematic object."""
state = dict()
state['fingerprint'] = self.fingerprint
state['hibernating'] = self.hibernating
state['address'] = self.address
return state
def __setstate__(self, state):
"""Used for headache-free unpickling. Creates ExitPolicy from string
representation."""
self.fingerprint = state['fingerprint']
self.hibernating = state['hibernating']
self.address = state['address']
def timestamp(t):
"""Returns UNIX timestamp"""
td = t - datetime.datetime(1970, 1, 1)
ts = td.days*24*60*60 + td.seconds
return ts
def pad_network_state_files(network_state_files):
"""Add hour-long gaps into files list where gaps exist in file times."""
nsf_date = None
network_state_files_padded = []
for nsf in network_state_files:
f_datenums = map(int, os.path.basename(nsf).split('-')[:-1])
new_nsf_date = datetime.datetime(f_datenums[0], f_datenums[1], f_datenums[2], f_datenums[3], f_datenums[4], f_datenums[5])
if (nsf_date != None):
td = new_nsf_date - nsf_date
if (int(td.total_seconds()) != 3600):
if (int(td.total_seconds()) % 3600 != 0):
raise ValueError('Gap between {0} and {1} not some number of hours.'.format(nsf_date, new_nsf_date))
if _testing:
print('Missing consensuses between {0} and {1}'.\
format(nsf_date, new_nsf_date))
num_missing_hours = int(td.total_seconds()/3600) - 1
for i in range(num_missing_hours):
network_state_files_padded.append(None)
network_state_files_padded.append(nsf)
else:
network_state_files_padded.append(nsf)
else:
network_state_files_padded.append(nsf)
nsf_date = new_nsf_date
return network_state_files_padded
def get_bw_weight(flags, position, bw_weights, water_filling=False, fprint=None,\
cons_rel_stats=None):
"""Returns weight to apply to relay's bandwidth for given position.
flags: list of Flag values for relay from a consensus
position: position for which to find selection weight,
one of 'g' for guard, 'm' for middle, and 'e' for exit
bw_weights: bandwidth_weights from NetworkStatusDocumentV3 consensus
"""
if (position == 'g'):
if (Flag.GUARD in flags) and (Flag.EXIT in flags):
if water_filling and 'Wgd' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wgd']
else:
return bw_weights['Wgd']
elif (Flag.GUARD in flags):
if water_filling and 'Wgg' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wgg']
else:
return bw_weights['Wgg']
elif (Flag.EXIT not in flags):
return bw_weights['Wgm']
else:
return 0
#raise ValueError('Wge weight does not exist.')
elif (position == 'm'):
if (Flag.GUARD in flags) and (Flag.EXIT in flags):
if water_filling and 'Wmd' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wmd']
else:
return bw_weights['Wmd']
elif (Flag.GUARD in flags):
if water_filling and 'Wmg' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wmg']
else:
return bw_weights['Wmg']
elif (Flag.EXIT in flags):
if water_filling and 'Wme' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wme']
else:
return bw_weights['Wme']
else:
return bw_weights['Wmm']
elif (position == 'e'):
if (Flag.GUARD in flags) and (Flag.EXIT in flags):
if water_filling and 'Wed' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wed']
else:
return bw_weights['Wed']
elif (Flag.GUARD in flags):
return bw_weights['Weg']
elif (Flag.EXIT in flags):
if water_filling and 'Wee' in cons_rel_stats[fprint].wf_bw_weights:
return cons_rel_stats[fprint].wf_bw_weights['Wee']
else:
return bw_weights['Wee']
else:
return bw_weights['Wem']
else:
raise ValueError('get_weight does not support position {0}.'.format(
position))
def select_weighted_node(weighted_nodes):
"""Takes (node,cum_weight) pairs where non-negative cum_weight increases,
ending at 1. Use cum_weights as cumulative probablity to select a node."""
r = random()
begin = 0
end = len(weighted_nodes)-1
mid = int((end+begin)/2)
while True:
if (r <= weighted_nodes[mid][1]):
if (mid == begin):
return weighted_nodes[mid][0]
else:
end = mid
mid = int((end+begin)/2)
else:
if (mid == end):
raise ValueError('Weights must sum to 1.')
else:
begin = mid+1
mid = int((end+begin)/2)
def might_exit_to_port(descriptor, port):
"""Returns if will exit to port for *some* ip.
Is conservative - never returns a false negative."""
for rule in descriptor.exit_policy:
if (port >= rule.min_port) and\
(port <= rule.max_port): # assumes full range for wildcard port
if rule.is_accept:
return True
else:
if (rule.is_address_wildcard()) or\
(rule.get_masked_bits() == 0):
return False
return True # default accept if no rule matches
def can_exit_to_port(descriptor, port):
"""Derived from compare_unknown_tor_addr_to_addr_policy() in policies.c.
That function returns ACCEPT, PROBABLY_ACCEPT, REJECT, and PROBABLY_REJECT.
We ignore the PRABABLY status, as is done by Tor in the uses of
compare_unknown_tor_addr_to_addr_policy() that we care about."""
for rule in descriptor.exit_policy:
if (port >= rule.min_port) and\
(port <= rule.max_port): # assumes full range for wildcard port
if (rule.is_address_wildcard()) or\
(rule.get_masked_bits() == 0):
if rule.is_accept:
return True
else:
return False
return True # default accept if no rule matches
def policy_is_reject_star(exit_policy):
"""Replicates Tor function of same name in policies.c."""
for rule in exit_policy:
if rule.is_accept:
return False
elif (((rule.min_port <= 1) and (rule.max_port == 65535)) or\
(rule.is_port_wildcard())) and\
((rule.is_address_wildcard()) or (rule.get_masked_bits == 0)):
return True
return True
def exit_filter(exit, cons_rel_stats, descriptors, fast, stable, internal, ip,\
port, loose):
"""Applies the criteria for choosing a relay as an exit.
If internal, doesn't consider exit policy.
If IP and port given, simply applies exit policy.
If just port given, guess as Tor does, with the option to be slightly more
loose than Tor and avoid false negatives (via loose=True).
If IP and port not given, check policy for any allowed exiting. This
behavior is for SOCKS RESOLVE requests in particular."""
rel_stat = cons_rel_stats[exit]
desc = descriptors[exit]
if (Flag.BADEXIT not in rel_stat.flags) and\
(Flag.RUNNING in rel_stat.flags) and\
(Flag.VALID in rel_stat.flags) and\
((not fast) or (Flag.FAST in rel_stat.flags)) and\
((not stable) or (Flag.STABLE in rel_stat.flags)):
if (internal):
# In an "internal" circuit final node is chosen just like a
# middle node (ignoring its exit policy).
return True
elif (ip != None):
return desc.exit_policy.can_exit_to(ip, port)
elif (port != None):
if (not loose):
return can_exit_to_port(desc, port)
else:
return might_exit_to_port(desc, port)
else:
return (not policy_is_reject_star(desc.exit_policy))
def filter_exits(cons_rel_stats, descriptors, fast, stable, internal, ip,\
port):
"""Applies exit filter to relays."""
exits = []
for fprint in cons_rel_stats:
if exit_filter(fprint, cons_rel_stats, descriptors, fast, stable,\
internal, ip, port, False):
exits.append(fprint)
return exits
def filter_exits_loose(cons_rel_stats, descriptors, fast, stable, internal,\
ip, port):
"""Applies loose exit filter to relays."""
exits = []
for fprint in cons_rel_stats:
if exit_filter(fprint, cons_rel_stats, descriptors, fast, stable,\
internal, ip, port, True):
exits.append(fprint)
return exits
def get_position_weights(nodes, cons_rel_stats, position, bw_weights,\
bwweightscale, water_filling=False):
"""Computes the consensus "bandwidth" weighted by position weights."""
weights = {}
for node in nodes:
bw = float(cons_rel_stats[node].bandwidth)
if water_filling:
weight = float(get_bw_weight(cons_rel_stats[node].flags,\
position,bw_weights, water_filling, node, cons_rel_stats))\
/ float(bwweightscale)
else:
weight = float(get_bw_weight(cons_rel_stats[node].flags,\
position,bw_weights)) / float(bwweightscale)
weights[node] = bw * weight
return weights
def get_weighted_nodes(nodes, weights):
"""Takes list of nodes (rel_stats) and weights (as a dict) and outputs
a list of (node, cum_weight) pairs, where cum_weight is the cumulative
probability of the nodes weighted by weights.
"""
# compute total weight
total_weight = 0
for node in nodes:
total_weight += weights[node]
if (total_weight == 0):
raise ValueError('ERROR: Node list has total weight zero.')
# create cumulative weights
weighted_nodes = []
cum_weight = 0
for node in nodes:
cum_weight += weights[node]/total_weight
weighted_nodes.append((node, cum_weight))
return weighted_nodes
def in_same_family(descriptors, node1, node2):
"""Takes list of descriptors and two node fingerprints,
checks if nodes list each other as in the same family."""
desc1 = descriptors[node1]
desc2 = descriptors[node2]
fprint1 = desc1.fingerprint
fprint2 = desc2.fingerprint
nick1 = desc1.nickname
nick2 = desc2.nickname
node1_lists_node2 = False
for member in desc1.family:
if ((member[0] == '$') and (member[1:] == fprint2)) or\
(member == nick2):
node1_lists_node2 = True
if (node1_lists_node2):
for member in desc2.family:
if ((member[0] == '$') and (member[1:] == fprint1)) or\
(member == nick1):
return True
return False
def in_same_16_subnet(address1, address2):
"""Takes IPv4 addresses as strings and checks if the first two bytes
are equal."""
# check first octet
i = 0
while (address1[i] != '.'):
if (address1[i] != address2[i]):
return False
i += 1
i += 1
while (address1[i] != '.'):
if (address1[i] != address2[i]):
return False
i += 1
return True
def middle_filter(node, cons_rel_stats, descriptors, fast=None,\
stable=None, exit_node=None, guard_node=None):
"""Return if candidate node is suitable as middle node. If an optional
argument is omitted, then the corresponding filter condition will be
skipped. This is useful for early filtering when some arguments are still
unknown."""
# Note that we intentionally allow non-Valid routers for middle
# as per path-spec.txt default config
rel_stat = cons_rel_stats[node]
return (Flag.RUNNING in rel_stat.flags) and\
((fast==None) or (not fast) or\
(Flag.FAST in rel_stat.flags)) and\
((stable==None) or (not stable) or\
(Flag.STABLE in rel_stat.flags)) and\
((exit_node==None) or\
((exit_node != node) and\
(not in_same_family(descriptors, exit_node, node)) and\
(not in_same_16_subnet(descriptors[exit_node].address,\
descriptors[node].address)))) and\
((guard_node==None) or\
((guard_node != node) and\
(not in_same_family(descriptors, guard_node, node)) and\
(not in_same_16_subnet(descriptors[guard_node].address,\
descriptors[node].address))))
def select_middle_node(bw_weights, bwweightscale, cons_rel_stats, descriptors,\
fast, stable, exit_node, guard_node, weighted_middles=None, water_filling=False):
"""Chooses a valid middle node by selecting randomly until one is found."""
# create weighted middles if not given
if (weighted_middles == None):
middles = cons_rel_stats.keys()
# create cumulative weighted middles
weights = get_position_weights(middles, cons_rel_stats, 'm',\
bw_weights, bwweightscale, water_filling)
weighted_middles = get_weighted_nodes(middles, weights)
# select randomly until acceptable middle node is found
i = 1
while True:
middle_node = select_weighted_node(weighted_middles)
if _testing:
print('select_middle_node() made choice #{0}.'.format(i))
i += 1
if (middle_filter(middle_node, cons_rel_stats, descriptors, fast,\
stable, exit_node, guard_node)):
break
return middle_node
def guard_is_time_to_retry(guard, time):
"""Tests if enough time has passed to retry an unreachable
(i.e. hibernating) guard. Derived from entry_is_time_to_retry() in
entrynodes.c."""
if (guard['last_attempted'] < guard['unreachable_since']):
return True
diff = time - guard['unreachable_since']
if (diff < 6*60*60):
return (time > (guard['last_attempted'] + 60*60))
elif (diff < 3*24*60*60):
return (time > (guard['last_attempted'] + 4*60*60))
elif (diff < 7*24*60*60):
return (time > (guard['last_attempted'] + 18*60*60))
else:
return (time > (guard['last_attempted'] + 36*60*60));
def guard_filter_for_circ(guard, cons_rel_stats, descriptors, fast,\
stable, exit, circ_time, guards):
"""Returns if guard is usable for circuit."""
# - liveness (given by entry_is_live() call in choose_random_entry_impl())
# - not bad_since
# - has descriptor (although should be ensured by create_circuits()
# - not unreachable_since
# - fast/stable
# - not same as exit
# - not in exit family
# - not in exit /16
# note that Valid flag not checked
# note that hibernate status not checked (only checks unreachable_since)
if (guards[guard]['bad_since'] == None):
if (guard in cons_rel_stats) and (guard in descriptors):
rel_stat = cons_rel_stats[guard]
return ((not fast) or (Flag.FAST in rel_stat.flags)) and\
((not stable) or (Flag.STABLE in rel_stat.flags)) and\
((guards[guard]['unreachable_since'] == None) or\
guard_is_time_to_retry(guards[guard],circ_time)) and\
(exit != guard) and\
(not in_same_family(descriptors, exit, guard)) and\
(not in_same_16_subnet(descriptors[exit].address,\
descriptors[guard].address))
else:
raise ValueError('Guard {0} not present in consensus or\ descriptors but wasn\'t marked bad.'.format(guard))
else:
return False
def filter_flags(cons_rel_stats, descriptors, flags, no_flags):
nodes = []
for fprint in cons_rel_stats:
rel_stat = cons_rel_stats[fprint]
i = 0
j=0
for flag in no_flags:
if flag in rel_stat.flags:
j+=1
for flag in flags:
if flag in rel_stat.flags:
i+=1
if i == len(flags) and j==0 and fprint in descriptors:
nodes.append(fprint)
return nodes
def filter_guards(cons_rel_stats, descriptors):
"""Returns relays filtered by general (non-client-specific) guard criteria.
In particular, omits checks for IP/family/subnet conflicts within list.
"""
guards = []
for fprint in cons_rel_stats:
rel_stat = cons_rel_stats[fprint]
if (Flag.RUNNING in rel_stat.flags) and\
(Flag.VALID in rel_stat.flags) and\
(Flag.GUARD in rel_stat.flags) and\
(fprint in descriptors):
guards.append(fprint)
return guards
def get_new_guard(bw_weights, bwweightscale, cons_rel_stats, descriptors,\
client_guards, weighted_guards=None, water_filling=False):
"""Selects a new guard that doesn't conflict with the existing list."""
# - doesn't conflict with current guards
# - running
# - valid
# - need guard
# - need descriptor, though should be ensured already by create_circuits()
# - not single hop relay
# follows add_an_entry_guard(NULL,0,0,for_directory) call which appears
# in pick_entry_guards() and more directly in choose_random_entry_impl()
if (weighted_guards == None):
# create weighted guards
guards = filter_guards(cons_rel_stats, descriptors)
guard_weights = get_position_weights(guards, cons_rel_stats,\
'g', bw_weights, bwweightscale, water_filling)
weighted_guards = get_weighted_nodes(guards, guard_weights)
# Because conflict with current guards is unlikely,
# randomly select a guard, test, and repeat if necessary
i = 1
while True:
guard_node = select_weighted_node(weighted_guards)
if _testing:
print('get_new_guard() made choice #{0}.'.format(i))
i += 1
guard_conflict = False
for client_guard in client_guards:
if (client_guard == guard_node) or\
(in_same_family(descriptors, client_guard, guard_node)) or\
(in_same_16_subnet(descriptors[client_guard].address,\
descriptors[guard_node].address)):
guard_conflict = True
break
if (not guard_conflict):
break
return guard_node
def get_guards_for_circ(bw_weights, bwweightscale, cons_rel_stats,\
descriptors, fast, stable, guards,\
exit,\
circ_time, weighted_guards=None, water_filling=False):
"""Obtains needed number of live guards that will work for circuit.
Chooses new guards if needed, and *modifies* guard list by adding them."""
# Get live guards then add new ones until TorOptions.num_guards reached,
# where live is
# - bad_since isn't set
# - unreachable_since isn't set without retry
# - has descriptor, though create_circuits should ensure descriptor exists
# Note that node need not have Valid flag to be live. As far as I can tell,
# a Valid flag is needed to be added to the guard list, but isn't needed
# after that point.
# Note that hibernating status is not an input here.
# Rules derived from Tor source: choose_random_entry_impl() in entrynodes.c
# add guards if not enough in list
if (len(guards) < TorOptions.num_guards):
# Oddly then only count the number of live ones
# Slightly depart from Tor code by not considering the circuit's
# fast or stable flags when finding live guards.
# Tor uses fixed Stable=False and Fast=True flags when calculating #
# live but fixed Stable=Fast=False when adding guards here (weirdly).
# (as in choose_random_entry_impl() and its pick_entry_guards() call)
live_guards = filter(lambda x: (guards[x]['bad_since']==None) and\
(x in descriptors) and\
((guards[x]['unreachable_since'] == None) or\
guard_is_time_to_retry(guards[x],circ_time)),\
guards)
for i in range(TorOptions.num_guards - len(live_guards)):
new_guard = get_new_guard(bw_weights, bwweightscale,\
cons_rel_stats, descriptors, guards,\
weighted_guards, water_filling)
if _testing:
print('Need guard. Adding {0} [{1}]'.format(\
cons_rel_stats[new_guard].nickname, new_guard))
expiration = randint(TorOptions.guard_expiration_min,\
TorOptions.guard_expiration_max)
guards[new_guard] = {'expires':(expiration+\
circ_time), 'bad_since':None, 'unreachable_since':None,\
'last_attempted':0, 'made_contact':False}
# check for guards that will work for this circuit
guards_for_circ = filter(lambda x: guard_filter_for_circ(x,\
cons_rel_stats, descriptors, fast, stable, exit, circ_time, guards),\
guards)
# add new guards while there aren't enough for this circuit
# adding is done without reference to the circuit - how Tor does it
while (len(guards_for_circ) < TorOptions.min_num_guards):
new_guard = get_new_guard(bw_weights, bwweightscale,\
cons_rel_stats, descriptors, guards,\
weighted_guards, water_filling)
if _testing:
print('Need guard for circuit. Adding {0} [{1}]'.format(\
cons_rel_stats[new_guard].nickname, new_guard))
expiration = randint(TorOptions.guard_expiration_min,\
TorOptions.guard_expiration_max)
guards[new_guard] = {'expires':(expiration+\
circ_time), 'bad_since':None, 'unreachable_since':None,\
'last_attempted':0, 'made_contact':False}
if (guard_filter_for_circ(new_guard, cons_rel_stats, descriptors,\
fast, stable, exit, circ_time, guards)):
guards_for_circ.append(new_guard)
# return first TorOptions.num_guards usable guards
return guards_for_circ[0:TorOptions.num_guards]
def circuit_covers_port_need(circuit, descriptors, port, need):
"""Returns if circuit satisfies a port need, ignoring the circuit
time and need expiration."""
return ((not need['fast']) or (circuit['fast'])) and\
((not need['stable']) or (circuit['stable'])) and\
(can_exit_to_port(descriptors[circuit['path'][-1]], port))
def circuit_supports_stream(circuit, stream, descriptors):
"""Returns if stream can run over circuit (which is assumed live)."""
if (stream['type'] == 'connect'):
if (stream['ip'] == None):
raise ValueError('Stream must have ip.')
if (stream['port'] == None):
raise ValueError('Stream must have port.')
desc = descriptors[circuit['path'][-1]]
if (desc.exit_policy.can_exit_to(stream['ip'], stream['port'])) and\
(not circuit['internal']) and\
((circuit['stable']) or\
(stream['port'] not in TorOptions.long_lived_ports)):
return True
else:
return False
elif (stream['type'] == 'resolve'):
desc = descriptors[circuit['path'][-1]]
if (not policy_is_reject_star(desc.exit_policy)) and\
(not circuit['internal']):
return True
else:
return False
else:
raise ValueError('ERROR: Unrecognized stream in \
circuit_supports_stream: {0}'.format(stream['type']))
def uncover_circuit_ports(circuit, port_needs_covered):
"""Reduces cover count for ports that circuit indicates it covers."""
for port in circuit['covering']:
if (port in port_needs_covered):
port_needs_covered[port] -= 1
if _testing:
print('Decreased cover count for port {0} to {1}.'.\
format(port, port_needs_covered[port]))
else:
raise ValueError('Port {0} not found in port_needs_covered'.\
format(port))
def kill_circuits_by_relay(client_state, relay_down_fn, msg):
"""Kill circuits with a relay that is down as judged by relay_down_fn."""
# go through dirty circuits
new_dirty_exit_circuits = collections.deque()
while(len(client_state['dirty_exit_circuits']) > 0):
circuit = client_state['dirty_exit_circuits'].popleft()
rel_down = None
for i in range(len(circuit['path'])):
relay = circuit['path'][i]
if relay_down_fn(relay):
rel_down = relay
break
if (rel_down == None):
new_dirty_exit_circuits.append(circuit)
else:
if (_testing):
print('Killing dirty circuit because {0} {1}.'.\
format(rel_down, msg))
client_state['dirty_exit_circuits'] = new_dirty_exit_circuits
# go through clean circuits
new_clean_exit_circuits = collections.deque()
while(len(client_state['clean_exit_circuits']) > 0):
circuit = client_state['clean_exit_circuits'].popleft()
rel_down = None
for i in range(len(circuit['path'])):
relay = circuit['path'][i]
if relay_down_fn(relay):
rel_down = relay
break
if (rel_down == None):
new_clean_exit_circuits.append(circuit)
else:
if (_testing):
print('Killing clean circuit because {0} {1}.'.\
format(rel_down, msg))
uncover_circuit_ports(circuit, client_state['port_needs_covered'])
client_state['clean_exit_circuits'] = new_clean_exit_circuits
def get_network_state(ns_file):
"""Reads in network state file, returns NetworkState object."""
if _testing:
print('Using file {0}'.format(ns_file))
cons_rel_stats = {}
with open(ns_file, 'r') as nsf:
consensus = pickle.load(nsf)
new_descriptors = pickle.load(nsf)
hibernating_statuses = pickle.load(nsf)
# set variables from consensus
cons_valid_after = timestamp(consensus.valid_after)
cons_fresh_until = timestamp(consensus.fresh_until)
cons_bw_weights = consensus.bandwidth_weights
if (consensus.bwweightscale == None):
cons_bwweightscale = TorOptions.default_bwweightscale
else:
cons_bwweightscale = consensus.bwweightscale
for relay in consensus.relays:
if (relay in new_descriptors):
cons_rel_stats[relay] = consensus.relays[relay]
return NetworkState(cons_valid_after, cons_fresh_until, cons_bw_weights,
cons_bwweightscale, cons_rel_stats, hibernating_statuses,
new_descriptors)
def get_network_states(network_state_files, network_modifiers):
"""Generator that yields NetworkState object produced from
list of network state files and modifiers to apply.
Input:
network_state_files: list of filenames with sequential network statuses
as produced by pad_network_state_files(), i.e. no time gaps except
as indicated by None entries
network_modifiers: (list) contains objects to modify to network state in
order via modify_network_state() method
Output:
network_states: iterator yielding sequential NetworkState objects or
None
"""
for ns_file in network_state_files:
if (ns_file is not None):
# get network state variables from file
network_state = get_network_state(ns_file)
# apply network modifications
for network_modifier in network_modifiers:
network_modifier.modify_network_state(network_state)
else:
network_state = None
yield network_state
def set_initial_hibernating_status(hibernating_status, hibernating_statuses,
cur_period_start, cons_rel_stats):
"""Reads hibernating statuses and updates initial relay status."""
while (hibernating_statuses) and\
(hibernating_statuses[-1][0] <= cur_period_start):
hs = hibernating_statuses.pop()
if (hs[1] in hibernating_status) and _testing:
print('Reset hibernating of {0}:{1} to {2}.'.format(\
cons_rel_stats[hs[1]].nickname, hibernating_status[hs[1]],
hs[2]))
hibernating_status[hs[1]] = hs[2]
if _testing:
if (hs[2]):
print('{0} was hibernating at start of consensus period.'.\
format(cons_rel_stats[hs[1]].nickname))
def period_client_update(client_state, cons_rel_stats, cons_fresh_until,\
cons_valid_after):
"""Updates client state for new consensus period."""
if _testing:
print('Updating state for client {0} given new consensus.'.\
format(client_state['id']))
# Update guard list
# Tor does this stuff whenever a descriptor is obtained
guards = client_state['guards']
for guard, guard_props in guards.items():
# set guard as down if (following Tor's
# entry_guard_set_status)
# - not in current nodelist (!node check)
# - note that a node can appear the nodelist but not
# in consensus if it has an existing descriptor
# in routerlist (unclear to me when this gets purged)
# - Running flag not set
# - note that all nodes not in current consensus get
# *all* their node flags set to zero
# - Guard flag not set [and not a bridge])
# note that hibernating *not* considered here
if (guard_props['bad_since'] == None):
if (guard not in cons_rel_stats) or\
(Flag.RUNNING not in\
cons_rel_stats[guard].flags) or\
(Flag.GUARD not in\
cons_rel_stats[guard].flags):
if _testing:
print('Putting down guard {0}'.format(guard))
guard_props['bad_since'] = cons_valid_after
else:
if (guard in cons_rel_stats) and\
(Flag.RUNNING in\
cons_rel_stats[guard].flags) and\
(Flag.GUARD in\
cons_rel_stats[guard].flags):
if _testing:
print('Bringing up guard {0}'.format(guard))
guard_props['bad_since'] = None
# remove if down time including this period exceeds limit
if (guard_props['bad_since'] != None):
if (cons_fresh_until-guard_props['bad_since'] >=\
TorOptions.guard_down_time):
if _testing:
print('Guard down too long, removing: {0}'.\
format(guard))
del guards[guard]
continue
# expire old guards
if (guard_props['expires'] <= cons_valid_after):
if _testing:
print('Expiring guard: {0}'.format(guard))
del guards[guard]
# Kill circuits using relays that now appear to be "down", where
# down is not in consensus or without Running flag.
kill_circuits_by_relay(client_state, \
lambda r: (r not in cons_rel_stats) or \
(Flag.RUNNING not in cons_rel_stats[r].flags),\
'is down')
def timed_updates(cur_time, port_needs_global, client_states,
hibernating_statuses, hibernating_status, cons_rel_stats):
"""Perform timing-based updates that apply to all clients."""
# expire port needs
for port, need in port_needs_global.items():
if (need['expires'] != None) and\
(need['expires'] <= cur_time):
if _testing:
print('Port need for {0} expiring.'.format(port))
# remove need from global list
del port_needs_global[port]
# remove coverage number and per-circuit coverage from client state
for client_state in client_states:
del client_state['port_needs_covered'][port]
for circuit in client_state['clean_exit_circuits']:
circuit['covering'].discard(port)
# update hibernating status
while (hibernating_statuses) and\
(hibernating_statuses[-1][0] <= cur_time):
hs = hibernating_statuses.pop()
if _testing:
if (hs[1] in cons_rel_stats):
if hs[2]:
print('{0}:{1} started hibernating.'.\
format(cons_rel_stats[hs[1]].nickname, hs[1]))
else:
print('{0}:{1} stopped hibernating.'.\
format(cons_rel_stats[hs[1]].nickname, hs[1]))
hibernating_status[hs[1]] = hs[2]
def timed_client_updates(cur_time, client_state, port_needs_global,
cons_rel_stats, cons_valid_after,
cons_fresh_until, cons_bw_weights, cons_bwweightscale, descriptors,
hibernating_status, port_need_weighted_exits, weighted_middles,
weighted_guards, congmodel, pdelmodel, callbacks=None, water_filling=\
False):
"""Performs updates to client state that occur on a time schedule."""
guards = client_state['guards']
# kill old dirty circuits
while (len(client_state['dirty_exit_circuits'])>0) and\
(client_state['dirty_exit_circuits'][-1]['dirty_time'] <=\
cur_time - TorOptions.max_circuit_dirtiness):
if _testing:
print('Killed dirty exit circuit at time {0} w/ dirty time \
{1}'.format(cur_time, client_state['dirty_exit_circuits'][-1]['dirty_time']))
client_state['dirty_exit_circuits'].pop()
# kill old clean circuits
while (len(client_state['clean_exit_circuits'])>0) and\
(client_state['clean_exit_circuits'][-1]['time'] <=\
cur_time - TorOptions.circuit_idle_timeout):
if _testing:
print('Killed clean exit circuit at time {0} w/ time \
{1}'.format(cur_time, client_state['clean_exit_circuits'][-1]['time']))
uncover_circuit_ports(client_state['clean_exit_circuits'][-1],\
client_state['port_needs_covered'])
client_state['clean_exit_circuits'].pop()
# kill circuits with relays that have gone into hibernation
kill_circuits_by_relay(client_state, \
lambda r: hibernating_status[r], 'is hibernating')
# cover uncovered ports while fewer than
# TorOptions.max_unused_open_circuits clean
for port, need in port_needs_global.items():
if (client_state['port_needs_covered'][port] < need['cover_num']):
# we need to make new circuits
# note we choose circuits specifically to cover all port needs,
# while Tor makes one circuit (per sec) that covers *some* port
# (see circuit_predict_and_launch_new() in circuituse.c)
if _testing:
print('Creating {0} circuit(s) at time {1} to cover port \
{2}.'.format(need['cover_num']-client_state['port_needs_covered'][port],\
cur_time, port))
while (client_state['port_needs_covered'][port] <\
need['cover_num']) and\
(len(client_state['clean_exit_circuits']) < \
TorOptions.max_unused_open_circuits):
new_circ = create_circuit(cons_rel_stats,