Debian Codegraph @

lib/Crypto/PublicKey/_openssh.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2019, Helder Eijs <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 import struct
32
33 from Crypto.Cipher import AES
34 from Crypto.Hash import SHA512
35 from Crypto.Protocol.KDF import _bcrypt_hash
36 from Crypto.Util.strxor import strxor
37 from Crypto.Util.py3compat import tostr, bchr, bord
38
39
40 def read_int4(data):
41 if len(data) < 4:
42 raise ValueError("Insufficient data")
43 value = struct.unpack(">I", data[:4])[0]
44 return value, data[4:]
45
46
47 def read_bytes(data):
48 size, data = read_int4(data)
49 if len(data) < size:
50 raise ValueError("Insufficient data (V)")
51 return data[:size], data[size:]
52
53
54 def read_string(data):
55 s, d = read_bytes(data)
56 return tostr(s), d
57
58
59 def check_padding(pad):
60 for v, x in enumerate(pad):
61 if bord(x) != ((v + 1) & 0xFF):
62 raise ValueError("Incorrect padding")
63
64
65 def import_openssh_private_generic(data, password):
66 # https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.key?annotate=HEAD
67 # https://github.com/openssh/openssh-portable/blob/master/sshkey.c
68 # https://coolaj86.com/articles/the-openssh-private-key-format/
69 # https://coolaj86.com/articles/the-ssh-public-key-format/
70
71 if not data.startswith(b'openssh-key-v1\x00'):
72 raise ValueError("Incorrect magic value")
73 data = data[15:]
74
75 ciphername, data = read_string(data)
76 kdfname, data = read_string(data)
77 kdfoptions, data = read_bytes(data)
78 number_of_keys, data = read_int4(data)
79
80 if number_of_keys != 1:
81 raise ValueError("We only handle 1 key at a time")
82
83 _, data = read_string(data) # Public key
84 encrypted, data = read_bytes(data)
85 if data:
86 raise ValueError("Too much data")
87
88 if len(encrypted) % 8 != 0:
89 raise ValueError("Incorrect payload length")
90
91 # Decrypt if necessary
92 if ciphername == 'none':
93 decrypted = encrypted
94 else:
95 if (ciphername, kdfname) != ('aes256-ctr', 'bcrypt'):
96 raise ValueError("Unsupported encryption scheme %s/%s" % (ciphername, kdfname))
97
98 salt, kdfoptions = read_bytes(kdfoptions)
99 iterations, kdfoptions = read_int4(kdfoptions)
100
101 if len(salt) != 16:
102 raise ValueError("Incorrect salt length")
103 if kdfoptions:
104 raise ValueError("Too much data in kdfoptions")
105
106 pwd_sha512 = SHA512.new(password).digest()
107 # We need 32+16 = 48 bytes, therefore 2 bcrypt outputs are sufficient
108 stripes = []
109 constant = b"OxychromaticBlowfishSwatDynamite"
110 for count in range(1, 3):
111 salt_sha512 = SHA512.new(salt + struct.pack(">I", count)).digest()
112 out_le = _bcrypt_hash(pwd_sha512, 6, salt_sha512, constant, False)
113 out = struct.pack("<IIIIIIII", *struct.unpack(">IIIIIIII", out_le))
114 acc = bytearray(out)
115 for _ in range(1, iterations):
116 out_le = _bcrypt_hash(pwd_sha512, 6, SHA512.new(out).digest(), constant, False)
117 out = struct.pack("<IIIIIIII", *struct.unpack(">IIIIIIII", out_le))
118 strxor(acc, out, output=acc)
119 stripes.append(acc[:24])
120
121 result = b"".join([bchr(a)+bchr(b) for (a, b) in zip(*stripes)])
122
123 cipher = AES.new(result[:32],
124 AES.MODE_CTR,
125 nonce=b"",
126 initial_value=result[32:32+16])
127 decrypted = cipher.decrypt(encrypted)
128
129 checkint1, decrypted = read_int4(decrypted)
130 checkint2, decrypted = read_int4(decrypted)
131 if checkint1 != checkint2:
132 raise ValueError("Incorrect checksum")
133 ssh_name, decrypted = read_string(decrypted)
134
135 return ssh_name, decrypted