-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls_mini.py
1568 lines (1419 loc) · 64.8 KB
/
tls_mini.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
############################################################
### Imports (minimal!)
############################################################
from datetime import datetime
from os import urandom
from sys import stdout, stderr, argv
from socket import socket
############################################################
### Utilities
############################################################
# simple things we could have implemented, but these are much faster
from operator import xor
from functools import reduce
BASE64_LOOKUP = bytes(
i - 0x41 if 0x41 <= i <= 0x5A else
i - 0x47 if 0x61 <= i <= 0x7A else
i + 0x04 if 0x30 <= i <= 0x39 else
0x3E if i == 0x2B else
0x3F if i == 0x2F else
0xFF for i in range(256))
def rotl32(x, bits):
return (x << bits | x >> (32 - bits)) & 0xFFFFFFFF
def rotr32(x, bits):
return (x << (32 - bits) | x >> bits) & 0xFFFFFFFF
def rotl64(x, bits):
return (x << bits | x >> (64 - bits)) & 0xFFFFFFFFFFFFFFFF
def rotr64(x, bits):
return (x << (64 - bits) | x >> bits) & 0xFFFFFFFFFFFFFFFF
def only_or_none(x):
if x is not None:
[x] = x
return x
def urandom_nonzero(count):
b = bytearray()
while len(b) < count:
a = urandom(16)
if all(a): b += a
return b[:count]
def xor_bytes(a, b):
l = len(a)
assert l == len(b)
return (int.from_bytes(a, 'little') ^
int.from_bytes(b, 'little')).to_bytes(l, 'little')
def create_reader(buf):
mv = memoryview(buf)
def read(n):
nonlocal mv
res, mv = partition_data(mv, n, False)
return bytes(res)
return read
def min_bytes_for_int(x):
return (x.bit_length() + 7) // 8
def split_url(url):
ss = url[url.index('://')+3:]
result = ss.split('/', 1)
if len(result) == 1:
hostname, path = result[0], ''
else:
hostname, path = result
return hostname, '/' + path
def host_match(hostname, pattern):
if pattern.startswith('*.'):
return hostname.endswith(pattern[1:])
else:
return hostname == pattern
def partition_data(data, pos, verify=True):
a, b = data[:pos], data[pos:]
if verify and (len(a) != pos if pos >= 0 else len(b) != -pos):
raise ValueError('data too small')
return a, b
def consume_front(seq, n):
res = seq[:n]
del seq[:n]
return res
def base64_decode(inp):
lookup = BASE64_LOOKUP
inl, out = len(inp), bytearray()
if inl % 4: raise ValueError('input must have length multiple of 4')
neq = next(i for i, x in enumerate(reversed(inp)) if x != 0x3D)
if neq > 2: raise ValueError('too much padding')
inp = inp[:inl-neq] + b'A' * neq
for i in range(0, inl, 4):
a, b, c, d = ts = inp[i:i+4].ljust(4, b'A').translate(lookup)
if 0xFF in ts: raise ValueError('invalid character found')
out += (a << 18 | b << 12 | c << 6 | d).to_bytes(3, 'big')
return bytes(out[:len(out)-neq])
############################################################
### Binary structure helpers
############################################################
class StructureDict(dict):
def __init__(self):
self.order = []
def __setitem__(self, key, value):
key in self and self.order.remove(key)
super().__setitem__(key, value)
self.order.append(key)
def __delitem__(self, key):
super().__delitem__(key)
self.order.remove(key)
class StructureMeta(type):
def __prepare__(self, bases):
return StructureDict()
def __new__(cls, name, bases, attrs):
all_fields = []
for field_name in attrs.order:
field = attrs[field_name]
if isinstance(field, Field):
field._name = field_name
all_fields.append(field)
new_cls = type.__new__(cls, name, bases, attrs)
new_cls._fields = tuple(all_fields)
return new_cls
class Field(object):
def __get__(self, instance, owner):
return instance.__dict__[self._name]
def __set__(self, instance, value):
instance.__dict__[self._name] = value
class Structure(Field, metaclass=StructureMeta):
_fields = ()
def __init__(self, **kwds):
for field in self._fields:
setattr(self, field._name, kwds.pop(field._name, None))
if kwds:
raise ValueError('unknown fields: ' + repr(kwds))
def __repr__(self):
return '{}({})'.format(self.__class__.__name__,
', '.join('{}={}'.format(field._name, getattr(self, field._name))
for field in self._fields))
def __bytes__(self):
return b''.join(field._encode(getattr(self, field._name))
for field in self._fields)
@staticmethod
def _create_reader_with_remaining(buf):
mv = memoryview(buf)
def read(n):
nonlocal mv
res, mv = partition_data(mv, n)
return bytes(res)
return read, (lambda: len(mv))
@classmethod
def _decode_structure_from_rr(cls, read, remaining, exact):
res = cls()
for field in res._fields:
setattr(res, field._name, field._decode(read, remaining))
if exact and remaining():
raise ValueError('extraneous data found')
return res
@classmethod
def decode_structure_from_bytes(cls, data):
read, remaining = Structure._create_reader_with_remaining(data)
return cls._decode_structure_from_rr(read, remaining, True)
@classmethod
def decode_structure_from_stream(cls, read):
remaining = lambda: 0xFFFFFFFF
return cls._decode_structure_from_rr(read, remaining, False)
class Integer(Field):
def __init__(self, length):
self.length = length
def _encode(self, value):
return value.to_bytes(self.length, 'big')
def _decode(self, read, remaining):
return int.from_bytes(read(self.length), 'big')
class FixedString(Field):
def __init__(self, length):
self.length = length
def _encode(self, value):
if len(value) != self.length:
raise ValueError('must be of length {}')
return value
def _decode(self, read, remaining):
return read(self.length)
class VariableString(Field):
def __init__(self, min_length, max_length):
self.min_length, self.max_length = min_length, max_length
self.int_size = min_bytes_for_int(max_length)
def _encode(self, value):
a, b, l = self.min_length, self.max_length, len(value)
if not (a <= l <= b):
raise ValueError('must be of length {}-{}'.format(a, b))
return l.to_bytes(self.int_size, 'big') + value
def _decode(self, read, remaining):
a, b, l = self.min_length, self.max_length, int.from_bytes(read(self.int_size), 'big')
if not (a <= l <= b):
raise ValueError('incoming data has invalid length {}'.format(l))
return read(l)
class Multiple(VariableString):
def __init__(self, base_type, min_length, max_length, optional=False):
super().__init__(min_length, max_length)
self.base_type, self.optional = base_type, optional
def _encode(self, value):
if self.optional and len(value) == 0: return b''
return super()._encode(b''.join(self.base_type._encode(x) for x in value))
def _decode(self, read, remaining):
if self.optional and remaining() == 0: return []
res, data = [], super()._decode(read, remaining)
read, remaining = Structure._create_reader_with_remaining(data)
while remaining(): res.append(self.base_type._decode(read, remaining))
return res
class SubStructure(Field):
def __init__(self, struct_type):
self.struct_type = struct_type
def _encode(self, value):
return bytes(value)
def _decode(self, read, remaining):
return self.struct_type._decode_structure_from_rr(read, remaining, False)
TLS_RECORD_MAX_SIZE = 16384
class TLSPre:
class HelloExtension(Structure):
extension_type = Structure.Integer(2)
extension_data = Structure.VariableString(0, 2**16 - 1)
class ServerDHParams(Structure):
dh_p = Structure.VariableString(1, 2**16 - 1)
dh_g = Structure.VariableString(1, 2**16 - 1)
dh_Ys = Structure.VariableString(1, 2**16 - 1)
class ServerECDHParams(Structure):
curve_type = Structure.Integer(1)
namedcurve = Structure.Integer(2)
public = Structure.VariableString(1, 2**8 - 1)
class ServerName(Structure):
name_type = Structure.Integer(1)
host_name = Structure.VariableString(1, 2**16 - 1)
class TLSStructures:
global TLSPre
class TLSRecord(Structure):
type = Structure.Integer(1)
protocol_version = Structure.Integer(2)
fragment = Structure.VariableString(0, TLS_RECORD_MAX_SIZE + 2048)
class PreMasterSecret(Structure):
client_version = Structure.Integer(2)
random = Structure.FixedString(46)
class MACCalculationHeader(Structure):
seq_num = Structure.Integer(8)
type = Structure.Integer(1)
version = Structure.Integer(2)
length = Structure.Integer(2)
class ServerNameIndication(Structure):
server_name_list = Structure.Multiple(Structure.SubStructure(TLSPre.ServerName), 1, 2**16 - 1)
class SupportedSignatureAlgorithms(Structure):
algos = Structure.Multiple(Structure.Integer(2), 2, 2**16 - 2)
class ClientHello(Structure):
client_version = Structure.Integer(2)
random = Structure.FixedString(32)
session_id = Structure.VariableString(0, 32)
cipher_suites = Structure.Multiple(Structure.Integer(2), 2, 2**16 - 2)
compression_methods = Structure.Multiple(Structure.Integer(1), 1, 2**8 - 1)
extensions = Structure.Multiple(Structure.SubStructure(TLSPre.HelloExtension), 0, 2**16 - 1,
optional=True)
class ServerHello(Structure):
server_version = Structure.Integer(2)
random = Structure.FixedString(32)
session_id = Structure.VariableString(0, 32)
cipher_suite = Structure.Integer(2)
compression_method = Structure.Integer(1)
extensions = Structure.Multiple(Structure.SubStructure(TLSPre.HelloExtension), 0, 2**16 - 1,
optional=True)
class Certificate(Structure):
certificate_list = Structure.Multiple(Structure.VariableString(1, 2**24 - 1), 0, 2**24 - 1)
class ServerKeyExchangeDHE(Structure):
params = Structure.SubStructure(TLSPre.ServerDHParams)
hash_algo = Structure.Integer(1)
sig_algo = Structure.Integer(1)
signature = Structure.VariableString(0, 2**16 - 1)
class ServerKeyExchangeECDHE(Structure):
params = Structure.SubStructure(TLSPre.ServerECDHParams)
hash_algo = Structure.Integer(1)
sig_algo = Structure.Integer(1)
signature = Structure.VariableString(0, 2**16 - 1)
class ClientKeyExchangeRSA(Structure):
enc_pre_master_secret = Structure.VariableString(0, 2**16 - 1)
class ClientKeyExchangeDHE(Structure):
dh_Yc = Structure.VariableString(1, 2**16 - 1)
class ClientKeyExchangeECDHE(Structure):
ecdh_Yc = Structure.VariableString(1, 2**8-1)
class Finished(Structure):
verify_data = Structure.FixedString(12)
# move everything in TLSPre over to TLSStructures
locals().update(TLSPre.__dict__)
del TLSPre
############################################################
### AES
############################################################
AES_POLY = 0x11B
def aes_gf8_mul(a, b):
aes_poly = AES_POLY # for performance
r = 0
while b:
r ^= -(b & 1) & a # xor r with a if lower-order bit of b set
a, b = a << 1, b >> 1
a ^= -(a >> 8) & aes_poly # xor a with aes_poly with bit 8 set
return r
def aes_gf8_inv(k):
return next(x for x in range(256) if aes_gf8_mul(k, x) == 1)
def aes_generate_boxes():
rotl8 = lambda q, z: (q << z | q >> (8 - z)) & 0xFF
xfrm = lambda q: reduce(xor, (rotl8(q, z) for z in range(5))) ^ 0x63
g = 3 # x + 1
g_inv = aes_gf8_inv(g)
s_fwd, s_rev = [None] * 256, [None] * 256
a, a_inv = 1, 1
while True:
x = xfrm(a_inv)
s_fwd[a] = x
s_rev[x] = a
a, a_inv = aes_gf8_mul(a, g), aes_gf8_mul(a_inv, g_inv)
if a == 1: break
[rem] = set(range(256)) - set(s_fwd)
s_fwd[0], s_rev[rem] = rem, 0
return bytes(s_fwd), bytes(s_rev)
class AES(object):
S_FWD, S_REV = aes_generate_boxes()
M_FWD = tuple(bytes(aes_gf8_mul(i, j) for i in range(256))
for j in (0x2, 0x3, 0x1, 0x1))
M_REV = tuple(bytes(aes_gf8_mul(i, j) for i in range(256))
for j in (0xE, 0xB, 0xD, 0x9))
block_size = 16
def __init__(self, key):
if len(key) not in (16, 24, 32):
raise ValueError('bad key length')
aes_split_word = lambda word: word.to_bytes(4, 'big')
aes_join_word = lambda parts: int.from_bytes(parts, 'big')
aes_SubWord = lambda word: aes_join_word(aes_split_word(word).translate(self.S_FWD))
aes_RotWord = lambda word: (word << 8 | word >> 24) & 0xFFFFFFFF
wo = [aes_join_word(key[s:s+4]) for s in range(0, len(key), 4)]
Nk = self.Nk = len(wo)
Nr = self.Nr = Nk + 6
rcon = 1
for i in range(Nk, 4 * (Nr + 1)):
temp = wo[i-1]
if i % Nk == 0:
temp = aes_SubWord(aes_RotWord(temp)) ^ (rcon << 24)
rcon = aes_gf8_mul(rcon, 2)
elif Nk > 6 and i % Nk == 4:
temp = aes_SubWord(temp)
wo.append(wo[i-Nk] ^ temp)
w = self.w = []
for i in range(Nr + 1):
w.append(b''.join(map(aes_split_word, wo[4*i:4*i+4])))
def _crypt(self, block, inv):
if len(block) != 16:
raise ValueError('bad block length')
(Nr, AddRoundKey, SubBytes, ShiftRows, MixColumns) = (
self.Nr, self.AddRoundKey, self.SubBytes, self.ShiftRows, self.MixColumns)
state = bytes(block)
state = AddRoundKey(state, Nr if inv else 0)
for rnd in range(1, Nr)[::-1 if inv else 1]:
state = SubBytes(state, inv)
state = ShiftRows(state, inv)
if inv:
state = AddRoundKey(state, rnd) # runs on inv
state = MixColumns(state, inv)
if not inv:
state = AddRoundKey(state, rnd) # runs on not inv
state = SubBytes(state, inv)
state = ShiftRows(state, inv)
state = AddRoundKey(state, 0 if inv else Nr)
return state
def encrypt(self, block):
return self._crypt(block, False)
def decrypt(self, block):
return self._crypt(block, True)
def AddRoundKey(self, state, rnd):
return (int.from_bytes(state, 'little') ^
int.from_bytes(self.w[rnd], 'little')).to_bytes(16, 'little')
def SubBytes(self, state, inv):
tbl = self.S_REV if inv else self.S_FWD
return state.translate(tbl)
def ShiftRows(self, state, inv):
(s00, s10, s20, s30,
s01, s11, s21, s31,
s02, s12, s22, s32,
s03, s13, s23, s33) = state
if inv:
return bytes((s00, s13, s22, s31,
s01, s10, s23, s32,
s02, s11, s20, s33,
s03, s12, s21, s30))
else:
return bytes((s00, s11, s22, s33,
s01, s12, s23, s30,
s02, s13, s20, s31,
s03, s10, s21, s32))
def MixColumns(self, state, inv):
matrx = self.M_REV if inv else self.M_FWD
nst = bytearray()
for i in (0, 4, 8, 12):
((a0, a1, a2, a3),
(b0, b1, b2, b3),
(c0, c1, c2, c3),
(d0, d1, d2, d3)) = map(state[i:i+4].translate, matrx)
nst[i:i+4] = (a0 ^ b1 ^ c2 ^ d3,
a1 ^ b2 ^ c3 ^ d0,
a2 ^ b3 ^ c0 ^ d1,
a3 ^ b0 ^ c1 ^ d2)
return bytes(nst)
############################################################
### AES+GCM
############################################################
def aes_gcm_gen_reduction_table():
red_table = [0] * 256
for s in range(8):
m = 0b11100001 << (113 + s)
for i in range(256):
if i & (1 << s):
red_table[i] ^= m
return red_table
AES_GCM_REDUCTION_TABLE = aes_gcm_gen_reduction_table()
class AESGCM(object):
iv_size = 4
nonce_size = 8
tag_size = 16
def __init__(self, key, iv):
self.aes = AES(key)
self.iv = iv
self.mult_table = self._gen_mult_table()
def encrypt(self, nonce, header, fragment):
fragment, tag = self._crypt(self.iv + nonce, header, fragment, False)
return fragment + tag
def decrypt(self, nonce, header, fragment):
fragment, given_tag = partition_data(fragment, -16)
fragment, expected_tag = self._crypt(self.iv + nonce, header, fragment, True)
if given_tag != expected_tag: raise ValueError('bad tag')
return fragment
def _gen_mult_table(self):
m = int.from_bytes(self.aes.encrypt(b'\0' * 16), 'big')
mult_table = [0] * 256
for s in reversed(range(8)):
for i in range(256):
if i & (1 << s):
mult_table[i] ^= m
m = (m >> 1) ^ ((0b11100001 << 120) * (m & 1))
return mult_table
def _crypt(self, iv, addl, data, decrypt):
int_from_bytes, int_to_bytes = int.from_bytes, int.to_bytes
enumerate_, reversed_ = enumerate, reversed # cache as closures for performance
mult_table, red_table = self.mult_table, AES_GCM_REDUCTION_TABLE
data = bytearray(data)
hash_state = 0
Ji = 1
def hash_block(x):
nonlocal hash_state
h = hash_state
m = 0
for k, c in enumerate_(reversed_(x.ljust(16, b'\0'))):
m ^= mult_table[c ^ (h & 0xFF)] << (8 * k)
h >>= 8
for k in range(15):
m = (m >> 8) ^ red_table[m & 0xFF]
hash_state = m
for i in range(0, len(addl), 16):
hash_block(addl[i:i+16])
for i in range(0, len(data), 16):
Ji += 1
chunk = data[i:i+16] # can't use xor_bytes below because chunk may be < 16 bytes
newchunk = bytes(map(xor, chunk, self.aes.encrypt(iv + int_to_bytes(Ji, 4, 'big'))))
data[i:i+16] = newchunk
hash_block(chunk if decrypt else newchunk)
hash_block((len(addl) << 67 | len(data) << 3).to_bytes(16, 'big'))
auth_tag = (int_from_bytes(self.aes.encrypt(iv + b'\0\0\0\1'), 'big') ^
hash_state).to_bytes(16, 'big')
return bytes(data), auth_tag
############################################################
### SHA1 / SHA256 / SHA512
############################################################
def primes_iter():
yield from (2, 3)
primes = [3]
n = 5
while True:
for p in primes:
if p * p > n:
primes.append(n)
yield n
break
elif n % p == 0:
break
n += 2
def floor_root(n, root):
a, b = 0, n
while True:
m = (a + b) >> 1
em = m ** root
if em == n: return m
elif b - a == 1: return a
elif em < n: a = m # too small
else: b = m # too big
def sha2_constants(root, bits, n):
return [floor_root(p << (bits * root), root) & ~(-1 << bits)
for _, p in zip(range(n), primes_iter())]
class SHAx(object):
def __init__(self, msg=b''):
self.block_buffer = bytearray()
self.processed_len = 0
self.hash_state = self.initial_state
self.update(msg)
def update(self, msg):
self.processed_len += len(msg)
bb = self.block_buffer
bb.extend(msg)
bsz = self.block_size
while len(bb) >= bsz:
self.hash_state = self._process_block(consume_front(bb, bsz), self.hash_state)
return self
def digest(self):
num_bits = self.processed_len * 8
len_size = self.word_size * 2
state = self.hash_state
bb = self.block_buffer + b'\x80'
bsz = self.block_size
rem = bsz - len(bb)
if rem >= len_size:
bb += bytes(rem - len_size)
else:
bb += bytes(rem)
state = self._process_block(bb, state)
bb = bytearray(bsz - len_size)
bb += num_bits.to_bytes(len_size, 'big')
state = self._process_block(bb, state)
return b''.join(x.to_bytes(self.word_size, 'big')
for x in state[:self.output_size // self.word_size])
def copy(self):
cls = type(self)
new = cls.__new__(cls)
new.block_buffer = self.block_buffer.copy()
new.processed_len = self.processed_len
new.hash_state = self.hash_state
return new
def _process_block(self, blk, state):
assert len(blk) == self.block_size
ws, nr = self.word_size, self.num_rounds
sch = [int.from_bytes(blk[s:s+ws], 'big') for s in range(0, len(blk), ws)]
while len(sch) < nr:
sch.append(self._next_schedword(sch))
blk_state = state
for i, w in enumerate(sch):
blk_state = self._run_round(blk_state, i, w)
msk = (1 << (self.word_size * 8)) - 1
return [(a + b) & msk for a, b in zip(state, blk_state)]
def _next_schedword(self, sch): raise NotImplementedError
def _run_round(self, state): raise NotImplementedError
class SHA1(SHAx):
block_size = 64
word_size = 4
output_size = 20
num_rounds = 80
initial_state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]
f_20 = (
lambda x, y, z: (x & y) ^ (~x & z),
lambda x, y, z: x ^ y ^ z,
lambda x, y, z: (x & y) ^ (x & z) ^ (y & z),
lambda x, y, z: x ^ y ^ z,
)
k_20 = (0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6)
def _next_schedword(self, sch):
return rotl32(sch[-3] ^ sch[-8] ^ sch[-14] ^ sch[-16], 1)
def _run_round(self, state, i, w):
a, b, c, d, e = state
T = (rotl32(a, 5) +
self.f_20[i // 20](b, c, d) +
e + self.k_20[i // 20] + w) & 0xFFFFFFFF
return T, a, rotl32(b, 30), c, d
class SHA2(SHAx):
Ch = staticmethod(lambda x, y, z: (x & y) ^ (~x & z))
Maj = staticmethod(lambda x, y, z: (x & y) ^ (x & z) ^ (y & z))
def _next_schedword(self, sch):
return (self.sigma1(sch[-2]) +
sch[-7] +
self.sigma0(sch[-15]) +
sch[-16]) & self.word_mask
def _run_round(self, state, i, w):
a, b, c, d, e, f, g, h = state
T1 = h + self.Sigma1(e) + self.Ch(e,f,g) + self.K[i] + w
T2 = self.Sigma0(a) + self.Maj(a,b,c)
msk = self.word_mask
return (T1 + T2) & msk, a, b, c, (d + T1) & msk, e, f, g
class SHA256(SHA2):
block_size = 64
word_size = 4
output_size = 32
num_rounds = 64
initial_state = sha2_constants(2, 32, 8)
word_mask = 0xFFFFFFFF
Sigma0 = staticmethod(lambda x: rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22))
Sigma1 = staticmethod(lambda x: rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25))
sigma0 = staticmethod(lambda x: rotr32(x, 7) ^ rotr32(x, 18) ^ (x >> 3))
sigma1 = staticmethod(lambda x: rotr32(x, 17) ^ rotr32(x, 19) ^ (x >> 10))
K = sha2_constants(3, 32, num_rounds)
class SHA384(SHA2):
block_size = 128
word_size = 8
output_size = 48
num_rounds = 80
initial_state = sha2_constants(2, 64, 16)[8:]
word_mask = 0xFFFFFFFFFFFFFFFF
Ch = staticmethod(lambda x, y, z: (x & y) ^ (~x & z))
Maj = staticmethod(lambda x, y, z: (x & y) ^ (x & z) ^ (y & z))
Sigma0 = staticmethod(lambda x: rotr64(x, 28) ^ rotr64(x, 34) ^ rotr64(x, 39))
Sigma1 = staticmethod(lambda x: rotr64(x, 14) ^ rotr64(x, 18) ^ rotr64(x, 41))
sigma0 = staticmethod(lambda x: rotr64(x, 1) ^ rotr64(x, 8) ^ (x >> 7))
sigma1 = staticmethod(lambda x: rotr64(x, 19) ^ rotr64(x, 61) ^ (x >> 6))
K = sha2_constants(3, 64, num_rounds)
############################################################
### HMAC
############################################################
class HMAC(object):
def __init__(self, key, msg=b'', digestmod=None):
bsz = digestmod.block_size
if len(key) > bsz:
key = digestmod(key).digest()
if len(key) < bsz:
key = key.ljust(bsz, b'\0')
self.inner = digestmod(xor_bytes(key, b'\x36' * bsz))
self.outer = digestmod(xor_bytes(key, b'\x5C' * bsz))
self.inner.update(msg)
def update(self, msg):
self.inner.update(msg)
return self
def digest(self):
outer = self.outer.copy()
outer.update(self.inner.digest())
return outer.digest()
def copy(self):
cls = type(self)
new = cls.__new__(cls)
new.inner = self.inner.copy()
new.outer = self.outer.copy()
return new
############################################################
### Elliptic Curves
############################################################
class ECCurve(object):
def __init__(self, p, a, b, n, gx, gy):
self.p, self.a, self.b, self.n = p, a, b, n
self.octets = min_bytes_for_int(p)
self.g = ECPoint(gx, gy, self)
def inv(self, x):
p = self.p
t, nt = 0, 1
r, nr = p, x % p
while nr:
q = r // nr
t, nt = nt, t - q * nt
r, nr = nr, r - q * nr
t %= p
assert (t * x) % p == 1
return t
class ECPoint(object):
def __init__(self, x, y, curve):
c = self.curve = curve
self.x, self.y = x % c.p, y % c.p
if (x or y) and (x ** 2 - (y ** 3 + c.a * x + c.b)) % c.p == 0:
raise ValueError('point not on curve')
def __bool__(self):
return bool(self.x or self.y)
def __add__(a, b):
c = a.curve
if a.curve is not b.curve: raise ValueError('curve mismatch')
if not a: return b
if not b: return a
x1, y1, x2, y2 = a.x, a.y, b.x, b.y
if x1 == x2 and (y1 + y2) % c.p == 0: return ECPoint(0, 0, c)
if x1 == x2 and y1 == y2: return a * 2
l = ((y2 - y1) * c.inv(x2 - x1)) % c.p
x3 = l * l - x1 - x2
y3 = l * (x1 - x3) - y1
return ECPoint(x3, y3, c)
def __mul__(p, s):
c = p.curve
if not p: return ECPoint(0, 0, c)
if s == 2:
x1, y1 = p.x, p.y
l = ((3 * x1 * x1 + c.a) * c.inv(2 * y1)) % c.p
x3 = l * l - 2 * x1
y3 = l * (x1 - x3) - y1
return ECPoint(x3, y3, c)
else:
r = ECPoint(0, 0, c)
while s:
if s & 1: r += p
p, s = p * 2, s >> 1
return r
def __bytes__(self):
c = self.curve
return b''.join((b'\4',
self.x.to_bytes(c.octets, 'big'),
self.y.to_bytes(c.octets, 'big')))
@staticmethod
def from_bytes(data, curve):
if data and data[0] != 4: raise ValueError('uncompressed only')
if len(data) != 1 + 2 * curve.octets: raise ValueError('wrong size')
x = int.from_bytes(data[1:1+curve.octets], 'big')
y = int.from_bytes(data[1+curve.octets:], 'big')
return ECPoint(x, y, curve)
############################################################
### RSA
############################################################
class RSAPublicKey(object):
def __init__(self, m, e):
self.m, self.e = m, e
self.size = min_bytes_for_int(m)
def encrypt(self, data):
b = b''.join((b'\0\2', urandom_nonzero(self.size - len(data) - 3), b'\0', data))
return pow(int.from_bytes(b, 'big'), self.e, self.m).to_bytes(self.size, 'big')
def verify(self, data, signature, expected_hash_algo):
if len(signature) != self.size: raise ValueError('wrong size')
x = pow(int.from_bytes(signature, 'big'), self.e, self.m)
b = x.to_bytes(self.size, 'big')
if b[:2] != b'\0\1': raise ValueError('bad signature')
b = b[2:].lstrip(b'\xFF')
if b[0] != 0: raise ValueError('bad signature')
(sig_algo, _), sig_hash = parse_asn1(b[1:], single=True)
if (X509_HASH_ALGOS[sig_algo.value] is not expected_hash_algo or
sig_hash.value != expected_hash_algo(data).digest()):
raise ValueError('bad signature')
############################################################
### ASN.1
############################################################
class ASN1BitString(object):
def __init__(self, content_bytes, unused_bits):
self.content_bytes, self.unused_bits = content_bytes, unused_bits
if not 0 <= unused_bits <= 7: raise ValueError('invalid number of unused bits')
if content_bytes[-1] & ((1 << unused_bits) - 1): raise ValueError('unused bits not zero')
def __bytes__(self):
if self.unused_bits != 0: raise ValueError('not even octets')
return self.content_bytes
def __int__(self):
cb, nb = self.content_bytes, len(self.content_bytes) * 8
n = int.from_bytes(cb, 'big')
return int('{:0{}b}'.format(n, nb)[::-1], 2) # reverse bit order
class ASN1Node(object):
RAW_TO_VALUE = {
1: lambda raw: bool(raw[0]) if len(raw) == 1 else int(''), # Boolean
2: lambda raw: int.from_bytes(raw, 'big', signed=True), # Integer
3: lambda raw: ASN1BitString(bytes(raw[1:]), raw[0]), # BitString
4: lambda raw: bytes(raw), # OctetString
5: lambda raw: None if raw == b'' else int(''), # Null
6: lambda raw: __class__.__parse_oid(bytes(raw)), # OID
12: lambda raw: str(raw, 'utf-8'), # UTF8String
18: lambda raw: str(raw, 'ascii'), # NumericString
19: lambda raw: str(raw, 'ascii'), # PrintableString
20: lambda raw: str(raw, 'ascii'), # TeletexString
21: lambda raw: str(raw, 'ascii'), # VideotexString
22: lambda raw: str(raw, 'ascii'), # IA5String
23: lambda raw: __class__.__parse_time(str(raw, 'ascii')), # UTCTime
24: lambda raw: __class__.__parse_time(str(raw, 'ascii')), # GeneralizedTime
28: lambda raw: str(raw, 'utf-8'), # UniversalString
}
def __init__(self, klass, constructed, tag, raw):
self.klass, self.constructed, self.tag = klass, constructed, tag
self.raw, self.value = raw, None
def __getitem__(self, index):
return self.value[index]
def __len__(self):
return len(self.value)
def __iter__(self):
return iter(self.value)
def __repr__(self):
if self.klass:
return '<{}/{}: {}>'.format(self.klass, self.tag, repr(self.value))
return '<{}>'.format(repr(self.value))
def __parse_time(raw):
for fmt in ('%y%m%d%H%M%SZ', '%Y%m%d%H%M%SZ'):
try:
return datetime.strptime(raw, fmt)
except ValueError:
pass
raise ValueError('invalid time string: {}'.format(raw))
def __parse_oid(raw):
cur, subs = None, []
for x in raw:
cur = (cur or 0) << 7 | (x & 0x7F)
if not (x & 0x80):
subs.append(cur)
cur = None
if cur is not None: raise ValueError('unfinished OID')
x, y = 2, subs[0] - 80
while y < 0: x, y = x - 1, y + 40
subs[0:1] = [x, y]
return '.'.join(str(x) for x in subs)
def parse_asn1(data, *, single=False, decoder=None):
if type(data) is not memoryview: data = memoryview(data)
nodes = []
while data:
klass, constructed, tag = data[0] >> 6, data[0] >> 5 & 0x1, data[0] & 0x1F
if tag == 0x1F: raise NotImplementedError('multi-byte ident unsupported')
length = data[1]
length_length = 0
if length == 0xFF: raise NotImplementedError('indefinite length unsupported')
if length & 0x80:
length_length = length & 0x7F
length_bytes = data[2:2+length_length]
if len(length_bytes) != length_length: raise ValueError('unexpected end of length')
length = int.from_bytes(length_bytes, 'big')
header, data = partition_data(data, 2 + length_length)
raw, data = partition_data(data, length)
node = ASN1Node(klass, constructed, tag, bytes(header) + bytes(raw))
nodes.append(node)
if constructed:
node.value = parse_asn1(raw, decoder=decoder)
elif klass != 0x0 and decoder:
node.value = decoder(klass, tag, raw)
else:
node.value = ASN1Node.RAW_TO_VALUE[tag](raw)
if single:
[nodes] = nodes
return nodes
def asn1_find_child_with_tag(node, cls, tag):
return next((x for x in node if x.klass == cls and x.tag == tag), None)
def asn1_get_node_for_pair_key(node, key_value, unwrap_levels=0):
for _ in range(unwrap_levels): node = (x for [x] in node)
node = list(node)
return next((v for k, *v in node if k.value == key_value), None)
############################################################
### X.509
############################################################
X509_HASH_ALGOS = {
'2.16.840.1.101.3.4.2.1': SHA256,
'2.16.840.1.101.3.4.2.2': SHA384,
'1.3.14.3.2.26': SHA1,
}
X509_RSA_HASH_ALGOS = {
'1.2.840.113549.1.1.11': SHA256,
'1.2.840.113549.1.1.12': SHA384,
'1.2.840.113549.1.1.5': SHA1,
}
def x509_san_decoder(klass, tag, raw):
if klass != 2 or tag != 2: raise ValueError('only DNS SAN supported')
return str(raw, 'ascii')
class X509Cert(object):
def __init__(self, tree):
'tree is result from parse_asn1(data, single=True)'
self.tree = tree
if not (tree[0][0].klass == 0x2 and
tree[0][0].tag == 0 and
tree[0][0][0].value == 2):
# not a v3 cert
tree[0].value.insert(0, None)
if tree[0][2].raw != tree[1].raw:
raise ValueError('cert has algo mismatch')
def get_extension_data(self, oid):
cert_ext = only_or_none(asn1_find_child_with_tag(self.tree[0], 0x2, 3))
if cert_ext is None: return None
ext_data_nodes = asn1_get_node_for_pair_key(cert_ext, oid)
return ext_data_nodes[-1].value if ext_data_nodes is not None else None
def get_subject_bytes(self):
return self.tree[0][5].raw
def get_issuer_bytes(self):
return self.tree[0][3].raw
def has_rsa_key(self):
(algo, _), _ = self.tree[0][6]
return algo.value == '1.2.840.113549.1.1.1'
def extract_rsa_key(self):
if not self.has_rsa_key(): raise NotImplementedError('non-RSA key')
pk_m, pk_e = parse_asn1(bytes(self.tree[0][6][1].value), single=True)
return RSAPublicKey(pk_m.value, pk_e.value)
def verify_validity_period(self, now_dt):
valid_start, valid_end = self.tree[0][4]
valid_start, valid_end = valid_start.value, valid_end.value
if not valid_start <= now_dt <= valid_end:
raise ValueError('cert has expired or used too early')
def extract_common_name(self):
cn_node = only_or_none(asn1_get_node_for_pair_key(self.tree[0][5], '2.5.4.3', 1))
return cn_node.value if cn_node is not None else None
def extract_subj_alt_names(self):
san_ext_data = self.get_extension_data('2.5.29.17')
if san_ext_data is None: return []
san_ext = parse_asn1(san_ext_data, single=True, decoder=x509_san_decoder)
return [n.value for n in san_ext]
def verify_desired_key_usage(self, desired_key_usage):
key_usg_data = self.get_extension_data('2.5.29.15')
if key_usg_data is not None:
key_usg_bit_str = parse_asn1(key_usg_data, single=True)
key_usg = int(key_usg_bit_str.value)
if (key_usg & desired_key_usage) != desired_key_usage:
raise ValueError('key used for wrong purpose')
def verify_is_cert_authority(self, cert_idx):
basic_constraints_data = self.get_extension_data('2.5.29.19')
if basic_constraints_data is None: raise ValueError('no basic constraints found')
basic_constraints = parse_asn1(basic_constraints_data, single=True)
if not (len(basic_constraints) > 0 and
type(basic_constraints[0].value) is bool and
basic_constraints[0].value):
raise ValueError('non-CA cert used as CA')
maybe_path_len = basic_constraints[-1].value
if type(maybe_path_len) is int and cert_idx - 1 > maybe_path_len:
raise ValueError('cert chain too long')
def verify_cert_against_issuer(self, issuer):
if self.get_issuer_bytes() != issuer.get_subject_bytes():
raise ValueError('invalid cert chain')
algo, _ = self.tree[1]
expected_hash_algo = X509_RSA_HASH_ALGOS[algo.value]
issuer.extract_rsa_key().verify(self.tree[0].raw,
bytes(self.tree[2].value),
expected_hash_algo)
class X509CertStore(object):
__DEFAULT = None
def __init__(self, filename):
self.store = store = {}
with open(filename, 'rb') as fd:
lines = [x.rstrip() for x in fd]
begin_lines = [i for i, x in enumerate(lines) if x == b'-----BEGIN CERTIFICATE-----']
end_lines = [i for i, x in enumerate(lines) if x == b'-----END CERTIFICATE-----']
if (len(begin_lines) != len(end_lines) or
not all(a < b for a, b in zip(begin_lines, end_lines))):
raise ValueError('badly formed cert bundle')
for begin, end in zip(begin_lines, end_lines):
cert_b64 = b''.join(lines[begin+1:end])