-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpwhashck
More file actions
executable file
·951 lines (796 loc) · 34 KB
/
Copy pathpwhashck
File metadata and controls
executable file
·951 lines (796 loc) · 34 KB
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
#!/usr/bin/env python3
# pwhashck (part of ossobv/vcutil) // wdoekes/2025 // Public Domain
#
# Password hash creator and hash verifier with minimal dependencies for
# Cisco and Wordpress passwords. Might be more in the future.
#
# (Optional dependencies: python3-bcrypt, python3-passlib)
#
# Primary use case is checking whether stored hashes match: for example
# to compare a Cisco "show running-config" secret with an expected
# value.
#
# Secondary use case is offline creation of hashed passwords so
# cleartext passwords don't need to be typed remotely.
#
# Currently supported algorithms:
# - Cisco Type 5 (MD5-crypt)
# - Cisco Type 7 (XOR Cipher, DO NOT USE!)
# - Cisco Type 8 (PBKDF2-HMAC-SHA256)
# - Cisco Type 9 (Scrypt)
# - Cisco SHA-512 (PBKDF2-HMAC-SHA512)
# - Wordpress bcrypt ($wp$...)
# - Wordpress phpass ($P$...)
#
# Usage examples:
#
# $ pwhashck -a cisco-type9
# Password:
# Password (again):
# $9$U2fpKV8W5CkHyU$GTyqN66V..dUILHdzUlAYms6ML.M1jyuhRcGylQhSFU
#
# $ pwhashck -a cisco \
# -H '$9$U2fpKV8W5CkHyU$GTyqN66V..dUILHdzUlAYms6ML.M1jyuhRcGylQhSFU' \
# -p goodpassword
# $9$U2fpKV8W5CkHyU$GTyqN66V..dUILHdzUlAYms6ML.M1jyuhRcGylQhSFU
#
# $ pwhashck -a cisco \
# -H '$9$U2fpKV8W5CkHyU$GTyqN66V..dUILHdzUlAYms6ML.M1jyuhRcGylQhSFU' \
# -p BADPASSWORD
# Supplied: $9$U2fpKV8W5CkHyU$GTyqN66V..dUILHdzUlAYms6ML.M1jyuhRcGylQhSFU
# Generated: $9$U2fpKV8W5CkHyU$IOUwUPn.XV4c.s5KB.GTBSSyBYND1uM/qDjisIFLuko
# mismatch!
#
import os
import sys
from argparse import ArgumentParser
from base64 import b64decode, b64encode
from collections import namedtuple
from getpass import getpass
from hashlib import md5, pbkdf2_hmac, scrypt, sha384
from hmac import new as hmac_new
from random import choice, randint
from secrets import randbits
from unittest import TestCase, expectedFailure, skipIf, main as unittest_main
try:
import passlib.hash as has_passlib
except ImportError:
has_passlib = False
try:
import bcrypt as has_bcrypt
except ImportError:
has_bcrypt = False
else:
has_bcrypt = None
if has_passlib:
def requires_passlib(func):
return func
def requires_bcrypt_or_passlib(func):
return func
elif has_bcrypt:
def requires_passlib(func):
return skipIf(True, 'requires python3-passlib')(func)
def requires_bcrypt_or_passlib(func):
return func
else:
def requires_passlib(func):
return skipIf(True, 'requires python3-passlib')(func)
def requires_bcrypt_or_passlib(func):
return skipIf(True, 'requires python3-bcrypt/passlib')(func)
# Standard base64 chars. Used for translation tables for alternate alphabets.
B64_STD = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
B64_URL = b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
Algo = namedtuple('Algo', 'id function description')
class InvalidPassword(Exception):
"""
Exception thrown if an invalid password is submitted to be hashed.
"""
pass
class InvalidHash(Exception):
"""
Exception thrown if an invalid or unknown hash is supplied.
"""
pass
class Cisco:
"""
Cisco password tools.
Original "Cisco Password Hasher" by Brett Verney (@wifiwizardofoz)
Contributors - Josh Schmelzle (@joshschmelzle), Kyle Kowalczyk(@superadm1n)
Version: v1.0 | 21-04-2021
Adapted by Walter Doekes (@wdoekes) for inclusion in this more generic
pwhashck tool that requires fewer dependencies and supports password
validation/checking.
"""
# Translate Standard Base64 table to Cisco Base64 Table (for Type8/9)
B64 = b'./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
B64_TABLE = bytes.maketrans(B64_STD, B64)
# When generating random tokens, the endianness is generally irrelevant.
# Use this constant.
ENDIAN_IRRELEVANT = 'little'
@classmethod
def pwd_check(cls, password):
"""
Checks cleartext password for invalid characters for Cisco devices
:param password: Clear text password
:raises InvalidPassword: If the password contains invalid
characters not supported by Cisco
:return: None
"""
invalid_chars = '?"'
if len(password) > 127:
raise InvalidPassword(
'Password must be between 1 and 127 characters in length')
if any(char in invalid_chars for char in password):
raise InvalidPassword(
'? and " are invalid characters for Cisco passwords')
@classmethod
def type5(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Cisco type 5
:param password: Clear text password to be hashed
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
cls.pwd_check(password)
password = password.encode()
magic = b'$1$'
saltlen = 4
if hash_str:
assert hash_str.startswith('$1$'), hash_str
salt = hash_str[3:3 + saltlen].encode()
else:
salt = (
b64encode(randbits(24).to_bytes(3, cls.ENDIAN_IRRELEVANT))
.translate(cls.B64_TABLE))
assert len(salt) == saltlen, salt
# Type 5 is md5crypt.
binhash = md5crypt(password, salt, magic)
safehash = b64encode(binhash).translate(cls.B64_TABLE)[0:22]
ciscohash = '{}{}${}'.format(
magic.decode(), salt.decode(), safehash.decode())
return ciscohash
@classmethod
def type7(cls, password: str, hash_str: str | None = None) -> str:
"""
XORs cleartext password to Cisco Type 7 (DO NOT USE)
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
cls.pwd_check(password)
if hash_str:
seed = int(hash_str[0:2], 16)
assert 0 <= seed <= 15, seed
else:
seed = randint(0, 15) # Cisco uses 0-15 range
xlat = [
0x64, 0x73, 0x66, 0x64, 0x3b, 0x6b, 0x66, 0x6f,
0x41, 0x2c, 0x2e, 0x69, 0x79, 0x65, 0x77, 0x72,
0x6b, 0x6c, 0x64, 0x4a, 0x4b, 0x44, 0x48, 0x53,
0x55, 0x42, 0x73, 0x67, 0x76, 0x63, 0x61, 0x36,
0x39, 0x38, 0x33, 0x34, 0x6e, 0x63, 0x78, 0x76,
0x39, 0x38, 0x37, 0x33, 0x32, 0x35, 0x34, 0x6b,
0x6c, 0x64, 0x66, 0x73, 0x61, 0x39, 0x38, 0x33,
0x37, 0x32, 0x34, 0x6b, 0x6c, 0x64, 0x66, 0x73,
]
res = [seed]
for i, ch in enumerate(password.encode()):
res.append(ch ^ xlat[(seed + i) & 0x3f])
return ''.join(f'{b:02X}' for b in res)
@classmethod
def type8(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Cisco Type 9
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
cls.pwd_check(password)
saltlen = 14
password = password.encode()
if hash_str:
assert hash_str.startswith('$8$'), hash_str
salt = hash_str[3:3 + saltlen].encode()
else:
salt = (
b64encode(randbits(80).to_bytes(10, cls.ENDIAN_IRRELEVANT))
.translate(cls.B64_TABLE).rstrip(b'='))
assert len(salt) == saltlen, salt
# Type 8 is pbkdf2_hmac.
binhash = pbkdf2_hmac('sha256', password, salt, 20000, dklen=32)
safehash = b64encode(binhash).translate(cls.B64_TABLE).rstrip(b'=')
ciscohash = '$8${}${}'.format(salt.decode(), safehash.decode())
return ciscohash
@classmethod
def type9(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Cisco Type 9
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
cls.pwd_check(password)
saltlen = 14
password = password.encode()
if hash_str:
assert hash_str.startswith('$9$'), hash_str
salt = hash_str[3:3 + saltlen].encode()
else:
salt = (
b64encode(randbits(80).to_bytes(10, cls.ENDIAN_IRRELEVANT))
.translate(cls.B64_TABLE).rstrip(b'='))
assert len(salt) == saltlen, salt
# Type 9 is scrypt hash.
binhash = scrypt(password, salt=salt, n=16384, r=1, p=1)[0:32]
safehash = b64encode(binhash).translate(cls.B64_TABLE).rstrip(b'=')
ciscohash = '$9${}${}'.format(salt.decode(), safehash.decode())
return ciscohash
@classmethod
def type10(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Cisco Type 10 (NOT WORKING!)
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
# Optional dependency.
from passlib.hash import sha512_crypt # python3-passlib
cls.pwd_check(password)
saltlen = 16 # or 8 for non-Cisco hashes?
rounds = 5000
password = password.encode()
if hash_str:
assert hash_str.startswith('$6$'), hash_str
if len(hash_str) > 19 and hash_str[19] == '$':
saltlen = 16
elif len(hash_str) > 11 and hash_str[11] == '$':
saltlen = 8
else:
raise InvalidHash('expected 8 or 16 character salt')
salt = hash_str[3:3 + saltlen]
# TODO: take rounds into account?
else:
salt = (
b64encode(randbits(96).to_bytes(12, cls.ENDIAN_IRRELEVANT))
.translate(cls.B64_TABLE).decode())
assert len(salt) == saltlen, salt
if False:
# Type 10 is pbkdf2_hmac?
binhash = pbkdf2_hmac('sha512', password, salt.encode(), rounds, dklen=64)
safehash = b64encode(binhash).translate(cls.B64_TABLE).rstrip(b'=')
ciscohash = '$6${}${}'.format(salt, safehash.decode())
else:
# Type 10 is sha512_crypt?
ciscohash = (
sha512_crypt.using(rounds=rounds, salt=salt).hash(password))
return ciscohash
@classmethod
def sha512(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Cisco SHA-512.
Here and there this is referenced as Type 10, but elsewhere a
Type 10 password looks different.
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
cls.pwd_check(password)
saltlen = 16 # binary salt
rounds = 5000
password = password.encode()
if hash_str:
assert hash_str.startswith('$sha512$'), hash_str
void, algo, rounds, salt, digest = hash_str.split('$')
salt = b64decode(salt.encode())
rounds = int(rounds)
else:
salt = randbits(128).to_bytes(16, cls.ENDIAN_IRRELEVANT)
assert len(salt) == saltlen, salt
digest = pbkdf2_hmac('sha512', password, salt, rounds, dklen=16)
ciscohash = '$sha512${rounds}${salt}${digest}'.format(
rounds=rounds,
salt=b64encode(salt).decode(),
digest=b64encode(digest).decode())
return ciscohash
@classmethod
def autodetect(cls, password: str, hash_str: str | None = None) -> str:
"""
Detects algorithm based on hash or chooses a default.
"""
if not hash_str:
return cls.type9(password, None)
if hash_str.startswith('$1$') and len(hash_str) == 30:
return cls.type5(password, hash_str)
if hash_str.startswith('$8$') and len(hash_str) == 61:
return cls.type8(password, hash_str)
if hash_str.startswith('$9$') and len(hash_str) == 61:
return cls.type9(password, hash_str)
# if hash_str.startswith('$6$') and len(hash_str) == 106:
# return cls.type10(password, hash_str)
if hash_str.startswith('$sha512$'):
return cls.sha512(password, hash_str)
raise InvalidHash(hash_str)
class Wordpress:
"""
Wordpress password tools.
"""
# Translate Standard Base64 table to Cisco Base64 Table (for Type8/9)
B64 = b'./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
B64_TABLE = bytes.maketrans(B64_STD, B64)
# When generating random tokens, the endianness is generally irrelevant.
# Use this constant.
ENDIAN_IRRELEVANT = 'little'
@classmethod
def phpass(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Wordpress "$P$..." style hash
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
# Optional dependency.
from passlib.hash import phpass as passlib_phpass # python3-passlib
saltlen = 8
if hash_str:
# Allow both '$P$' (Wordpress) and '$H$' (phpBB3).
assert hash_str.startswith(('$P$', '$H$')), hash_str
rounds = cls.B64.index(hash_str[3].encode())
salt = hash_str[4:4 + saltlen]
prefix = hash_str[0:3]
else:
rounds = None # use default
# No need for translate(). Since we're not stripping '=' at
# the end, the order of our alphabet doesn't matter.
salt = (
b64encode(randbits(48).to_bytes(6, cls.ENDIAN_IRRELEVANT))
.decode().replace('+', '.'))
prefix = None
assert len(salt) == saltlen, salt
hash_ = passlib_phpass.using(rounds=rounds, salt=salt).hash(password)
if prefix:
hash_ = prefix + hash_[3:] # maybe replace '$P$' with '$H$'
return hash_
@classmethod
def bcrypt(cls, password: str, hash_str: str | None = None) -> str:
"""
Hashes cleartext password to Wordpress "$wp$2y$10$..." style hash
> WordPress 6.8 will use bcrypt for password hashing
> https://github.com/WordPress/WordPress/commit/
> 05770e25c32e415a9f26383d80ed9a0a904fd3a0
:param password: Clear text password
:param hash_str: Original hash to take parameters from
:raises InvalidPassword: If the password contains invalid characters
:return: Hashed password
"""
# Optional dependency: bcrypt is fast. Passlib falls back to a
# python3 implementation if there is no bcrypt. But maybe you
# have bcrypt and not passlib.
try:
from bcrypt import hashpw as bcrypt # python3-bcrypt
except ImportError:
from passlib.hash import (
bcrypt as passlib_bcrypt) # python3-passlib OR python3-bcrypt
bcrypt = None
password = password.encode()
if hash_str:
void, wp, ident, rounds, salt_checksum_digest = hash_str.split('$')
rounds = int(rounds)
salt = salt_checksum_digest[0:22]
saltmagic = f'${ident}${rounds}${salt}'.encode()
else:
wp, ident, rounds = 'wp', '2b', 10 # '2y' is old, '2b' is new
# bcrypt_gensalt(rounds=rounds) # b'$2y$10$...'
# The bcrypt salt is rather picky. It not only uses the B64
# alphabet but also little endian bit order, which python
# b64encode does not do. So, to ensure that we're not
# setting the wrong bits, we'll simply replace the last byte
# with a new (but) valid one.
salt = (
b64encode(randbits(128).to_bytes(16, cls.ENDIAN_IRRELEVANT))
.translate(cls.B64_TABLE).rstrip(b'='))
assert len(salt) == 22, salt
salt = salt[0:21] + choice([b'.', b'O', b'e', b'u']) # 2 bits
salt = salt.decode()
saltmagic = f'${ident}${rounds}${salt}'.encode()
assert ident in ('2y', '2b'), ident
# WordPress uses bcrypt for password hashing, but bcrypt has a
# limitation - it only considers the first 72 bytes of the
# password. Anything longer is simply truncated and does not
# participate in the hash. This can weaken the security of long
# passwords.
#
# To avoid this, WordPress first passes the password through
# SHA-384 - this is called pre-hashing. As a result, a
# fixed-length string is produced, which fits within the 72-byte
# limit. This string is then processed by bcrypt.
pre_hash = b64encode(
hmac_new(b'wp-sha384', password, digestmod=sha384).digest())
assert len(pre_hash) <= 72, 'BCrypt would silently truncate'
if bcrypt:
bcrypthash = bcrypt(pre_hash, saltmagic).decode()
else:
bcrypthash = (
passlib_bcrypt.using(salt=salt, ident=ident, rounds=rounds)
.hash(pre_hash))
return "${}{}".format(wp, bcrypthash)
@classmethod
def autodetect(cls, password: str, hash_str: str | None = None) -> str:
"""
Detects algorithm based on hash or chooses a default.
"""
if not hash_str:
return cls.phpass(password, None)
if hash_str.startswith('$wp$') and len(hash_str) in (62, 63):
# 62 or 63 depending on '2' or '2y'.
return cls.bcrypt(password, hash_str)
if hash_str.startswith('$P$') and len(hash_str) == 34:
return cls.phpass(password, hash_str)
raise InvalidHash(hash_str)
def _reverse_endian_for_b64(binstr):
"""
b64encode encodes in big endian. But sometimes we want little endian.
"""
def flip6(a: int, b: int, c: int) -> int:
"""Reverse order of four 6-bit groups in 24-bit integer."""
v = (a << 16 | b << 8 | c)
flipped = (
((v & 0x3f) << 18) |
((v >> 6 & 0x3f) << 12) |
((v >> 12 & 0x3f) << 6) |
(v >> 18 & 0x3f))
return flipped.to_bytes(3, 'big')
new = bytearray()
for a, b, c in zip(binstr[0::3], binstr[1::3], binstr[2::3]):
new.extend(flip6(a, b, c))
leftover = len(binstr) % 3
if leftover == 1:
new.extend(flip6(0, 0, binstr[-1])[0:2])
if leftover == 2:
new.extend(flip6(0, binstr[-2], binstr[-1]))
return bytes(new)
def md5crypt(password: bytes, salt: bytes, magic: bytes = '$1$') -> bytes:
"""
Portable dependency free md5crypt.
Partially generated by Mr. Chat. Cleaned up.
"""
assert len(salt) in (4, 8), salt
# Step 1: Initial hash A
ctx = md5()
ctx.update(password + magic + salt)
# Step 2: Add alternate sum
alt = md5(password + salt + password).digest()
for i in range(len(password)):
ctx.update(alt[i % 16:i % 16 + 1])
# Step 3: Add bits depending on password length
i = len(password)
while i:
if i & 1:
ctx.update(b'\x00')
else:
ctx.update(password[:1])
i >>= 1
final = ctx.digest()
# Step 4: 1000 rounds of mixing
for i in range(1000):
md = md5()
if i & 1:
md.update(password)
else:
md.update(final)
if i % 3:
md.update(salt)
if i % 7:
md.update(password)
if i & 1:
md.update(final)
else:
md.update(password)
final = md.digest()
# Step 5: rearrange
rearranged = bytearray([
final[0], final[6], final[12],
final[1], final[7], final[13],
final[2], final[8], final[14],
final[3], final[9], final[15],
final[4], final[10], final[5],
final[11],
])
return _reverse_endian_for_b64(rearranged)
ALGOS = (
Algo('cisco', Cisco.autodetect, 'Cisco autodetect/default'),
Algo('cisco-type5', Cisco.type5, 'Cisco Type 5 (MD5-crypt)'),
Algo('cisco-type7', Cisco.type7, 'Cisco Type 7 (XOR Cipher, DO NOT USE!)'),
Algo('cisco-type8', Cisco.type8, 'Cisco Type 8 (PBKDF2-HMAC-SHA256)'),
Algo('cisco-type9', Cisco.type9, 'Cisco Type 9 (Scrypt)'),
Algo('cisco-sha512', Cisco.sha512, 'Cisco SHA-512'),
Algo('wordpress', Wordpress.autodetect, 'Wordpress autodetect/default'),
Algo('wordpress-bcrypt', Wordpress.bcrypt, 'Wordpress ($wp$.. >= WP 6.8)'),
Algo('wordpress-phpass', Wordpress.phpass, 'Wordpress ($P$..)'),
)
ALGODICT = dict((algo.id, algo) for algo in ALGOS)
class PwhashckTest(TestCase):
def getrandpass(self):
ENDIAN_IRRELEVANT = 'little'
return (
b64encode(randbits(128).to_bytes(16, ENDIAN_IRRELEVANT)).decode())
def generate_random_and_test(self, generate, get_salt_magic=None):
password = self.getrandpass()
generated = generate(password)
if get_salt_magic:
salt_magic, password_digest = get_salt_magic(generated)
else:
salt_magic, password_digest = generated.rsplit('$', 1)
salt_magic += '$...'
generated2 = generate(password, salt_magic)
self.assertEqual(generated, generated2)
return password, generated
class ReverseEndianForB64Test(TestCase):
def test_base64(self):
test_vectors = (
('dMxEn42/4s8zd8up',
'ExMd/24nz8s4pu8d'),
('9UvJidvsTEqgkAPU',
'JvU9svdigqETUPAk'),
)
for in_, exp in test_vectors:
out = (
b64encode(_reverse_endian_for_b64(b64decode(in_.encode())))
.decode())
self.assertEqual(out, exp)
def test_binary(self):
test_vectors = (
(b'\0', b'\0\0'),
(b'\x6a', b'\xa8\x10'),
(b'\xfc\x3f', b'\xff\x03\xc0'),
(b'\xff\x03\xc0', b'\x00\xfc?'),
(b'\xf1\xe2\xd3\xc4', b'L\xb7\xbc\x100'),
(b'\xf1\xe2\xd3\xc4\xb5', b'L\xb7\xbc\xd5#\x00'),
(b'\x33\x33\x33\xcc\xcc\xcc', b'\xcc\xcc\xcc\x33\x33\x33'),
)
for in_, exp in test_vectors:
out = _reverse_endian_for_b64(in_)
self.assertEqual(out, exp)
if len(in_) % 3 == 0:
rev = _reverse_endian_for_b64(out)
self.assertEqual(rev, in_)
class CiscoTests(PwhashckTest):
def test_cisco_autodetect_type5(self):
hash_ = '$1$e.N8$Q2P5fWCnrFAM/NeO2iYFb1'
self.assertEqual(Cisco.autodetect('abcd', hash_), hash_)
# test_cisco_autodetect_type7 <- no autodetection
def test_cisco_autodetect_type8(self):
hash_ = '$8$xPNISQRzSouZHp$x6Z8J7DhroiSoFRVO1xv7gjHGjook1Q4OGFPfcM7myI'
self.assertEqual(Cisco.autodetect('abcd', hash_), hash_)
def test_cisco_autodetect_type9(self):
hash_ = '$9$iRIslBHoCHW.An$3jTXMOGi6Lw3V6nBQbzBcEaifnCOYP9q6vRBWXV2kso'
self.assertEqual(Cisco.autodetect('abcd', hash_), hash_)
def test_cisco_autodetect_sha512(self):
hash_ = (
'$sha512$5000$Jhz6OQ7AKGJTVG6PR/7kWQ==$xE36SYeKJuc4m7xXJDnlRw==')
self.assertEqual(Cisco.autodetect('abcd', hash_), hash_)
def test_cisco_random_type5(self):
password, generated = self.generate_random_and_test(Cisco.type5)
void, one, salt, pwd = generated.split('$')
self.assertEqual([void, one, len(salt), len(pwd)], ['', '1', 4, 22])
def test_cisco_random_type7(self):
password, generated = self.generate_random_and_test(
Cisco.type7, (lambda x: (x[0:2], x[2:])))
self.assertEqual(len(generated), 50)
self.assertTrue(int(generated[0:2], 16) <= 15)
def test_cisco_random_type8(self):
password, generated = self.generate_random_and_test(Cisco.type8)
void, eight, salt, pwd = generated.split('$')
self.assertEqual([void, eight, len(salt), len(pwd)], ['', '8', 14, 43])
def test_cisco_random_type9(self):
password, generated = self.generate_random_and_test(Cisco.type9)
void, nine, salt, pwd = generated.split('$')
self.assertEqual([void, nine, len(salt), len(pwd)], ['', '9', 14, 43])
@requires_passlib
def test_cisco_random_type10(self):
password, generated = self.generate_random_and_test(Cisco.type10)
void, six, salt, pwd = generated.split('$')
self.assertEqual([void, six, len(salt), len(pwd)], ['', '6', 16, 86])
def test_cisco_random_sha512(self):
password, generated = self.generate_random_and_test(Cisco.sha512)
void, algo, rounds, salt, pwd = generated.split('$')
self.assertEqual([void, algo, rounds, len(salt), len(pwd)], [
'', 'sha512', '5000', 24, 24])
def test_cisco_type5_pass_PAssw0rd(self):
self.assertEqual(
Cisco.type5('P@ssw0rd', '$1$w1Jm$...'),
'$1$w1Jm$bCt7eJNv.CjWPwyfWcobP0')
def test_cisco_type5_pass_somepass(self):
self.assertEqual(
Cisco.type5('somepass', '$1$uOFH$...'),
'$1$uOFH$nuMn/p38pLcBGIEK9I5/n1')
def test_cisco_type7_pass_firewall_cx(self):
self.assertEqual(
Cisco.type7('firewall.cx', '07...'),
'0709285E4B1E18091B5C0814')
def test_cisco_type7_pass_PAssw0rd(self):
self.assertEqual(
Cisco.type7('P@ssw0rd', '08...'),
'08116C5D1A0E550516')
def test_cisco_type7_pass_catcat(self):
self.assertEqual(
Cisco.type7('catcat', '09...'),
'094F4F1D1A0403')
def test_cisco_type8_pass_cisco(self):
self.assertEqual(
Cisco.type8('cisco', '$8$dsYGNam3K1SIJO$...'),
'$8$dsYGNam3K1SIJO$7nv/35M/qr6t.dVc7UY9zrJDWRVqncHub1PE9UlMQFs')
def test_cisco_type8_pass_cisco_2(self):
self.assertEqual(
Cisco.type8('cisco', '$8$mTj4RZG8N9ZDOk$...'),
'$8$mTj4RZG8N9ZDOk$elY/asfm8kD3iDmkBe3hD2r4xcA/0oWS5V3os.O91u.')
def test_cisco_type8_pass_hashcat(self):
self.assertEqual(
Cisco.type8('hashcat', '$8$TnGX/fE4KGHOVU$...'),
'$8$TnGX/fE4KGHOVU$pEhnEvxrvaynpi8j4f.EMHr6M.FzU8xnZnBr/tJdFWk')
def test_cisco_type9_empty(self):
self.assertEqual(
Cisco.type9('', '$9$BRvU0Gj/aK/DLE$...'),
'$9$BRvU0Gj/aK/DLE$Tx2uI69utzmMXgUq1Y8n7j6/N2lfN8meEpzIBI/Rl4w')
def test_cisco_type9_pass_cisco(self):
self.assertEqual(
Cisco.type9('cisco', '$9$WnArItcQHW/uuE$...'),
'$9$WnArItcQHW/uuE$x5WTLbu7PbzGDuv0fSwGKS/KURsy5a3WCQckmJp0MbE')
def test_cisco_type9_pass_cisco_2(self):
self.assertEqual(
Cisco.type9('cisco', '$9$nhEmQVczB7dqsO$...'),
'$9$nhEmQVczB7dqsO$X.HsgL6x1il0RxkOSSvyQYwucySCt7qFm4v7pqCxkKM')
def test_cisco_type9_pass_hashcat(self):
self.assertEqual(
Cisco.type9('hashcat', '$9$2MJBozw/9R3UsU$...'),
'$9$2MJBozw/9R3UsU$2lFhcKvpghcyw8deP25GOfyZaagyUOGBymkryvOdfo6')
def test_cisco_sha512_pass_empty(self):
# https://github.com/BrettVerney/ciscoPWDhasher/issues/3
# https://www.attackdebris.com/?p=451
self.assertEqual(
Cisco.sha512('', '$sha512$5000$vlCP+V07DGEJ9TcSV/GpuA==$...'),
'$sha512$5000$vlCP+V07DGEJ9TcSV/GpuA==$2S8SLoECmbtb/o17ZhXuKg==')
def test_cisco_sha512_pass_cisco(self):
# https://github.com/BrettVerney/ciscoPWDhasher/issues/3
# https://www.attackdebris.com/?p=451
self.assertEqual(
Cisco.sha512('cisco', '$sha512$5000$SvZkzlRDO115YrLXsZuWCg==$...'),
'$sha512$5000$SvZkzlRDO115YrLXsZuWCg==$Yu0w7sFjhLnbtZQJ/nyp+A==')
@requires_passlib
def test_cisco_WRONG_type10_pass_testpassword(self):
# This password matches if we use passlib sha512_crypt.
# But this is not the Cisco one.
self.assertEqual(
# Taken from: https://openwall.info/wiki/john/sample-hashes
Cisco.type10('password', '$6$zWwwXKNj$...'), # short salt!!
('$6$zWwwXKNj$gLAOoZCjcr8p/.VgV/FkGC3NX7BsXys3KHYePfuIG'
'MNjY83dVxugPYlxVg/evpcVEJLT/rSwZcDMlVVf/bhf.1'))
@requires_passlib
@expectedFailure
def test_cisco_type10_pass_testpassword(self):
# This password doesn't match. Still not found.
# https://www.cisco.com/c/en/us/td/docs/routers/asr9000/software/
# asr9k-r7-8/system-security/configuration/guide/
# b-system-security-cg-asr9000-78x/configuring-aaa-services.html
self.assertEqual(
Cisco.type10('testpassword', '$6$9UvJidvsTEqgkAPU$...'),
('$6$9UvJidvsTEqgkAPU$3CL1Ei/F.E4v/Hi.UaqLwX8UsSEr9ApG6'
'c5pzhMJmZtgW4jObAQ7meAwyhu5VM/aRFJqe/jxZG17h6xPrvJWf1'))
self.assertEqual(
Cisco.type10('testpassword', '$6$MMvhlj1CzSd2nJfB$...'),
('$6$MMvhlj1CzSd2nJfB$Bbzvxzriwx4iLFg75w4zj15YK3yeoq5Uo'
'Ryc1evtSX0c4EuaMlqK.v7E3zbY1yKKxkN6rXpQuhMJOuyRHItDc1'))
class WordpressTests(PwhashckTest):
@requires_bcrypt_or_passlib
def test_wordpress_autodetect_bcrypt(self):
hash_ = (
'$wp$2y$10$h7qfnKnrwvLYe7O4hHwCAOMwAvbvfVKyIqapg4GGI.xtI0vNrmtxi')
self.assertEqual(Wordpress.autodetect('abcd', hash_), hash_)
@requires_bcrypt_or_passlib
def test_wordpress_autodetect_bcrypt_2(self):
hash_ = (
'$wp$2b$10$02XkzZGMghMFeQpsk6lwked1I0czG5XbchPAsJuWnfv4zsCiBcSRi')
self.assertEqual(Wordpress.autodetect('abcd', hash_), hash_)
@requires_passlib
def test_wordpress_autodetect_phpass_7_rounds(self):
hash_ = '$P$54lRmf8jtQqLkM5WQ6DP0lcm4hVPOo1'
self.assertEqual(Wordpress.autodetect('abcd', hash_), hash_)
@requires_passlib
def test_wordpress_autodetect_phpass_13_rounds(self):
hash_ = '$P$B2x.t.aO79h5xx1A9NaB7cnZBdjJc5.'
self.assertEqual(Wordpress.autodetect('abcd', hash_), hash_)
@requires_passlib
def test_wordpress_autodetect_phpass_19_rounds(self):
hash_ = '$P$HoFS15WRDrvrs/4wMYrK48kp2tEVSh1'
self.assertEqual(Wordpress.autodetect('abcd', hash_), hash_)
@requires_bcrypt_or_passlib
def test_wordpress_random_bcrypt(self):
def bcrypt_split(x):
rest, salt_and_pwd = x.rsplit('$', 1)
return f'{rest}${salt_and_pwd[0:22]}', salt_and_pwd[22:]
password, generated = self.generate_random_and_test(
Wordpress.bcrypt, bcrypt_split)
void, wp, id_, rnd, salt_and_pwd = generated.split('$')
self.assertEqual([void, wp, id_, rnd, len(salt_and_pwd)], [
'', 'wp', '2b', '10', 53])
@requires_passlib
def test_wordpress_random_phpass(self):
password, generated = self.generate_random_and_test(
Wordpress.phpass, (lambda x: (x[0:12], x[12:])))
void, p, salt_and_pwd = generated.split('$')
self.assertEqual([void, p, len(salt_and_pwd)], ['', 'P', 31])
@requires_passlib
def test_wordpress_phpass_empty(self):
hash_ = '$P$HjSoTlRVoaMO/6/eLHxXfdyXGc5dj..'
self.assertEqual(Wordpress.phpass('', hash_), hash_)
@requires_passlib
def test_wordpress_phpass_hashcat(self):
hash_ = '$P$984478476IagS59wHZvyQMArzfx58u.' # 'P' wordpress, joomla
self.assertEqual(Wordpress.phpass('hashcat', hash_), hash_)
hash_ = '$H$984478476IagS59wHZvyQMArzfx58u.' # 'H' phpBB3
self.assertEqual(Wordpress.phpass('hashcat', hash_), hash_)
def main(argv=None):
parser = ArgumentParser(
description=(
'Create or verify password hashes (Cisco, Wordpress, ...)'))
parser.add_argument(
'-a', '--algo', choices=[algo.id for algo in ALGOS], help=(
'Hash algorithm to use'))
parser.add_argument(
'-p', '--password', help=(
'Password to hash or verify. If omitted, you will be prompted'))
parser.add_argument(
'-H', '--hash', dest='hash_str', help=(
'Turns on check mode. Supply existing hash to verify against. '
'If hash is the empty string, you will be prompted for one.'))
args = parser.parse_args(argv)
if not args.algo:
parser.error('Algorithm -a is required')
assert False, 'does not get here'
func = ALGODICT[args.algo].function
mode = ('check' if args.hash_str is not None else 'create')
if mode == 'check':
if not args.hash_str:
args.hash_str = input('Hashed password: ')
args.hash_str = args.hash_str.rstrip() # no whitespace / CRs please
if not args.password:
args.password = getpass('Password to verify: ')
else:
if not args.password:
args.password = getpass('Password: ')
password2 = getpass('Password (again): ')
if args.password != password2:
parser.error('Password confirmation did not match')
assert False, 'does not get here'
args.password = args.password.rstrip() # no whitespace / CRs please
try:
if mode == 'create':
result = func(args.password)
print(result)
return 0
if mode == 'check':
result = func(args.password, args.hash_str)
if result != args.hash_str:
print(f'Supplied: {args.hash_str}')
print(f'Generated: {result}')
print('mismatch!', file=sys.stderr)
return 1
print(result)
return 0
except InvalidHash as e:
parser.error(f'Invalid hash -H supplied: {e}')
assert False, 'does not get here'
except InvalidPassword as e:
parser.error(f'Invalid password -p supplied: {e}')
assert False, 'does not get here'
raise NotImplementedError
if __name__ == '__main__':
if os.environ.get('RUNTESTS', '') not in ('', '0'):
unittest_main()
assert False, 'does not get here'
raise SystemExit(main())