/
test_bridges.py
1820 lines (1561 loc) · 80.6 KB
/
test_bridges.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
# -*- coding: utf-8 -*-
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Isis Lovecruft <isis@torproject.org>
# please also see AUTHORS file
# :copyright: (c) 2007-2015, The Tor Project, Inc.
# (c) 2007-2015, all entities within the AUTHORS file
# :license: 3-Clause BSD, see LICENSE for licensing information
"""Unittests for the :mod:`bridgedb.bridges` module."""
from binascii import a2b_hex
import datetime
import ipaddr
import io
import hashlib
import os
import warnings
from twisted.trial import unittest
from bridgedb import bridges
from bridgedb.Bridges import FilteredBridgeSplitter
from bridgedb.bridgerequest import BridgeRequestBase
from bridgedb.parse import descriptors
from bridgedb.parse.addr import PortList
from bridgedb.parse.nickname import InvalidRouterNickname
# Don't print "WARNING:root: Couldn't parse K=V from PT arg: ''" a bunch of
# times while running the tests.
warnings.filterwarnings("ignore", ".*Couldn't parse K=V from PT arg.*", Warning)
BRIDGE_NETWORKSTATUS = '''\
r FourfoldQuirked LDIlxIBTMQJeIR9Lblv0XDM/3Sw c4EVu2rO/iD/DJYBX/Ll38DGQWI 2014-12-22 21:51:27 179.178.155.140 36489 0
a [6bf3:806b:78cd:d4b4:f6a7:4ced:cfad:dad4]:36488
s Fast Guard Running Stable Valid
w Bandwidth=1585163
p reject 1-65535
'''
BRIDGE_SERVER_DESCRIPTOR = '''\
@purpose bridge
router FourfoldQuirked 179.178.155.140 36489 0 0
or-address [6bf3:806b:78cd:d4b4:f6a7:4ced:cfad:dad4]:36488
platform Tor 0.2.3.24-rc on Linux
opt protocols Link 1 2 Circuit 1
published 2014-12-22 21:51:27
opt fingerprint 2C32 25C4 8053 3102 5E21 1F4B 6E5B F45C 333F DD2C
uptime 33200687
bandwidth 1866688205 2110169275 1623207134
opt extra-info-digest 4497E81715D958105C6A39D348163AD8F3080FB2
onion-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANKicvIGWp9WGKOJV8Fs3YKdTDrgxlggzyKgkW+MZWEPQ9lLcrmXqBdW
nVK5EABByHnnxJfk+sm+6yDYxY/lFVL1SEP84pAK1Z21f4+grNlwox1DLyntXDdz
BCZuRszuBYK3ncsk+ePQeUzRKQ/GZt9s/oy0IjtNbAoAoq7DKUVzAgMBAAE=
-----END RSA PUBLIC KEY-----
signing-key
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALnJK7A9aZIp2ry9ruVYzm4VfaXzNHdTcvkXTrETu/jLXsosEwj9viSe
Ry3W/uctbjzdwlIY0ZBUuV20q9bh+/c7Q0T8LOHBZouOy+nhFOUX+Q5YCG9cRnY0
hBebYTzyplh0tT8xyYwcS8y6esL+gjVDLo6Og3QPhWRFQ4CyCic9AgMBAAE=
-----END RSA PUBLIC KEY-----
contact Somebody <somebody@example.com>
ntor-onion-key aVmfOm9C046wM8ktGnpfBHSNj1Jm30M/m2P7W3a7Xn8
reject *:*
router-signature
-----BEGIN SIGNATURE-----
nxml4rTyTrj8dHcsFt2B4ACz2AN5CuZ2t5UF1BtXUpuzHmqVlg7imy8Cp2xIwoDa
4uv/tTG32macauVnMHt0hSbtBF5nHfxU9G1T/XzdtL+KD8REDGky4allXnmvF6In
rFtSn2OeZewvi8oYPmVYKgzHL6tzZxs2Sn/bOTj5sRw=
-----END SIGNATURE-----
'''
BRIDGE_EXTRAINFO = '''\
extra-info FourfoldQuirked 2C3225C4805331025E211F4B6E5BF45C333FDD2C
published 2014-12-22 21:51:27
write-history 2014-12-22 21:51:27 (900 s) 3188736,2226176,2866176
read-history 2014-12-22 21:51:27 (900 s) 3891200,2483200,2698240
dirreq-write-history 2014-12-22 21:51:27 (900 s) 1024,0,2048
dirreq-read-history 2014-12-22 21:51:27 (900 s) 0,0,0
geoip-db-digest 51AE9611B53880B2BCF9C71E735D73F33FAD2DFE
geoip6-db-digest 26B0D55B20BEB496A3ADE7C6FDD866F5A81027F7
dirreq-stats-end 2014-12-22 21:51:27 (86400 s)
dirreq-v3-ips
dirreq-v3-reqs
dirreq-v3-resp ok=16,not-enough-sigs=0,unavailable=0,not-found=0,not-modified=0,busy=0
dirreq-v3-direct-dl complete=0,timeout=0,running=0
dirreq-v3-tunneled-dl complete=12,timeout=0,running=0
transport obfs3 179.178.155.140:36490
transport obfs2 179.178.155.140:36491
transport scramblesuit 179.178.155.140:36492 password=ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
transport obfs4 179.178.155.140:36493 iat-mode=0,node-id=25293f2761d658cc70c19515861842d712751bdc,public-key=02d20bbd7e394ad5999a4cebabac9619732c343a4cac99470c03e23ba2bdc2bc
bridge-stats-end 2014-12-22 21:51:27 (86400 s)
bridge-ips ca=8
bridge-ip-versions v4=8,v6=0
bridge-ip-transports <OR>=8
router-signature
-----BEGIN SIGNATURE-----
cn4+8pQwCMPnHcp1s8wm7ZYsnd9AXJH6ysNlvQ63jsPCG9JdE5E8BwCThEgUccJI
XILT4o+SveEQUG72R4bENsKxqV4rRNh1g6CNAbYhAITqrU9B+jImDgrBBW+XWT5K
78ECRPn6Y4KsxFb0TIn7ddv9QjApyBJNIDMihH80Yng=
-----END SIGNATURE-----
'''
# The timestamps have changed, and the IP:port for obfs3 changed
BRIDGE_EXTRAINFO_NEW = '''\
extra-info FourfoldQuirked 2C3225C4805331025E211F4B6E5BF45C333FDD2C
published 2014-12-22 22:51:27
write-history 2014-12-22 22:51:27 (900 s) 3188736,2226176,2866176
read-history 2014-12-22 22:51:27 (900 s) 3891200,2483200,2698240
dirreq-write-history 2014-12-22 22:51:27 (900 s) 1024,0,2048
dirreq-read-history 2014-12-22 22:51:27 (900 s) 0,0,0
geoip-db-digest 51AE9611B53880B2BCF9C71E735D73F33FAD2DFE
geoip6-db-digest 26B0D55B20BEB496A3ADE7C6FDD866F5A81027F7
dirreq-stats-end 2014-12-22 22:51:27 (86400 s)
dirreq-v3-ips
dirreq-v3-reqs
dirreq-v3-resp ok=16,not-enough-sigs=0,unavailable=0,not-found=0,not-modified=0,busy=0
dirreq-v3-direct-dl complete=0,timeout=0,running=0
dirreq-v3-tunneled-dl complete=12,timeout=0,running=0
transport obfs3 11.11.11.11:1111
transport obfs2 179.178.155.140:36491
transport scramblesuit 179.178.155.140:36492 password=ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
transport obfs4 179.178.155.140:36493 iat-mode=0,node-id=25293f2761d658cc70c19515861842d712751bdc,public-key=02d20bbd7e394ad5999a4cebabac9619732c343a4cac99470c03e23ba2bdc2bc
bridge-stats-end 2014-12-22 22:51:27 (86400 s)
bridge-ips ca=8
bridge-ip-versions v4=8,v6=0
bridge-ip-transports <OR>=8
router-signature
-----BEGIN SIGNATURE-----
cn4+8pQwCMPnHcp1s8wm7ZYsnd9AXJH6ysNlvQ63jsPCG9JdE5E8BwCThEgUccJI
XILT4o+SveEQUG72R4bENsKxqV4rRNh1g6CNAbYhAITqrU9B+jImDgrBBW+XWT5K
78ECRPn6Y4KsxFb0TIn7ddv9QjApyBJNIDMihH80Yng=
-----END SIGNATURE-----
'''
class BridgeIntegrationTests(unittest.TestCase):
"""Integration tests to ensure that the new :class:`bridgedb.bridges.Bridge`
class has compatible behaviour with the expected behaviour of the old
:class:`bridgedb.Bridges.Bridge` class.
.. data: OldTest (enum)
These tests were refactored from the old tests for
``deprecated.Bridge`, which lived in
``lib/bridgedb/test/test_Bridges.py``. For the translations from the old
tests in ``test_Bridges.BridgeClassTest`` to their new
equivalents here in ``test_bridges.BridgeIntegrationTests``,
which should test for the same things as their old equivalents, see the
following table:
============================================== ========================
OldTest Equivalent Test(s) Here
============================================== ========================
test_init test_integration_init_[0-5]
test_getID test_integration_getID
test_setDescriptorDigest test_integration_setDescriptorDigest
test_setExtraInfoDigest test_integration_setExtraInfoDigest
test_setVerified test_integration_setVerified
test_setRunningStable test_integration_setRunningStable
test_getConfigLine_vanilla_withoutFingerprint test_integration_getConfigLine_vanilla_withoutFingerprint
test_getConfigLine_vanilla_withFingerprint test_integration_getConfigLine_vanilla_withFingerprint
test_getConfigLine_scramblesuit_withFingeprint test_integration_getConfigLine_scramblesuit_withFingerprint
test_splitterBridgeInsertion test_integration_hashringBridgeInsertion
============================================== ========================
..
"""
def setUp(self):
self.nickname = 'unnamed'
self.ip = ipaddr.IPAddress('127.0.0.1')
self.orport = '9001'
self.fingerprint = 'A1CC8DFEF1FA11AF9C40AF1054DF9DAF45250556'
self.id_digest = a2b_hex(self.fingerprint)
self.or_addresses = {ipaddr.IPAddress('6.6.6.6'): PortList(6666),
ipaddr.IPAddress('42.1.42.1'): PortList(443)}
def test_integration_init_0(self):
"""Ensure that we can initialise the new :class:`bridgedb.bridges.Bridge`
class in the same manner as the old :class:`bridgedb.Bridges.Bridge`
class. This test ensures that initialisation with a fingerprint is
successful.
"""
b = bridges.Bridge(self.nickname, self.ip, self.orport,
fingerprint=self.fingerprint)
self.assertIsInstance(b, bridges.Bridge)
def test_integration_init_1(self):
"""Ensure that we can initialise the new :class:`bridgedb.bridges.Bridge`
class in the same manner as the old :class:`bridgedb.Bridges.Bridge`
class. This test ensures that initialisation with a digest of a
bridge's ID key is successful.
"""
b = bridges.Bridge(self.nickname, self.ip, self.orport,
id_digest=self.id_digest)
self.assertIsInstance(b, bridges.Bridge)
def test_integration_init_2(self):
"""Initialisation of a :class:`bridgedb.bridges.Bridge` with a bad
``id_digest`` should raise a TypeError.
"""
self.failUnlessRaises(TypeError, bridges.Bridge,
self.nickname, self.ip, self.orport,
id_digest=self.id_digest[:-1])
def test_integration_init_3(self):
"""Initialisation of a :class:`bridgedb.bridges.Bridge` with a bad
``fingerprint`` should raise a TypeError.
"""
self.failUnlessRaises(TypeError, bridges.Bridge,
self.nickname, self.ip, self.orport,
fingerprint=self.fingerprint[:-1])
def test_integration_init_4(self):
"""Initialisation of a :class:`bridgedb.bridges.Bridge` with a bad
``fingerprint`` should raise a TypeError.
"""
invalid_fingerprint = self.fingerprint[:-1] + 'q'
self.failUnlessRaises(TypeError, bridges.Bridge, self.nickname,
self.ip, self.orport,
fingerprint=invalid_fingerprint)
def test_integration_init_5(self):
"""Initialisation of a :class:`bridgedb.bridges.Bridge` without either
a ``fingerprint`` or an ``id_digest`` should raise a TypeError.
"""
self.failUnlessRaises(TypeError, bridges.Bridge,
self.nickname, self.ip, self.orport)
def test_integration_getID(self):
"""Calling ``bridges.Bridge.getID()`` should return the binary encoded
``fingerprint``.
"""
bridge = bridges.Bridge(self.nickname, self.ip, self.orport,
self.fingerprint)
self.assertEqual(self.id_digest, bridge.getID())
def test_integration_setDescriptorDigest(self):
"""Test setting the server-descriptor digest value."""
bridge = bridges.Bridge(self.nickname, self.ip, self.orport,
self.fingerprint)
testtext = 'thisisatest'
bridge.setDescriptorDigest(testtext)
self.assertEqual(bridge.desc_digest, testtext)
def test_integration_setExtraInfoDigest(self):
"""Test setting the extra-info digest value."""
bridge = bridges.Bridge(self.nickname, self.ip, self.orport,
self.fingerprint)
testtext = 'thisisatest'
bridge.setExtraInfoDigest(testtext)
self.assertEqual(bridge.ei_digest, testtext)
def test_integration_setVerified(self):
"""Test setting the `verified` attribute on a Bridge."""
raise unittest.SkipTest(
("The setVerified() and isVerified() methods were not refactored "
"into the new bridgedb.bridges.Bridge class, as it's not clear "
"yet if they are necessary. Skip these tests for now."))
bridge = bridges.Bridge(self.nickname, self.ip, self.orport,
self.fingerprint)
bridge.setVerified()
self.assertTrue(bridge.isVerified())
self.assertTrue(bridge.verified)
self.assertEqual(self.id_digest, bridge.getID())
def test_integration_setRunningStable(self):
"""Test setting the `running` and `stable` attributes on a Bridge."""
bridge = bridges.Bridge(self.nickname, self.ip, self.orport,
self.fingerprint)
self.assertFalse(bridge.running)
self.assertFalse(bridge.stable)
bridge.setStatus(True, True)
self.assertTrue(bridge.running)
self.assertTrue(bridge.stable)
def test_integration_getConfigLine_vanilla_withoutFingerprint(self):
"""Should return a config line without a fingerprint."""
#self.skip = True
bridge = bridges.Bridge('nofpr', '23.23.23.23', 2323, self.fingerprint,
or_addresses=self.or_addresses)
bridgeLine = bridge.getConfigLine()
ip = bridgeLine.split(':')[0]
self.assertTrue(ipaddr.IPAddress(ip))
def test_integration_getConfigLine_vanilla_withFingerprint(self):
"""Should return a config line with a fingerprint."""
bridge = bridges.Bridge('fpr', '23.23.23.23', 2323,
id_digest=self.id_digest,
or_addresses=self.or_addresses)
bridgeLine = bridge.getConfigLine(includeFingerprint=True)
self.assertIsNotNone(bridgeLine)
self.assertSubstring(self.fingerprint, bridgeLine)
ip = bridgeLine.split(':')[0]
self.assertTrue(ipaddr.IPAddress(ip))
def test_integration_getConfigLine_scramblesuit_withFingerprint(self):
"""Should return a scramblesuit config line with a fingerprint."""
bridge = bridges.Bridge('philipkdick', '23.23.23.23', 2323,
id_digest=self.id_digest,
or_addresses=self.or_addresses)
ptArgs = {'password': 'NEQGQYLUMUQGK5TFOJ4XI2DJNZTS4LRO'}
pt = bridges.PluggableTransport(bridge.fingerprint, 'scramblesuit',
ipaddr.IPAddress('42.42.42.42'), 4242,
ptArgs)
bridge.transports.append(pt)
bridgeLine = bridge.getConfigLine(includeFingerprint=True,
transport='scramblesuit')
ptArgsList = ' '.join(["{0}={1}".format(k,v) for k,v in ptArgs.items()])
self.assertEqual("scramblesuit 42.42.42.42:4242 %s %s"
% (self.fingerprint, ptArgsList),
bridgeLine)
def test_integration_hashringBridgeInsertion(self):
key = "Testing-Bridges-To-Rings"
hashring = FilteredBridgeSplitter(key)
bridge1 = bridges.Bridge('unamed1', '1.2.3.5', 9100,
'a1cc8dfef1fa11af9c40af1054df9daf45250550')
bridge1.setStatus(running = True)
bridge2 = bridges.Bridge('unamed2', '1.2.3.4', 8080,
'a1cc8dfef1fa11af9c40af1054df9daf45250551')
bridge2.setStatus(running = True)
bridge3 = bridges.Bridge('unamed3', '5.2.3.4', 8080,
'b1cc8dfef1fa11af9c40af1054df9daf45250552')
bridge3.setStatus(running = True)
bridge4 = bridges.Bridge('unamed3', '5.2.3.4', 8080,
'b1cc8dfef1fa11af9c40af1054df9daf45250552')
bridge4.setStatus(running = True)
self.failUnlessEqual(len(hashring), 0)
hashring.insert(bridge1)
hashring.insert(bridge2)
hashring.insert(bridge3)
# Check that all were inserted
self.failUnlessEqual(len(hashring), 3)
hashring.insert(bridge1)
# Check that the same bridge is not inserted twice
self.failUnlessEqual(len(hashring), 3)
hashring.insert(bridge4)
# Check that identical bridges are not inserted twice
self.failUnlessEqual(len(hashring), 3)
class FlagsTests(unittest.TestCase):
"""Tests for :class:`bridgedb.bridges.Flags`."""
def setUp(self):
self.flags = bridges.Flags()
self._all_flag_names = ["fast", "guard", "running", "stable", "valid"]
def test_init(self):
"""Upon initialisation, all flags should be ``False``."""
for flag in self._all_flag_names:
f = getattr(self.flags, flag, None)
self.assertFalse(f, "%s should be False" % flag)
def test_settingStable(self):
"""Setting the Stable flag to ``True`` should result in Flags.stable
being ``True``.
"""
self.flags.stable = True
self.assertTrue(self.flags.stable, "The Stable flag should be True")
def test_settingRunning(self):
"""Setting the Running flag to ``True`` should result in Flags.running
being ``True``.
"""
self.flags.running = True
self.assertTrue(self.flags.running, "The Running flag should be True")
def test_changingFlags(self):
"""Setting a flag and then unsetting it should result in it being
``True`` and then ``False``.
"""
self.flags.valid = True
self.assertTrue(self.flags.valid, "The Valid flag should be True")
self.flags.valid = False
self.assertFalse(self.flags.valid, "The Valid flag should be False")
def test_update_Fast_Stable(self):
"""Test changing flags with the update() method."""
self.flags.update(["Fast", "Stable"])
self.assertTrue(self.flags.fast)
self.assertTrue(self.flags.stable)
def test_update_Fast(self):
"""Test changing flags with the update() method."""
self.flags.update(["Fast"])
self.assertTrue(self.flags.fast)
self.assertFalse(self.flags.stable)
def test_update_Stable(self):
"""Test changing flags with the update() method."""
self.flags.update(["Stable"])
self.assertFalse(self.flags.fast)
self.assertTrue(self.flags.stable)
class BridgeAddressBaseTests(unittest.TestCase):
"""Tests for :class:`bridgedb.bridges.BridgeAddressBase`."""
def setUp(self):
self.fingerprint = '2C3225C4805331025E211F4B6E5BF45C333FDD2C'
self.bab = bridges.BridgeAddressBase()
def test_BridgeAddressBase_init(self):
"""The BridgeAddressBase's _address and _fingerprint should be None."""
self.assertIsNone(self.bab._address)
self.assertIsNone(self.bab._fingerprint)
def test_BridgeAddressBase_fingerprint_del(self):
"""The del method for the fingerprint property should reset the
fingerprint to None.
"""
self.bab.fingerprint = self.fingerprint
self.assertEqual(self.bab.fingerprint, self.fingerprint)
del(self.bab.fingerprint)
self.assertIsNone(self.bab.fingerprint)
self.assertIsNone(self.bab._fingerprint)
def test_BridgeAddressBase_address_del(self):
"""The del method for the address property should reset the
address to None.
"""
self.bab.address = '11.12.13.14'
self.assertEqual(self.bab.address, ipaddr.IPv4Address('11.12.13.14'))
del(self.bab.address)
self.assertIsNone(self.bab.address)
self.assertIsNone(self.bab._address)
def test_BridgeAddressBase_country(self):
"""The getter method for the country property should get the
address's geoIP country code.
"""
self.bab.address = '11.12.13.14'
self.assertEqual(self.bab.address, ipaddr.IPv4Address('11.12.13.14'))
cc = self.bab.country
self.assertIsNotNone(cc)
self.assertIsInstance(cc, basestring)
self.assertEqual(len(cc), 2)
class PluggableTransportTests(unittest.TestCase):
"""Tests for :class:`bridgedb.bridges.PluggableTransport."""
def setUp(self):
self.fingerprint = "ABCDEF0123456789ABCDEF0123456789ABCDEF01"
def test_PluggableTransport_init_with_parameters(self):
"""Initialising a PluggableTransport with args should work."""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar'})
self.assertIsInstance(pt, bridges.PluggableTransport)
def test_PluggableTransport_init(self):
"""Initialising a PluggableTransport without args should work."""
pt = bridges.PluggableTransport()
self.assertIsInstance(pt, bridges.PluggableTransport)
def test_PluggableTransport_port_del(self):
"""The del method for the port property should reset the port to None.
"""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar'})
self.assertEqual(pt.port, 443)
del(pt.port)
self.assertIsNone(pt.port)
self.assertIsNone(pt._port)
def test_PluggableTransport_parseArgumentsIntoDict_valid_list(self):
"""Parsing a valid list of PT args should return a dictionary."""
pt = bridges.PluggableTransport()
args = pt._parseArgumentsIntoDict(["sharedsecret=foobar",
"publickey=1234"])
self.assertIsInstance(args, dict)
self.assertItemsEqual(args, {"sharedsecret": "foobar",
"publickey": "1234"})
def test_PluggableTransport_parseArgumentsIntoDict_valid_list_multi(self):
"""Parsing a valid list with multiple PT args in a single list element
should return a dictionary.
"""
pt = bridges.PluggableTransport()
args = pt._parseArgumentsIntoDict(["sharedsecret=foobar,password=baz",
"publickey=1234"])
self.assertIsInstance(args, dict)
self.assertItemsEqual(args, {"sharedsecret": "foobar",
"password": "baz",
"publickey": "1234"})
def test_PluggableTransport_parseArgumentsIntoDict_invalid_missing_equals(self):
"""Parsing a string of PT args where one PT arg (K=V) is missing an
``=`` character should raise a ValueError.
"""
pt = bridges.PluggableTransport()
args = pt._parseArgumentsIntoDict(
["sharedsecret=foobar,password,publickey=1234"])
self.assertItemsEqual(args, {"sharedsecret": "foobar",
"publickey": "1234"})
def test_PluggableTransport_checkArguments_scramblesuit_missing_password(self):
"""Calling _checkArguments on a scramblesuit PT without a password should
raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'scramblesuit', ('34.230.223.87', 37341, []))
def test_PluggableTransport_checkArguments_obfs4_missing_iatmode(self):
"""Calling _checkArguments on an obfs4 PT without an iat-mode argument
should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', 37341, [
'cert=UXj/cWm0qolGrROYpkl0UyD/7PEhzkoZkZXrOpjRKwImvkpQZwmF0nSzBXfyfbT9afBZEw']))
def test_PluggableTransport_checkArguments_obfs4_missing_cert(self):
"""Calling _checkArguments on an obfs4 PT without a cert argument
should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', 37341, ['iat-mode=1']))
def test_PluggableTransport_checkArguments_obfs4_missing_publickey(self):
"""Calling _checkArguments on an obfs4 PT without a public-key argument
should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', 37341, [
('iat-mode=1,'
'node-id=2a79f14120945873482b7823caabe2fcde848722')]))
def test_PluggableTransport_checkArguments_obfs4_missing_nodeid(self):
"""Calling _checkArguments on an obfs4 PT without a public-key argument
should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', 37341, [
('iat-mode=1,'
'public-key=0a5b046d07f6f971b7776de682f57c5b9cdc8fa060db7ef59de82e721c8098f4')]))
def test_PluggableTransport_runChecks_invalid_fingerprint(self):
"""Calling _runChecks() on a PluggableTransport with an invalid
fingerprint should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
"INVALIDFINGERPRINT", 'obfs4', ('34.230.223.87', 37341, [
('iat-mode=0,'
'node-id=2a79f14120945873482b7823caabe2fcde848722,'
'public-key=0a5b046d07f6f971b7776de682f57c5b9cdc8fa060db7ef59de82e721c8098f4')]))
def test_PluggableTransport_runChecks_invalid_ip(self):
"""Calling _runChecks() on a PluggableTransport with an invalid
IP address should raise a InvalidPluggableTransportIP exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.InvalidPluggableTransportIP,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223', 37341, [
('iat-mode=0,'
'node-id=2a79f14120945873482b7823caabe2fcde848722,')]))
def test_PluggableTransport_runChecks_invalid_port_type(self):
"""Calling _runChecks() on a PluggableTransport with an invalid port
should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', "anyport", [
('iat-mode=0,'
'node-id=2a79f14120945873482b7823caabe2fcde848722,')]))
def test_PluggableTransport_runChecks_invalid_port_range(self):
"""Calling _runChecks() on a PluggableTransport with an invalid port
(too high) should raise a MalformedPluggableTransport exception.
"""
pt = bridges.PluggableTransport()
self.assertRaises(
bridges.MalformedPluggableTransport,
pt.updateFromStemTransport,
self.fingerprint, 'obfs4', ('34.230.223.87', 65536, [
('iat-mode=0,'
'node-id=2a79f14120945873482b7823caabe2fcde848722,')]))
def test_PluggableTransport_runChecks_invalid_pt_args(self):
"""Calling _runChecks() on a PluggableTransport with an invalid PT
args should raise a MalformedPluggableTransport exception.
"""
try:
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
'sharedsecret=foobar')
except Exception as error:
self.failUnlessIsInstance(error,
bridges.MalformedPluggableTransport)
def test_PluggableTransport_getTransportLine_bridge_prefix(self):
"""If the 'Bridge ' prefix was requested, then it should be at the
beginning of the bridge line.
"""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar',
'password': 'unicorns'})
bridgeLine = pt.getTransportLine(bridgePrefix=True)
self.assertTrue(bridgeLine.startswith("Bridge "))
def test_PluggableTransport_getTransportLine_without_Fingerprint(self):
"""If no fingerprint was requested, then there shouldn't be a
fingerprint in the bridge line.
"""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar',
'password': 'unicorns'})
bridgeLine = pt.getTransportLine(includeFingerprint=False)
self.assertNotSubstring(self.fingerprint, bridgeLine)
def test_PluggableTransport_getTransportLine_content_order(self):
"""Check the order and content of the bridge line string."""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar',
'password': 'unicorns'})
bridgeLine = pt.getTransportLine()
# We have to check for substrings because we don't know which order
# the PT arguments will end up in the bridge line. We also have to
# check for the lowercased transport name. Fortunately, the following
# three are the only ones which are important to have in order:
self.assertTrue(bridgeLine.startswith("voltronpt"))
self.assertSubstring("voltronpt 1.2.3.4:443 " + self.fingerprint,
bridgeLine)
# These ones can be in any order, but they should be at the end of the
# bridge line:
self.assertSubstring("password=unicorns", bridgeLine)
self.assertSubstring("sharedsecret=foobar", bridgeLine)
def test_PluggableTransport_getTransportLine_ptargs_space_delimited(self):
"""The PT arguments in a bridge line should be space-separated."""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "1.2.3.4", 443,
{'sharedsecret': 'foobar',
'password': 'unicorns'})
bridgeLine = pt.getTransportLine()
self.assertTrue(
("password=unicorns sharedsecret=foobar" in bridgeLine) or
("sharedsecret=foobar password=unicorns" in bridgeLine))
def test_PluggableTransport_getTransportLine_IPv6(self):
"""The address portion of a bridge line with an IPv6 address should
have square brackets around it.
"""
pt = bridges.PluggableTransport(self.fingerprint,
"voltronPT", "2006:42::1234", 443,
{'sharedsecret': 'foobar',
'password': 'unicorns'})
bridgeLine = pt.getTransportLine()
self.assertEqual(pt.address.version, 6)
self.assertIn("[2006:42::1234]:443", bridgeLine)
class BridgeBackwardsCompatibilityTests(unittest.TestCase):
"""Tests for :class:`bridgedb.bridges.BridgeBackwardsCompatibility`."""
def setUp(self):
self.nickname = "RouterNickname"
self.address = "23.23.23.23"
self.orPort = 9001
self.fingerprint = "0123456789ABCDEF0123456789ABCDEF01234567"
self.orAddresses = {"2006:42::123F": PortList(443, 9001, 1337),
"2006:42::123E": PortList(9001, 993)}
def test_BridgeBackwardsCompatibility_init_with_PortList(self):
"""Test initialisation with the usual number of valid arguments and
PortLists for the orAddresses.
"""
bridge = bridges.BridgeBackwardsCompatibility(
self.nickname,
self.address,
self.orPort,
self.fingerprint,
self.orAddresses)
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
def test_BridgeBackwardsCompatibility_init_without_PortList(self):
"""Test initialisation with the usual number of valid arguments and
integers for the orAddresses' ports.
"""
bridge = bridges.BridgeBackwardsCompatibility(
self.nickname,
self.address,
self.orPort,
self.fingerprint,
{"2006:42::123F": 443,
"2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
def test_BridgeBackwardsCompatibility_init_without_address(self):
"""Test initialisation without an IP address."""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
orport=self.orPort,
fingerprint=self.fingerprint,
or_addresses={"2006:42::123F": 443, "2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
def test_BridgeBackwardsCompatibility_init_invalid_orAddresses_address(self):
"""Test initialisation with an invalid ORAddress."""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
ip=self.address,
orport=self.orPort,
fingerprint=self.fingerprint,
or_addresses={"10.1.2.3": 443, "2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
self.assertEqual(len(bridge.orAddresses), 1)
def test_BridgeBackwardsCompatibility_init_invalid_orAddresses_port(self):
"""Test initialisation with an invalid ORPort."""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
ip=self.address,
orport=self.orPort,
fingerprint=self.fingerprint,
or_addresses={"2006:42::123F": 443, "2006:42::123E": "anyport"})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
self.assertEqual(len(bridge.orAddresses), 1)
def test_BridgeBackwardsCompatibility_setStatus_stable(self):
"""Using setStatus() to set the Stable flag should set Bridge.stable
and Bridge.flags.stable to True.
"""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
ip=self.address,
orport=self.orPort,
fingerprint=self.fingerprint,
or_addresses={"2006:42::123F": 443, "2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
self.assertFalse(bridge.stable)
self.assertFalse(bridge.flags.stable)
bridge.setStatus(stable=True)
self.assertTrue(bridge.stable)
self.assertTrue(bridge.flags.stable)
def test_BridgeBackwardsCompatibility_setStatus_running(self):
"""Using setStatus() to set the Running flag should set Bridge.running
and Bridge.flags.running to True.
"""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
ip=self.address,
orport="anyport",
fingerprint=self.fingerprint,
or_addresses={"2006:42::123F": 443, "2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
self.assertFalse(bridge.running)
self.assertFalse(bridge.flags.running)
bridge.setStatus(running=True)
self.assertTrue(bridge.running)
self.assertTrue(bridge.flags.running)
def test_BridgeBackwardsCompatibility_setStatus_running_stable(self):
"""Using setStatus() to set the Running and Stable flags should set
Bridge.running, Bridge.flags.running, Bridge.stable, and
Bridge.flags.stable.
"""
bridge = bridges.BridgeBackwardsCompatibility(
nickname=self.nickname,
ip=self.address,
orport="anyport",
fingerprint=self.fingerprint,
or_addresses={"2006:42::123F": 443, "2006:42::123E": 9001})
self.assertIsInstance(bridge, bridges.BridgeBackwardsCompatibility)
self.assertFalse(bridge.running)
self.assertFalse(bridge.flags.running)
self.assertFalse(bridge.stable)
self.assertFalse(bridge.flags.stable)
bridge.setStatus(running=True, stable=True)
self.assertTrue(bridge.running)
self.assertTrue(bridge.flags.running)
self.assertTrue(bridge.stable)
self.assertTrue(bridge.flags.stable)
class BridgeTests(unittest.TestCase):
"""Tests for :class:`bridgedb.bridges.Bridge`."""
def _parseAllDescriptorFiles(self):
self.networkstatus = descriptors.parseNetworkStatusFile(
self._networkstatusFile)[0]
self.serverdescriptor = descriptors.parseServerDescriptorsFile(
self._serverDescriptorFile)[0]
self.extrainfo = descriptors.parseExtraInfoFiles(
self._extrainfoFile).values()[0]
self.extrainfoNew = descriptors.parseExtraInfoFiles(
self._extrainfoNewFile).values()[0]
def _writeNetworkstatus(self, networkstatus):
with open(self._networkstatusFile, 'w') as fh:
fh.write(networkstatus)
fh.flush()
def _writeServerdesc(self, serverdesc):
with open(self._serverDescriptorFile, 'w') as fh:
fh.write(serverdesc)
fh.flush()
def _writeExtrainfo(self, extrainfo):
with open(self._extrainfoFile, 'w') as fh:
fh.write(extrainfo)
fh.flush()
def _writeExtrainfoNew(self, extrainfo):
with open(self._extrainfoNewFile, 'w') as fh:
fh.write(extrainfo)
fh.flush()
def _writeDescriptorFiles(self, networkstatus, serverdesc, extrainfo, extrainfoNew):
self._writeNetworkstatus(networkstatus)
self._writeServerdesc(serverdesc)
self._writeExtrainfo(extrainfo)
self._writeExtrainfoNew(extrainfoNew)
def setUp(self):
def _cwd(filename):
return os.path.sep.join([os.getcwd(), filename])
self._networkstatusFile = _cwd('BridgeTests-networkstatus-bridges')
self._serverDescriptorFile = _cwd('BridgeTests-bridge-descriptors')
self._extrainfoFile = _cwd('BridgeTests-cached-extrainfo')
self._extrainfoNewFile = _cwd('BridgeTests-cached-extrainfo.new')
self._writeDescriptorFiles(BRIDGE_NETWORKSTATUS,
BRIDGE_SERVER_DESCRIPTOR,
BRIDGE_EXTRAINFO,
BRIDGE_EXTRAINFO_NEW)
self._parseAllDescriptorFiles()
self.bridge = bridges.Bridge()
def tearDown(self):
"""Reset safelogging to its default (disabled) state, due to
test_Bridge_str_with_safelogging changing it.
"""
bridges.safelog.safe_logging = False
def test_Bridge_nickname_del(self):
"""The del method for the nickname property should reset the nickname
to None.
"""
self.bridge.updateFromNetworkStatus(self.networkstatus)
self.assertEqual(self.bridge.nickname, "FourfoldQuirked")
del(self.bridge.nickname)
self.assertIsNone(self.bridge.nickname)
self.assertIsNone(self.bridge._nickname)
def test_Bridge_nickname_invalid(self):
"""The del method for the nickname property should reset the nickname
to None.
"""
# Create a networkstatus descriptor with an invalid nickname:
filename = self._networkstatusFile + "-invalid"
fh = open(filename, 'w')
invalid = BRIDGE_NETWORKSTATUS.replace(
"FourfoldQuirked",
"ThisRouterNicknameContainsWayMoreThanNineteenBytes")
fh.seek(0)
fh.write(invalid)
fh.flush()
fh.close()
self.assertRaises(InvalidRouterNickname,
descriptors.parseNetworkStatusFile,
filename)
def test_Bridge_orport_del(self):
"""The del method for the orPort property should reset the orPort
to None.
"""
self.bridge.updateFromNetworkStatus(self.networkstatus)
self.assertEqual(self.bridge.orPort, 36489)
del(self.bridge.orPort)
self.assertIsNone(self.bridge.orPort)
self.assertIsNone(self.bridge._orPort)
def test_Bridge_str_without_safelogging(self):
"""The str() method of a Bridge should return an identifier for the
Bridge, which should be different if safelogging is enabled.
"""
bridges.safelog.safe_logging = False
bridge = bridges.Bridge()
bridge.updateFromNetworkStatus(self.networkstatus)
identifier = str(bridge)
self.assertEqual(identifier,
''.join(['$', bridge.fingerprint,
'~', bridge.nickname]))
def test_Bridge_str_with_safelogging(self):
"""The str() method of a Bridge should return an identifier for the
Bridge, which should be different if safelogging is enabled.
"""
bridges.safelog.safe_logging = True
bridge = bridges.Bridge()
bridge.updateFromNetworkStatus(self.networkstatus)
identifier = str(bridge)
self.assertEqual(
identifier,
''.join(['$$',
hashlib.sha1(bridge.fingerprint).hexdigest().upper(),
'~', bridge.nickname]))
def test_Bridge_str_without_fingerprint(self):
"""The str() method of a Bridge should return an identifier for the
Bridge, which should be different if the fingerprint is unknown.
"""
bridge = bridges.Bridge()
bridge.updateFromNetworkStatus(self.networkstatus)
del(bridge.fingerprint)
identifier = str(bridge)
self.assertEqual(identifier,
''.join(['$', '0'*40,
'~', bridge.nickname]))
def test_Bridge_str_without_fingerprint_without_nickname(self):
"""Calling str(Bridge) on a Bridge whose fingerprint and nickname were
not set should return a Bridge identifier string where the fingerprint
is all 0's and the nickname is "Unnamed".
"""
bridge = bridges.Bridge()
identifier = str(bridge)
self.assertEqual(identifier, ''.join(['$', '0'*40, '~', 'Unnamed']))
def test_Bridge_constructBridgeLine_IPv6(self):
"""Bridge._constructBridgeLine() called with an IPv6 address should
wrap the IPv6 address in '[]' in the returned bridge line.
"""
bridge = bridges.Bridge()
addrport = (u'6bf3:806b:78cd::4ced:cfad:dad4', 36488, 6)
bridgeline = bridge._constructBridgeLine(addrport,
includeFingerprint=False,
bridgePrefix=True)
self.assertEqual(bridgeline, 'Bridge [6bf3:806b:78cd::4ced:cfad:dad4]:36488')
def test_Bridge_allVanillaAddresses_idempotency_self(self):
"""Bridge.allVanillaAddresses should be idempotent, i.e. calling
allVanillaAddresses should not affect the results of subsequent calls.
"""
self.bridge.address = '1.1.1.1'
self.bridge.orPort = 443
self.assertItemsEqual(self.bridge.allVanillaAddresses,
[(ipaddr.IPv4Address('1.1.1.1'), 443, 4)])
self.assertItemsEqual(self.bridge.allVanillaAddresses,
[(ipaddr.IPv4Address('1.1.1.1'), 443, 4)])