-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmakepw.py
executable file
·10232 lines (10188 loc) · 153 KB
/
makepw.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
#!/usr/bin/python
# Copyright 2018 by Eric M. Hopper
# Licensed under the GNU Public License version 3 or any later version
from __future__ import print_function
"""A utility for generating passwords that pass most sites ridiculous password
rules from a master password using repeated hashing with the site name as a
salt.
"""
__author__ = "Eric M. Hopper"
__copyright__ = "Copyright 2018, Eric Hopper"
__license__ = "GPLv3+"
__version__ = "1.0"
import binascii
import hmac
import hashlib
import getpass
try:
import argparse
except ImportError:
import optparse
argparse = optparse
optparse.ArgumentParser = optparse.OptionParser
optparse.ArgumentParser.add_argument = optparse.ArgumentParser.add_option
import pkg_resources
import sys
import struct
import os
import os.path
try:
from urllib2 import urlopen
except ImportError:
# Assume Python3
from urllib.request import urlopen
try:
# Python 2
readstr = raw_input
def binxor(a, b):
return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(a, b))
except NameError:
# Python 3
readstr = input
def binxor(a, b):
return bytes(x ^ y for x, y in zip(a, b))
def pbkdf2(key, salt, iters, hmod=hashlib.sha256):
"""Computes the PKCS#5 v2.0 PBKDF2 function given a key, a salt
and a number of iterations, and an optional hashing module. The
hashing module will be used as the hashing module for HMAC.
This function only computes one block worth of key material."""
try:
# Python 2
irange = xrange
except NameError:
# Python 3
irange = range
key = as_bytes(key)
salt = as_bytes(salt)
try:
iters = int(iters)
except ValueError:
raise TypeError("iters must be an integer.")
if iters <= 0:
raise ValueError("Too few iterations.")
hmac_con = hmac.HMAC
result = None
salt = salt + struct.pack("!L", 1)
for i in irange(0, iters):
hasher = hmac_con(key=key, digestmod=hmod)
hasher.update(salt)
salt = hasher.digest()
if result is None:
result = salt
else:
result = binxor(result, salt)
return result
def not_pbkdf2(key, salt, iters, hmod=hashlib.sha256):
"""An iterated hash function that doesn't follow the PBKDF2 standard.
This function has been replaced with a PBKDF2 version on the theory that
the people who created the standard knew what they were doing.
It's being kept around for old passwords generated using it."""
try:
irange = xrange
except NameError:
irange = range
key = as_bytes(key)
salt = as_bytes(salt)
try:
iters = int(iters)
except ValueError:
raise TypeError("iters must be an integer.")
if iters <= 0:
raise ValueError("Too few iterations.")
hmac_con = hmac.HMAC
for i in irange(0, iters):
hasher = hmac_con(key=key, digestmod=hmod)
hasher.update(salt)
salt = hasher.digest()
return salt
def bytes_as_int(bstr):
"""Convert a bunch of bytes into an int both Python 2 and 3."""
try:
return int.from_bytes(bstr, 'big')
except AttributeError:
return int(binascii.b2a_hex(bstr), 16)
def as_bytes(arg):
"""Transform any iterable over bytes into bytes."""
try:
arg = bytes().join(arg)
except TypeError:
args = object()
if not isinstance(arg, bytes):
raise TypeError("Expected bytes, got something else.")
return arg
def mk_arg_parser():
parser = argparse.ArgumentParser(description="Generate a site password "
"from a master password and a site name.")
parser.add_argument('--iterations', '-i',
metavar='ITERS', type=int, default=200000,
help="Number of hash iterations. Defaults to 200000. "
"For the original behavior of a non-iterated hash, "
"use an iteration count of 0.")
parser.add_argument('--site', '-s',
metavar='SITE', type=str,
help="Unique site or account identifier, usually the"
" last two components of site domain name (aka"
" slashdot.org).")
parser.add_argument('--extra', '-e', action='store_true', default=False,
help="Backwards compatility - equivalent to "
"--format stupid_policy14")
parser.add_argument('--old', '-o', action='store_true', default=False,
help="Use old non-PBKDF2 function for generating the "
"password. Not relevant with -r")
parser.add_argument('--format', '-f',
metavar='FORMAT', type=str, default=None,
help="Output format of resulting password. Defaults"
" to 'stupid_policy13'. Use --list-formats for a"
" list of supported formats.")
parser.add_argument('--list-formats', '-l', action='store_true',
default=False,
help="Print out a list of supported formats,"
" like --help, this short-circuits any other function.")
parser.add_argument('--random', '-r', action='store_true',
help="Use the OS secure random number generation to"
" creae a random password instead of asking for a"
" master password. Useful for generating master"
" passwords, or with the xkcd algorithm. Implies"
" --no-check and ignores the site name and --iterations.")
parser.add_argument('--no-check', '-n', action='store_true', default=False,
help="Do not print out hash for check_site site. "
"This hash can help you tell if you entered the "
"wrong password.")
try:
old = argparse.OptionParser
old = parser.parse_args
parser.parse_args = lambda a: old(a)[0]
except AttributeError:
pass
return parser
def get_site(argsite):
if argsite is not None:
sitename = argsite
else:
sitename = readstr("Last two components of site name "
"(aka slashdot.org): ")
return sitename.encode('utf-8')
def gen_short_pw(hashval):
"""Generate a 13 character password with 60 bits of entropy that probably
meets various silly password requirements."""
hashval = as_bytes(hashval)
resultb64 = binascii.b2a_base64(hashval)
output = b'0' + resultb64[0:5] + b'*' + resultb64[5:10] + b'l'
return output.decode('ascii')
def gen_long_pw(hashval):
"""Generate a 14 character password with about 75 bits of entropy that
that almost certainly meets various silly password requirements."""
hashval = as_bytes(hashval)
resultb64 = binascii.b2a_base64(hashval)
resultint = bytes_as_int(hashval)
uppercase = ''.join(chr(x) for x in \
range(ord(b'A'), ord(b'Z'))).encode('ascii')
lowercase = ''.join(chr(x) for x in \
range(ord(b'a'), ord(b'z'))).encode('ascii')
digits = ''.join(chr(x) for x \
in range(ord(b'0'), ord(b'9'))).encode('ascii')
symbols = b'*/+'
size = 11
split = 6
if len(frozenset(uppercase) & frozenset(resultb64[0:size])) > 0:
letterchoices = lowercase
else:
letterchoices = uppercase
letter = resultint % len(letterchoices)
resultint = resultint // len(letterchoices)
symbol = resultint % len(symbols)
resultint = resultint // len(symbols)
digit = resultint % len(digits)
output = digits[digit:digit+1] + resultb64[0:split] + \
symbols[symbol:symbol+1] + resultb64[split:size] + \
letterchoices[letter:letter+1]
return output.decode('ascii')
def gen_xkcd_pw(numwords, randbytes):
lstfile = urlopen('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-no-swears.txt')
wordlist = tuple(lstfile.read().split())
lstfile.close()
wordlist = tuple(w.decode('utf-8') for w in wordlist if len(w) >= 3)
randbigint = bytes_as_int(randbytes)
pw = u''
for i in range(0, numwords):
pw += wordlist[randbigint % len(wordlist)].capitalize()
randbigint //= len(wordlist)
return pw
def print_formats():
print("""List of password formats:
stupid_policy13 - Alphanumeric characters with at least 1 uppercase,
1 lowercase, one number and one symbol. Designed to satisfy
most stupid password policies. About 60 bits of entropy.
stupid_policy14 - The same as above, buy slightly longer and varied for
75 bits of entropy.
xkcd4 - Four random capitalized common English words of 5 letters
or more, chosen from a list of 8813 for 52 bits of
entropy. The word list is all words >= 3 letters from
https://github.com/first20hours/google-10000-english . The
name and idea comes from https://xkcd.com/936
xkcd5 - Same as previous, but with 5 words instead, for about 66
bits of entropy.
xkcd6 - Same as xkcd4, but with 6 words. Has about 79 bits of
entropy.
* Note that xkcd passwords have more effective entropy than
their 'official' entropy values because an attacker will
have to try a lot of passwords where no part of the
password comes from a dictionary.
""")
pass
# https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-usa-no-swears-medium.txt
def random_password_seed(args):
return os.urandom(32)
def hashed_password_seed(args):
sitename = get_site(args.site)
key = getpass.getpass().encode('utf-8')
if not args.no_check or args.random:
check_result = pbkdf2(key, b'check_site', 100)
print("check_site hash is: %s" % gen_long_pw(check_result))
if args.iterations == 0:
hasher = hmac.HMAC(key=key, digestmod=hashlib.sha256)
hasher.update(sitename)
result = hasher.digest()
elif args.old:
result = not_pbkdf2(key, sitename, args.iterations)
else:
result = pbkdf2(key, sitename, args.iterations)
return result
def format_pw(pwfmt, randbytes):
if pwfmt == 'stupid_policy13':
return gen_short_pw(randbytes)
elif pwfmt == 'stupid_policy14':
return gen_long_pw(randbytes)
elif pwfmt.startswith('xkcd'):
try:
numwords = int(pwfmt[4:])
if 4 <= numwords <= 6:
return gen_xkcd_pw(numwords, randbytes)
except ValueError:
pass
print("Unknown format '{}', try `--list-formats` to get a list of valid"
" formats.".format(pwfmt), file=sys.stderr)
raise SystemExit(2)
def main(argv):
args = mk_arg_parser().parse_args(argv)
if args.list_formats:
print_formats()
return
if args.random:
result = random_password_seed(args)
else:
result = hashed_password_seed(args)
if args.format:
result = format_pw(args.format, result)
elif args.extra:
result = format_pw("stupid_policy14", result)
else:
result = format_pw("stupid_policy13", result)
print(result)
def entrypoint():
main(sys.argv[1:])
# The following list is a bzip2 compressed and base64 encoded version of the
# list that can be fetched from the following URL:
#
# https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-no-swears.txt
word_data = (
'the',
'of',
'and',
'to',
'a',
'in',
'for',
'is',
'on',
'that',
'by',
'this',
'with',
'i',
'you',
'it',
'not',
'or',
'be',
'are',
'from',
'at',
'as',
'your',
'all',
'have',
'new',
'more',
'an',
'was',
'we',
'will',
'home',
'can',
'us',
'about',
'if',
'page',
'my',
'has',
'search',
'free',
'but',
'our',
'one',
'other',
'do',
'no',
'information',
'time',
'they',
'site',
'he',
'up',
'may',
'what',
'which',
'their',
'news',
'out',
'use',
'any',
'there',
'see',
'only',
'so',
'his',
'when',
'contact',
'here',
'business',
'who',
'web',
'also',
'now',
'help',
'get',
'pm',
'view',
'online',
'c',
'e',
'first',
'am',
'been',
'would',
'how',
'were',
'me',
's',
'services',
'some',
'these',
'click',
'its',
'like',
'service',
'x',
'than',
'find',
'price',
'date',
'back',
'top',
'people',
'had',
'list',
'name',
'just',
'over',
'state',
'year',
'day',
'into',
'email',
'two',
'health',
'n',
'world',
're',
'next',
'used',
'go',
'b',
'work',
'last',
'most',
'products',
'music',
'buy',
'data',
'make',
'them',
'should',
'product',
'system',
'post',
'her',
'city',
't',
'add',
'policy',
'number',
'such',
'please',
'available',
'copyright',
'support',
'message',
'after',
'best',
'software',
'then',
'jan',
'good',
'video',
'well',
'd',
'where',
'info',
'rights',
'public',
'books',
'high',
'school',
'through',
'm',
'each',
'links',
'she',
'review',
'years',
'order',
'very',
'privacy',
'book',
'items',
'company',
'r',
'read',
'group',
'need',
'many',
'user',
'said',
'de',
'does',
'set',
'under',
'general',
'research',
'university',
'january',
'mail',
'full',
'map',
'reviews',
'program',
'life',
'know',
'games',
'way',
'days',
'management',
'p',
'part',
'could',
'great',
'united',
'hotel',
'real',
'f',
'item',
'international',
'center',
'ebay',
'must',
'store',
'travel',
'comments',
'made',
'development',
'report',
'off',
'member',
'details',
'line',
'terms',
'before',
'hotels',
'did',
'send',
'right',
'type',
'because',
'local',
'those',
'using',
'results',
'office',
'education',
'national',
'car',
'design',
'take',
'posted',
'internet',
'address',
'community',
'within',
'states',
'area',
'want',
'phone',
'dvd',
'shipping',
'reserved',
'subject',
'between',
'forum',
'family',
'l',
'long',
'based',
'w',
'code',
'show',
'o',
'even',
'black',
'check',
'special',
'prices',
'website',
'index',
'being',
'women',
'much',
'sign',
'file',
'link',
'open',
'today',
'technology',
'south',
'case',
'project',
'same',
'pages',
'uk',
'version',
'section',
'own',
'found',
'sports',
'house',
'related',
'security',
'both',
'g',
'county',
'american',
'photo',
'game',
'members',
'power',
'while',
'care',
'network',
'down',
'computer',
'systems',
'three',
'total',
'place',
'end',
'following',
'download',
'h',
'him',
'without',
'per',
'access',
'think',
'north',
'resources',
'current',
'posts',
'big',
'media',
'law',
'control',
'water',
'history',
'pictures',
'size',
'art',
'personal',
'since',
'including',
'guide',
'shop',
'directory',
'board',
'location',
'change',
'white',
'text',
'small',
'rating',
'rate',
'government',
'children',
'during',
'usa',
'return',
'students',
'v',
'shopping',
'account',
'times',
'sites',
'level',
'digital',
'profile',
'previous',
'form',
'events',
'love',
'old',
'john',
'main',
'call',
'hours',
'image',
'department',
'title',
'description',
'non',
'k',
'y',
'insurance',
'another',
'why',
'shall',
'property',
'class',
'cd',
'still',
'money',
'quality',
'every',
'listing',
'content',
'country',
'private',
'little',
'visit',
'save',
'tools',
'low',
'reply',
'customer',
'december',
'compare',
'movies',
'include',
'college',
'value',
'article',
'york',
'man',
'card',
'jobs',
'provide',
'j',
'food',
'source',
'author',
'different',
'press',
'u',
'learn',
'sale',
'around',
'print',
'course',
'job',
'canada',
'process',
'teen',
'room',
'stock',
'training',
'too',
'credit',
'point',
'join',
'science',
'men',
'categories',
'advanced',
'west',
'sales',
'look',
'english',
'left',
'team',
'estate',
'box',
'conditions',
'select',
'windows',
'photos',
'gay',
'thread',
'week',
'category',
'note',
'live',
'large',
'gallery',
'table',
'register',
'however',
'june',
'october',
'november',
'market',
'library',
'really',
'action',
'start',
'series',
'model',
'features',
'air',
'industry',
'plan',
'human',
'provided',
'tv',
'yes',
'required',
'second',
'hot',
'accessories',
'cost',
'movie',
'forums',
'march',
'la',
'september',
'better',
'say',
'questions',
'july',
'yahoo',
'going',
'medical',
'test',
'friend',
'come',
'dec',
'server',
'pc',
'study',
'application',
'cart',
'staff',
'articles',
'san',
'feedback',
'again',
'play',
'looking',
'issues',
'april',
'never',
'users',
'complete',
'street',
'topic',
'comment',
'financial',
'things',
'working',
'against',
'standard',
'tax',
'person',
'below',
'mobile',
'less',
'got',
'blog',
'party',
'payment',
'equipment',
'login',
'student',
'let',
'programs',
'offers',
'legal',
'above',
'recent',
'park',
'stores',
'side',
'act',
'problem',
'red',
'give',
'memory',
'performance',
'social',
'q',
'august',
'quote',
'language',
'story',
'sell',
'options',
'experience',
'rates',
'create',
'key',
'body',
'young',
'america',
'important',
'field',
'few',
'east',
'paper',
'single',
'ii',
'age',
'activities',
'club',
'example',
'girls',
'additional',
'password',
'z',
'latest',
'something',
'road',
'gift',
'question',
'changes',
'night',
'ca',
'hard',
'texas',
'oct',
'pay',
'four',
'poker',
'status',
'browse',
'issue',
'range',
'building',
'seller',
'court',
'february',
'always',
'result',
'audio',
'light',
'write',
'war',
'nov',
'offer',
'blue',
'groups',
'al',
'easy',
'given',
'files',
'event',
'release',
'analysis',
'request',
'fax',
'china',
'making',
'picture',
'needs',
'possible',
'might',
'professional',
'yet',
'month',
'major',
'star',
'areas',
'future',
'space',
'committee',
'hand',
'sun',
'cards',
'problems',
'london',
'washington',
'meeting',
'rss',
'become',
'interest',
'id',
'child',
'keep',
'enter',
'california',
'share',
'similar',
'garden',
'schools',
'million',
'added',
'reference',
'companies',
'listed',
'baby',
'learning',
'energy',
'run',