forked from cupslab/neural_network_cracking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwd_guess.py
3219 lines (2863 loc) · 122 KB
/
pwd_guess.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 -*-
# author: William Melicher
from __future__ import print_function
import os
import sys
# This is a hack to support multiple versions of the keras library.
# It would be better to use a solution like virtualenv.
if 'KERAS_PATH' in os.environ:
sys.path.insert(0, os.environ['KERAS_PATH'])
import keras
try:
sys.stderr.write('Using keras version %s\n' % (keras.__version__))
except AttributeError as e:
pass
from keras.models import Sequential, slice_X, model_from_json
from keras.layers.core import Activation, Dense, RepeatVector, TimeDistributedDense, Dropout, Masking
from keras.layers import recurrent
import keras.utils.layer_utils as layer_utils
from keras.optimizers import SGD
try:
from seya.layers.recurrent import Bidirectional
except ImportError as e:
sys.stderr.write('Warning, cannot import Bidirectional model. You may need '
'to install or use a different version of keras\n')
Bidirectional = None
from sklearn.utils import shuffle
import numpy as np
from sqlitedict import SqliteDict
import theano
import argparse
import itertools
import string
import gzip
import csv
import logging
import cProfile
import json
import random
import multiprocessing as mp
import tempfile
import subprocess as subp
import collections
import struct
import os.path
import mmap
import bisect
import unittest
import math
import re
import io
import generator
PASSWORD_END = '\n'
FNAME_PREFIX_PREPROCESSOR = 'disk_cache.'
FNAME_PREFIX_TRIE = 'trie_nodes.'
FNAME_PREFIX_SUBPROCESS_CONFIG = 'child_process.'
FNAME_PREFIX_THEANO_COMPILE = 'theanocompiledir.'
FNAME_PREFIX_PROCESS_LOG = 'log.child_process.'
FNAME_PREFIX_PROCESS_OUT = 'out.child_process.'
FORKED_FLAG = 'forked'
# From: https://docs.python.org/3.4/library/itertools.html
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return map(lambda x: filter(lambda y: y, x),
itertools.zip_longest(*args, fillvalue=fillvalue))
class BaseTrie(object):
def increment(self, aword, weight = 1):
raise NotImplementedError()
def iterate(self, serial_type):
raise NotImplementedError()
def finish(self):
pass
config_keys = {
'trie' : lambda _: NodeTrie(),
'disk' : lambda c: DiskBackedTrie(c),
None : lambda _: BaseTrie()
}
@staticmethod
def fromConfig(config):
try:
return BaseTrie.config_keys[config.trie_implementation](config)
except KeyError as e:
logging.error('Cannot find trie type %s.',
config.trie_implementation)
class NodeTrie(BaseTrie):
def __init__(self):
self.nodes = collections.defaultdict(NodeTrie)
self.weight = 0
self._size = 0
@staticmethod
def increment_optimized(anode, aword, weight = 1):
root = anode
inc_str = aword
root.weight += weight
while len(inc_str) != 0:
next_char, inc_str = inc_str[0], inc_str[1:]
root.weight += weight
root = root.nodes[next_char]
root.weight += weight
def increment(self, aword, weight = 1):
NodeTrie.increment_optimized(self, aword, weight)
def random_iterate(self, cur = ''):
if cur != '':
yield (cur, self.weight)
for key in self.nodes:
others = self.nodes[key].random_iterate(cur + key)
for item in others:
yield item
def set(self, key, value):
node = self
for c in key:
node = node.nodes[c]
node.weight = value
def set_append(self, key, value):
node = self
for c in key:
node = node.nodes[c]
if type(node.weight) == list:
node.weight.append(value)
else:
node.weight = [value]
def get_completions(self, key):
answers = []
node = self
for c in key:
values = node.weight
if type(values) == list:
answers += values
if c in node.nodes:
node = node.nodes[c]
elif len(c) != 1:
for k in c:
if k in node.nodes:
node = node.nodes[k]
else:
return answers
else:
return answers
values = node.weight
if type(values) == list:
answers += values
return answers
def get_longest_prefix(self, key):
node = self
value, accum = 0, 0;
for i, c in enumerate(key):
if c in node.nodes:
node = node.nodes[c]
if node.weight != 0:
value, accum = node.weight, i + 1
else:
break
return key[:accum], value
def sampled_training(self, value = ''):
node_children = [(k, self.nodes[k].weight)
for k in sorted(self.nodes.keys())]
if len(node_children) == 0:
return
yield (value, node_children)
for key in self.nodes:
for item in self.nodes[key].sampled_training(value + key):
yield item
def iterate(self, serial_type):
if serial_type == 'fuzzy':
return self.sampled_training()
else:
return self.random_iterate()
class DiskBackedTrie(BaseTrie):
def __init__(self, config):
self.config = config
self.current_node = None
self.current_branch_key = None
self.weights = NodeTrie()
self.keys = []
self.fork_length = config.fork_length
def finish(self):
if self.current_branch_key is not None:
self.close_branch()
self.config.set_intermediate_info('db_trie_keys', self.keys)
self.config.set_intermediate_info('db_trie_weights', self.weights)
logging.info('Finishing disk backed trie iteration')
def make_serializer(self):
return TrieSerializer.getFactory(self.config, True)(
os.path.join(self.config.trie_intermediate_storage,
self.sanitize(self.current_branch_key)))
def sanitize(self, prefix):
assert prefix in self.keys
return FNAME_PREFIX_TRIE + str(self.keys.index(prefix))
def close_branch(self):
if self.current_branch_key is not None:
assert self.current_node is not None
self.make_serializer().serialize(self.current_node)
self.current_node = None
self.current_branch_key = None
def open_new_branch(self, key):
self.close_branch()
self.current_node = NodeTrie()
self.current_branch_key = key
self.keys.append(key)
def increment(self, aword, weight = 1):
start, end = (aword[:self.fork_length], aword[self.fork_length:])
if start != self.current_branch_key:
self.open_new_branch(start)
self.weights.increment(start, weight)
self.current_node.increment(end, weight)
def iterate_subtrees(self, serial_type):
for key in self.keys:
self.current_branch_key = key
for subitem in self.make_serializer().deserialize():
yield (key + subitem[0], subitem[1])
def iterate(self, serial_type):
self.finish()
for c in self.weights.iterate(serial_type):
yield c
for s in self.iterate_subtrees(serial_type):
yield s
self.current_branch_key = None
@classmethod
def fromIntermediate(cls, config):
answer = cls(config)
answer.keys = config.get_intermediate_info('db_trie_keys')
answer.weights = config.get_intermediate_info('db_trie_weights')
return answer
class TrieSerializer(object):
def __init__(self, fname):
self.fname = fname
def open_file(self, mode, fname = None):
return open(fname if fname else self.fname, mode)
def serialize(self, trie):
directory = os.path.dirname(self.fname)
if not os.path.exists(directory) and directory != '':
logging.info('Making directory to save %s', directory)
os.mkdir(directory)
self.do_serialize(trie)
def do_serialize(self, trie):
raise NotImplementedError()
def deserialize(self):
raise NotImplementedError()
@staticmethod
def fromConfig(config):
return TrieSerializer.getFactory(config)(config.trie_fname)
@staticmethod
def getFactory(config, intermediate_serializer = False):
if config.trie_fname == ':memory:' and not intermediate_serializer:
return lambda x: MemoryTrieSerializer(
x, config.trie_serializer_type)
elif (config.trie_intermediate_storage == ':memory:'
and intermediate_serializer):
return lambda x: MemoryTrieSerializer(
x, config.trie_serializer_type)
elif config.trie_serializer_type == 'fuzzy':
return lambda x: TrieFuzzySerializer(x, config)
elif config.trie_serializer_type == 'reg':
return lambda x: NodeTrieSerializer(x, config)
logging.error('No serializer of type %s', config.trie_serializer_type)
class MemoryTrieSerializer(TrieSerializer):
memory_cache = {}
def __init__(self, fname, serializer_type):
super().__init__(fname)
self.serializer_type = serializer_type
def serialize(self, trie):
self.memory_cache[self.fname] = trie
def deserialize(self):
trie = self.memory_cache[self.fname]
return trie.iterate(self.serializer_type)
class BinaryTrieSerializer(TrieSerializer):
_fmt = '<QQ'
_fmt_size = struct.calcsize('<QQ')
str_len_fmt = '<B'
str_len_fmt_size = struct.calcsize('B')
def __init__(self, fname, config):
super().__init__(fname)
self.max_len = config.max_len
self.encoding = config.trie_serializer_encoding
self.toc_chunk_size = config.toc_chunk_size
self.use_mmap = config.use_mmap
def do_serialize(self, trie):
records = 0
table_of_contents = {}
toc_start = -1
with self.open_file('wb') as afile:
afile.write(struct.pack(self._fmt, 0, 0))
for item in trie.iterate(self.serializer_type):
pwd, weight = item
self.write_record(afile, pwd, weight)
records += 1
if records % self.toc_chunk_size == 0:
table_of_contents[records] = afile.tell()
toc_start = afile.tell()
for key in sorted(table_of_contents.keys()):
afile.write(struct.pack(self._fmt, key, table_of_contents[key]))
assert toc_start > 0
with self.open_file('r+b') as afile:
logging.info('Wrote %s records to %s', records, self.fname)
afile.write(struct.pack(self._fmt, records, toc_start))
def deserialize(self):
with self.open_file('rb') as afile:
num_records, toc_start = struct.unpack(
self._fmt, afile.read(self._fmt_size))
for _ in range(num_records):
answer = self.read_record(afile)
if answer is None:
break
yield answer
def read_toc(self, afile):
num_records, toc_start = struct.unpack(
self._fmt, afile.read(self._fmt_size))
afile.seek(toc_start)
toc = {}
while True:
chunk = afile.read(self._fmt_size)
if len(chunk) == 0:
break
key, toc_pos = struct.unpack(self._fmt, chunk)
toc[key] = toc_pos
return toc, toc_start
def read_from_pos(self, afile, start_pos, end_pos):
afile.seek(start_pos)
while afile.tell() < end_pos:
item = self.read_record(afile)
assert item is not None
yield item
def random_access(self):
with self.open_file('rb') as afile_obj:
if self.use_mmap:
afile = mmap.mmap(afile_obj.fileno(), 0, prot = mmap.PROT_READ)
else:
afile = afile_obj
toc, toc_start = self.read_toc(afile)
toc_locations = list(map(lambda k: toc[k], sorted(toc.keys())))
start_pos = [self._fmt_size] + toc_locations
end_pos = toc_locations + [toc_start]
intervals = list(zip(start_pos, end_pos))
random.shuffle(intervals)
for interval in intervals:
start, end = interval
for item in self.read_from_pos(afile, start, end):
yield item
def read_string(self, afile):
byte_string = afile.read(self.str_len_fmt_size)
if len(byte_string) == 0:
return None
strlen, = struct.unpack(self.str_len_fmt, byte_string)
return afile.read(strlen).decode(self.encoding)
def write_string(self, afile, astring):
string_bytes = astring.encode(self.encoding)
try:
afile.write(struct.pack(self.str_len_fmt, len(string_bytes)))
except struct.error as e:
logging.critical('Error when processing string %s', astring)
raise
afile.write(string_bytes)
def write_record(self, ostream, pwd, val):
self.write_string(ostream, pwd)
self.write_value(ostream, val)
def read_record(self, afile):
astr = self.read_string(afile)
if astr is None:
return None
return (astr, self.read_value(afile))
def write_value(self, afile, value):
raise NotImplementedError
def read_value(self, afile):
raise NotImplementedError()
class NodeTrieSerializer(BinaryTrieSerializer):
serializer_type = 'reg'
def __init__(self, *args):
super().__init__(*args)
self.fmt = '<d'
self.chunk_size = struct.calcsize(self.fmt)
def write_value(self, ostream, weight):
ostream.write(struct.pack(self.fmt, weight))
def read_value(self, afile):
return struct.unpack_from(self.fmt, afile.read(self.chunk_size))[0]
class TrieFuzzySerializer(BinaryTrieSerializer):
serializer_type = 'fuzzy'
def __init__(self, *args):
super().__init__(*args)
self.in_fmt = '<H'
self.out_fmt = '<1sd'
self.in_fmt_bytes = struct.calcsize(self.in_fmt)
self.out_fmt_bytes = struct.calcsize(self.out_fmt)
def write_value(self, ostream, output_list):
ostream.write(struct.pack(self.in_fmt, len(output_list)))
for item in output_list:
char, weight = item
ostream.write(struct.pack(
self.out_fmt, char.encode(self.encoding), weight))
def read_value(self, istream):
num_rec, = struct.unpack_from(
self.in_fmt, istream.read(self.in_fmt_bytes))
record = []
for _ in range(num_rec):
out_char, out_weight = struct.unpack_from(
self.out_fmt, istream.read(self.out_fmt_bytes))
record.append((out_char.decode(self.encoding), out_weight))
return record
class CharacterTable(object):
def __init__(self, chars, maxlen, padding_character = None):
self.chars = sorted(set(chars))
self.char_indices = dict((c, i) for i, c in enumerate(self.chars))
self.indices_char = dict((i, c) for i, c in enumerate(self.chars))
self.maxlen = maxlen
self.vocab_size = len(self.chars)
self.char_list = self.chars
self.padding_character = padding_character
def pad_to_len(self, astring, maxlen = None):
maxlen = maxlen if maxlen else self.maxlen
if len(astring) > maxlen:
return astring[len(astring) - maxlen:]
if self.padding_character is not None:
return astring + (PASSWORD_END * (maxlen - len(astring)))
return astring
def encode_many(self, string_list, maxlen = None):
maxlen = maxlen if maxlen else self.maxlen
x_str_list = map(lambda x: self.pad_to_len(x, maxlen), string_list)
x_vec = np.zeros((len(string_list), maxlen, len(self.chars)),
dtype = np.bool)
for i, xstr in enumerate(x_str_list):
self._encode_into(x_vec[i], xstr)
return x_vec
def _encode_into(self, X, C):
for i, c in enumerate(C):
X[i, self.char_indices[c]] = 1
def encode(self, C, maxlen=None):
maxlen = maxlen if maxlen else self.maxlen
X = np.zeros((maxlen, len(self.chars)))
self._encode_into(X, C)
return X
def decode(self, X, calc_argmax=True):
if calc_argmax:
X = X.argmax(axis=-1)
return ''.join(self.indices_char[x] for x in X)
def get_char_index(self, character):
return self.char_indices[character]
def translate(self, astring):
return astring
@staticmethod
def fromConfig(config, tokenizer = True):
if tokenizer and config.tokenize_words:
return TokenizingCharacterTable(config)
elif (config.uppercase_character_optimization or
config.rare_character_optimization):
return OptimizingCharacterTable(
config.char_bag, config.context_length,
config.get_intermediate_info('rare_character_bag'),
config.uppercase_character_optimization,
padding_character = config.padding_character)
else:
return CharacterTable(config.char_bag, config.context_length,
padding_character = config.padding_character)
class OptimizingCharacterTable(CharacterTable):
def __init__(self, chars, maxlen, rare_characters, uppercase,
padding_character = None):
if uppercase:
self.rare_characters = ''.join(
c for c in rare_characters if c not in string.ascii_uppercase)
else:
self.rare_characters = rare_characters
char_bag = chars
for r in self.rare_characters:
char_bag = char_bag.replace(r, '')
if len(rare_characters):
char_bag += self.rare_characters[0]
self.rare_dict = dict([(char, self.rare_characters[0])
for char in self.rare_characters])
self.rare_character_preimage = {
self.rare_characters[0] : list(self.rare_characters)}
else:
self.rare_character_preimage = {}
self.rare_dict = {}
if uppercase:
for c in string.ascii_uppercase:
if c not in chars:
continue
self.rare_dict[c] = c.lower()
char_bag = char_bag.replace(c, '')
assert c.lower() in char_bag
self.rare_character_preimage[c.lower()] = [c, c.lower()]
super().__init__(char_bag, maxlen, padding_character)
for key in self.rare_dict:
self.char_indices[key] = self.char_indices[self.rare_dict[key]]
translate_table = {}
for c in chars:
if c in self.rare_dict:
translate_table[c] = self.rare_dict[c]
else:
translate_table[c] = c
self.translate_table = ''.maketrans(translate_table)
self.rare_character_postimage = {}
for key in self.rare_character_preimage:
for item in self.rare_character_preimage[key]:
self.rare_character_postimage[item] = key
def translate(self, astring):
return astring.translate(self.translate_table)
class DelegatingCharacterTable(object):
def __init__(self, ctable):
self.real_ctable = ctable
self.chars = self.real_ctable.chars
self.vocab_size = len(self.chars)
self.char_list = self.chars
def encode(self, ystr, maxlen = None):
return self.real_ctable.encode(ystr, maxlen)
def get_char_index(self, char):
return self.real_ctable.get_char_index(char)
def decode(self, X, argmax = True):
return self.real_ctable.decode(X, argmax)
def translate(self, pwd):
return self.real_ctable.translate(pwd)
def encode_many(self, xstrs):
return self.real_ctable.encode_many(xstrs)
class TokenizingCharacterTable(DelegatingCharacterTable):
def __init__(self, config):
super().__init__(CharacterTable.fromConfig(config, False))
self.token_list = list(map(
self.real_ctable.translate,
config.get_intermediate_info('most_common_tokens')))
assert (len(self.token_list) > 0 and
len(self.token_list) <= config.most_common_token_count)
assert len(set(self.token_list)) == len(self.token_list)
if len(self.token_list) < config.most_common_token_count:
logging.warning(('Token list is smaller than specified. This can '
'happen if the training set does not have enough '
'tokens. Size is %s but expected %s. '),
len(self.token_list),
config.most_common_token_count)
self.char_list = self.token_list + list(self.chars)
self.vocab_size = len(self.char_list)
self.indices_char = {}
self.char_indices = {}
for i, token in enumerate(self.token_list):
self.indices_char[i] = token
self.char_indices[token] = i
for idx in self.real_ctable.indices_char:
self.indices_char[idx + len(self.token_list)] = (
self.real_ctable.indices_char[idx])
self.maxlen = self.real_ctable.maxlen
self.tokenizer = SpecificTokenizer(self.token_list)
def decode(self, X, calc_argmax=True):
if calc_argmax:
X = X.argmax(axis=-1)
return ''.join(self.indices_char[x] for x in X)
def encode_many(self, string_list, maxlen = None):
maxlen = maxlen if maxlen else self.maxlen
x_vec = np.zeros((len(string_list), maxlen, self.vocab_size),
dtype = np.bool)
for i, xstr in enumerate(string_list):
self._encode_into(x_vec[i], xstr)
return x_vec
def get_char_index(self, char):
char = self.real_ctable.translate(char)
if len(char) == 1:
return self.real_ctable.get_char_index(char) + len(self.token_list)
else:
return self.char_indices[char]
def _encode_into(self, X, C):
if type(C) == str:
C = self.tokenizer.tokenize(self.real_ctable.translate(C))
for i, token in enumerate(C[-self.maxlen:]):
X[i, self.get_char_index(token)] = 1
if len(C) < X.shape[0]:
for j in range(len(C), self.maxlen):
X[j, self.get_char_index(PASSWORD_END)] = 1
def translate(self, pwd):
return self.real_ctable.translate(''.join(pwd))
def encode(self, C, maxlen=None):
maxlen = maxlen if maxlen else self.maxlen
X = np.zeros((maxlen, self.vocab_size), dtype = np.bool)
self._encode_into(X, C)
return X
class ScheduledSamplingCharacterTable(DelegatingCharacterTable):
def __init__(self, config):
super().__init__(CharacterTable.fromConfig(config))
self.probability_calculator = None
self.sigma = 0
self.generation_size = 0
self.generation_counter = 0
self.total_size = 0
self.generation = 0
self.generations = self.config.generations
self.config = config
def init_model(self, model):
self.probability_calculator = Guesser(model, self.config, io.StringIO())
def end_generation(self):
if self.generation == 0:
self.generation_size = self.generation_counter
self.total_size = self.config.generations * self.generation_size
self.steepness_value = - (2 / self.total_size) * math.log(
1 / self.config.final_schedule_ratio - 1 )
self.generation += 1
self.generation_counter = 0
self.set_sigma()
logging.info('Scheduled sampling sigma', self.sigma)
def set_sigma(self):
if self.generation != 0:
cur_value = (self.generation * self.generation_size +
self.generation_counter)
self.sigma = 1 - (1 / (1 + math.exp(- self.steepness_value * (
cur_value - (self.total_size / 2)))))
def generate_replacements(self, strs):
cond_probs = self.probability_calculator.batch_prob(strs)
choices = self.chars
for i in range(len(cond_probs)):
cp = cond_probs[i][0]
yield np.random.choice(choices, p=cp / np.sum(cp))
def encode_many(self, xstrs):
assert self.probability_calculator is not None
answer = self.real_ctable.encode_many(xstrs)
replacements = np.random.binomial(1, self.sigma, size = len(xstrs))
replacement_strs, replacement_idx = [], []
for i in range(len(xstrs)):
astring = xstrs[i]
if replacements[i] and len(astring) > 0:
replacement_strs.append(astring[:-1])
replacement_idx.append(i)
self.generation_counter += len(xstrs)
self.set_sigma()
if len(replacement_strs) == 0:
return answer
replacements = self.generate_replacements(replacement_strs)
for idx, char in enumerate(replacements):
answer[replacement_idx[idx]][len(
replacement_strs[idx])] = self.real_ctable.encode(
char, maxlen = 1)
return answer
class ModelSerializer(object):
def __init__(self, archfile = None, weightfile = None, versioned = False):
self.archfile = archfile
self.weightfile = weightfile
self.model_creator_from_json = model_from_json
self.versioned = versioned
self.saved_counter = 0
def save_model(self, model):
if self.archfile is None or self.weightfile is None:
logging.info(
'Cannot save model because file arguments were not provided')
return
logging.info('Saving model architecture')
with open(self.archfile, 'w') as arch:
arch.write(model.to_json())
logging.info('Saving model weights')
self.saved_counter += 1
weight_fname = self.weightfile
if self.versioned:
weight_fname += '.' + str(self.saved_counter)
model.save_weights(weight_fname, overwrite = True)
logging.info('Done saving model')
def load_model(self):
from unittest.mock import Mock
# To be able to load models
# In case bidirectional model cannot be loaded
if Bidirectional is not None:
layer_utils.Bidirectional = Bidirectional
# This is for unittesting
def mock_predict_smart_parallel(distribution, input_vec, **kwargs):
answer = []
for i in range(len(input_vec)):
answer.append([distribution.copy()])
return answer
logging.info('Loading model architecture')
with open(self.archfile, 'r') as arch:
arch_data = arch.read()
as_json = json.loads(arch_data)
if 'mock_model' in as_json:
model = Mock()
model.predict = lambda x, **kwargs: mock_predict_smart_parallel(
as_json['mock_model'], x, **kwargs)
logging.info(
'Using mock model. You should not see this in production. ')
return model
model = self.model_creator_from_json(arch_data)
logging.info('Loading model weights')
model.load_weights(self.weightfile)
logging.info('Done loading model')
return model
serializer_type_list = {}
model_type_dict = {
'GRU' : recurrent.GRU,
'LSTM' : recurrent.LSTM
}
if hasattr(recurrent, 'JZS1'):
model_type_dict['JZS1'] = recurrent.JZS1
model_type_dict['JZS2'] = recurrent.JZS2
model_type_dict['JZS3'] = recurrent.JZS3
class ModelDefaults(object):
char_bag = (string.ascii_lowercase + string.ascii_uppercase +
string.digits + '~!@#$%^&*(),.<>/?\'"{}[]\|-_=+;: `' +
PASSWORD_END)
model_type = 'JZS1'
hidden_size = 128
layers = 1
max_len = 40
min_len = 4
training_chunk = 128
generations = 20
chunk_print_interval = 1000
lower_probability_threshold = 10**-5
relevel_not_matching_passwords = True
training_accuracy_threshold = 10**-10
train_test_ratio = 10
parallel_guessing = False
fork_length = 2
rare_character_optimization = False
rare_character_optimization_guessing = False
uppercase_character_optimization = False
rare_character_lowest_threshold = 20
guess_serialization_method = 'human'
simulated_frequency_optimization = False
trie_implementation = None
trie_fname = ':memory:'
trie_intermediate_storage = ':memory:'
intermediate_fname = ':memory:'
preprocess_trie_on_disk = False
preprocess_trie_on_disk_buff_size = 100000
trie_serializer_encoding = 'utf8'
trie_serializer_type = 'reg'
save_always = True
save_model_versioned = False
randomize_training_order = True
toc_chunk_size = 1000
model_optimizer = 'adam'
guesser_intermediate_directory = 'guesser_files'
cleanup_guesser_files = True
use_mmap = True
compute_stats = False
password_test_fname = None
chunk_size_guesser = 1000
random_walk_seed_num = 1000
max_gpu_prediction_size = 25000
gpu_fork_bias = 2
cpu_limit = 8
random_walk_confidence_bound_z_value = 1.96
random_walk_confidence_percent = 5
random_walk_upper_bound = 10
no_end_word_cache = False
enforced_policy = 'basic'
pwd_list_weights = {}
dropouts = False
dropout_ratio = .25
fuzzy_training_smoothing = False
scheduled_sampling = False
final_schedule_ratio = .05
context_length = None
train_backwards = False
bidirectional_rnn = False
dense_layers = 0
dense_hidden_size = 128
secondary_training = False
secondary_train_sets = None
training_main_memory_chunksize = 1000000
tokenize_words = False
tokenize_guessing = True
most_common_token_count = 2000
probability_striation = False
prob_striation_step = 0.05
freeze_feature_layers_during_secondary_training = True
secondary_training_save_freqs = False
guessing_secondary_training = False
deep_model = False
guesser_class = None
freq_format = 'hex'
padding_character = None
def __init__(self, adict = None, **kwargs):
self.adict = adict if adict is not None else dict()
for k in kwargs:
self.adict[k] = kwargs[k]
if self.context_length is None:
self.context_length = self.max_len
def __getattribute__(self, name):
if name != 'adict' and name in self.adict:
return self.adict[name]
else:
return super().__getattribute__(name)
def __setattr__(self, name, value):
if name != 'adict':
self.adict[name] = value
else:
super().__setattr__(name, value)
@staticmethod
def fromFile(afile):
if afile is None:
return ModelDefaults()
with open(afile, 'r') as f:
try:
answer = ModelDefaults(json.load(f))
except ValueError as e:
logging.error(('Error loading config. Config file is not valid'
' JSON format. %s'), str(e))
return None
return answer
def validate(self):
if self.trie_serializer_type == 'fuzzy':
assert self.simulated_frequency_optimization
assert self.trie_implementation is not None
assert self.fork_length < self.min_len
assert self.max_len <= 255
if (self.guess_serialization_method == 'calculator' and
self.password_test_fname):
assert os.path.exists(self.password_test_fname)
if self.rare_character_optimization_guessing:
assert (self.rare_character_optimization or
self.uppercase_character_optimization)
elif (self.rare_character_optimization or
self.uppercase_character_optimization):
logging.warning(
'Without rare_character_optimization_guessing setting,'
' output guesses may ignore case or special characters')
assert self.guess_serialization_method in serializer_type_list
assert self.context_length <= self.max_len
assert self.model_type in model_type_dict
assert self.training_main_memory_chunksize > self.training_chunk
if self.guessing_secondary_training:
assert self.secondary_training
assert self.secondary_training_save_freqs
def as_dict(self):
answer = dict(vars(ModelDefaults).copy())
answer.update(self.adict)
return dict([(key, value) for key, value in answer.items() if (
key[0] != '_' and not hasattr(value, '__call__')
and not type(value) == staticmethod)])
def model_type_exec(self):
try:
return model_type_dict[self.model_type]
except KeyError as e:
logging.warning('Cannot find model type %s', self.model_type)
logging.warning('Defaulting to LSTM model')
if self.model_type == 'JZS1':
self.model_type = 'LSTM'
return self.model_type_exec()
def set_intermediate_info(self, key, value):
with SqliteDict(self.intermediate_fname) as info:
info[key] = value
info.commit()
def get_intermediate_info(self, key):
try:
with SqliteDict(self.intermediate_fname) as info:
return info[key]
except KeyError as e:
logging.error('Cannot find intermediate data %s. Looking in %s',
str(e), self.intermediate_fname)
raise
def override_from_commandline(self, cmdline):
answer = {}
for keyval in cmdline.split(';'):
if not keyval:
continue
key, _, value = keyval.partition('=')
answer[key] = type(getattr(self, key))(value)
self.adict.update(answer)
class BasePreprocessor(object):
def __init__(self, config = ModelDefaults()):
self.config = config
def begin(self, anobj):
raise NotImplementedError()
def begin_resetable(self, resetable):
self.begin(resetable.create_new())
def next_chunk(self):
raise NotImplementedError()
def reset(self):
raise NotImplementedError()
def stats(self):
self.reset()
x_vec, y_vec, weights = self.next_chunk()
count_instances = 0
while len(x_vec) != 0:
count_instances += len(x_vec)
x_vec, y_vec, weights = self.next_chunk()
logging.info('Number of training instances %s', count_instances)
return count_instances
config_keys = {
'trie' : lambda c: TriePreprocessor(c),
'disk' : lambda c: HybridDiskPreprocessor(c),
None : lambda c: Preprocessor(c)
}