Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ demos/*.log
_build
.coverage
.cache
.idea
15 changes: 11 additions & 4 deletions paramiko/dsskey.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,12 +229,19 @@ def _from_private_key(self, file_obj, password):
self._decode_key(data)

def _decode_key(self, data):
pkformat, data = data
# private key file contains:
# DSAPrivateKey = { version = 0, p, q, g, y, x }
try:
keylist = BER(data).decode()
except BERException as e:
raise SSHException("Unable to parse key file: " + str(e))
if pkformat == self.PRIVATE_KEY_FORMAT_ORIGINAL:
try:
keylist = BER(data).decode()
except BERException as e:
raise SSHException("Unable to parse key file: " + str(e))
elif pkformat == self.PRIVATE_KEY_FORMAT_OPENSSH:
keylist = self._uint32_cstruct_unpack(data, "iiiii")
keylist = [0] + list(keylist)
else:
raise SSHException("private key format.")
if type(keylist) is not list or len(keylist) < 6 or keylist[0] != 0:
raise SSHException(
"not a valid DSA private key file (bad ber encoding)"
Expand Down
22 changes: 16 additions & 6 deletions paramiko/ecdsakey.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,12 +283,22 @@ def _from_private_key(self, file_obj, password):
self._decode_key(data)

def _decode_key(self, data):
try:
key = serialization.load_der_private_key(
data, password=None, backend=default_backend()
)
except (ValueError, AssertionError) as e:
raise SSHException(str(e))
pkformat, data = data
if pkformat == self.PRIVATE_KEY_FORMAT_ORIGINAL:
try:
key = serialization.load_der_private_key(
data, password=None, backend=default_backend()
)
except (ValueError, AssertionError) as e:
raise SSHException(str(e))
elif pkformat == self.PRIVATE_KEY_FORMAT_OPENSSH:
curve, verkey, sigkey = self._uint32_cstruct_unpack(data, "sss")
try:
key = ec.derive_private_key(sigkey, curve, default_backend())

@ploxiln ploxiln May 22, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't work: sigkey needs to be an integer, and curve needs to be translated into one of the Curve objects in _ECDSA_CURVES

noticed while working on my port and cleanup of this. here's a test to show the errors:
https://github.com/ploxiln/paramiko-ng/pull/13/files#diff-523fff3457d80985c9d2429eb3aecb6e
the fix is mixed into my large refactor, since I figured this out towards the end:
https://github.com/ploxiln/paramiko-ng/pull/13/files#diff-00344f8a080e03112e93210cdfd37302

except (AttributeError, TypeError) as e:
raise SSHException(str(e))
else:
raise SSHException("unknown private key format.")

self.signing_key = key
self.verifying_key = key.public_key()
Expand Down
4 changes: 2 additions & 2 deletions paramiko/ed25519key.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ def __init__(
verifying_key = nacl.signing.VerifyKey(msg.get_binary())
elif filename is not None:
with open(filename, "r") as f:
data = self._read_private_key("OPENSSH", f)
pkformat, data = self._read_private_key("OPENSSH", f)
elif file_obj is not None:
data = self._read_private_key("OPENSSH", file_obj)
pkformat, data = self._read_private_key("OPENSSH", file_obj)

if filename or file_obj:
signing_key = self._parse_signing_key_data(data, password)
Expand Down
203 changes: 191 additions & 12 deletions paramiko/pkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,25 @@
from binascii import unhexlify
import os
from hashlib import md5
import re
import struct

import bcrypt

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher

from paramiko import util
from paramiko.common import o600
from paramiko.py3compat import u, encodebytes, decodebytes, b, string_types
from paramiko.py3compat import (
u,
encodebytes,
decodebytes,
b,
string_types,
byte_ord,
)
from paramiko.ssh_exception import SSHException, PasswordRequiredException
from paramiko.message import Message

Expand Down Expand Up @@ -62,6 +73,14 @@ class PKey(object):
"mode": modes.CBC,
},
}
PRIVATE_KEY_FORMAT_ORIGINAL = 1
PRIVATE_KEY_FORMAT_OPENSSH = 2
BEGIN_TAG = re.compile(
r"^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$"
)
END_TAG = re.compile(
r"^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$"
)

def __init__(self, msg=None, data=None):
"""
Expand Down Expand Up @@ -281,26 +300,52 @@ def _read_private_key_file(self, tag, filename, password=None):

def _read_private_key(self, tag, f, password=None):
lines = f.readlines()

# find the BEGIN tag
start = 0
beginning_of_key = "-----BEGIN " + tag + " PRIVATE KEY-----"
while start < len(lines) and lines[start].strip() != beginning_of_key:
m = self.BEGIN_TAG.match(lines[start])
line_range = len(lines) - 1
while start < line_range and not m:
start += 1
if start >= len(lines):
m = self.BEGIN_TAG.match(lines[start])
start += 1
keytype = m.group(1) if m else None
if start >= len(lines) or keytype is None:
raise SSHException("not a valid " + tag + " private key file")

# find the END tag
end = start
m = self.END_TAG.match(lines[end])
while end < line_range and not m:
end += 1
m = self.END_TAG.match(lines[end])

if keytype == tag:
data = self._read_private_key_old_format(lines, end, password)
pkformat = self.PRIVATE_KEY_FORMAT_ORIGINAL
elif keytype == "OPENSSH":
data = self._read_private_key_new_format(
lines[start:end], password
)
pkformat = self.PRIVATE_KEY_FORMAT_OPENSSH
else:
raise SSHException(
"encountered {} key, expected {} key".format(keytype, tag)
)

return pkformat, data

def _read_private_key_old_format(self, lines, end, password):
start = 0
# parse any headers first
headers = {}
start += 1
while start < len(lines):
l = lines[start].split(": ")
if len(l) == 1:
line = lines[start].split(": ")
if len(line) == 1:
break
headers[l[0].lower()] = l[1].strip()
headers[line[0].lower()] = line[1].strip()
start += 1
# find end
end = start
ending_of_key = "-----END " + tag + " PRIVATE KEY-----"
while end < len(lines) and lines[end].strip() != ending_of_key:
end += 1
# if we trudged to the end of the file, just try to cope.
try:
data = decodebytes(b("".join(lines[start:end])))
Expand Down Expand Up @@ -337,6 +382,140 @@ def _read_private_key(self, tag, f, password=None):
).decryptor()
return decryptor.update(data) + decryptor.finalize()

def _read_private_key_new_format(self, lines, password):
"""
Read the new OpenSSH SSH2 private key format available
since OpenSSH version 6.5
Reference:
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
"""
try:
data = decodebytes(b("".join(lines)))
except base64.binascii.Error as e:
raise SSHException("base64 decoding error: " + str(e))

# read data struct
auth_magic = data[:14]
if auth_magic != b("openssh-key-v1"):
raise SSHException("unexpected OpenSSH key header encountered")

cstruct = self._uint32_cstruct_unpack(data[15:], "sssur")
cipher, kdfname, kdf_options, num_pubkeys, remainder = cstruct
# For now, just support 1 key.
if num_pubkeys > 1:
raise SSHException(
"unsupported: private keyfile has multiple keys"
)
pubkey, privkey_blob = self._uint32_cstruct_unpack(remainder, "ss")

if kdfname == b("bcrypt"):
if cipher == b("aes256-cbc"):
mode = modes.CBC
elif cipher == b("aes256-ctr"):
mode = modes.CTR
else:
raise SSHException(
"unknown cipher `{}` used in private key file".format(
cipher.decode("utf-8")
)
)
# Encrypted private key.
# If no password was passed in, raise an exception pointing
# out that we need one
if password is None:
raise PasswordRequiredException(
"private key file is encrypted"
)

# Unpack salt and rounds from kdfoptions
salt, rounds = self._uint32_cstruct_unpack(kdf_options, "su")

# run bcrypt kdf to derive key and iv/nonce (32 + 16 bytes)
key_iv = bcrypt.kdf(
b(password),
b(salt),
48,
rounds,
# We can't control how many rounds are on disk, so no sense
# warning about it.
ignore_few_rounds=True,
)
key = key_iv[:32]
iv = key_iv[32:]

# decrypt private key blob
decryptor = Cipher(
algorithms.AES(key), mode(iv), default_backend()
).decryptor()
decrypted_privkey = decryptor.update(privkey_blob)
decrypted_privkey += decryptor.finalize()
elif cipher == b("none") and kdfname == b("none"):
# Unencrypted private key
decrypted_privkey = privkey_blob
else:
raise SSHException(
"unknown cipher or kdf used in private key file"
)

# Unpack private key and verify checkints
cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr")
checkint1, checkint2, keytype, keydata = cstruct

if checkint1 != checkint2:
raise SSHException(
"OpenSSH private key file checkints do not match"
)

# Remove padding
padlen = byte_ord(keydata[len(keydata) - 1])
return keydata[: len(keydata) - padlen]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this unpad suffers from roughly the same bug I fixed for Ed25519Key in #1400


def _uint32_cstruct_unpack(self, data, strformat):
"""
Used to read new OpenSSH private key format.
Unpacks a c data structure containing a mix of 32-bit uints and
variable length strings prefixed by 32-bit uint size field,
according to the specified format. Returns the unpacked vars
in a tuple.
Format strings:
s - denotes a string
i - denotes a long integer, encoded as a byte string
u - denotes a 32-bit unsigned integer
r - the remainder of the input string, returned as a string
"""
arr = []
idx = 0
try:
for f in strformat:
if f == "s":
# string
s_size = struct.unpack(">L", data[idx : idx + 4])[0]
idx += 4
s = data[idx : idx + s_size]
idx += s_size
arr.append(s)
if f == "i":
# long integer
s_size = struct.unpack(">L", data[idx : idx + 4])[0]
idx += 4
s = data[idx : idx + s_size]
idx += s_size
i = util.inflate_long(s, True)
arr.append(i)
elif f == "u":
# 32-bit unsigned int
u = struct.unpack(">L", data[idx : idx + 4])[0]
idx += 4
arr.append(u)
elif f == "r":
# remainder as string
s = data[idx:]
arr.append(s)
break
except Exception as e:
raise SSHException(str(e))
return tuple(arr)

def _write_private_key_file(self, filename, key, format, password=None):
"""
Write an SSH2-format private key file in a form that can be read by
Expand Down
29 changes: 22 additions & 7 deletions paramiko/rsakey.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,27 @@ def _from_private_key(self, file_obj, password):
self._decode_key(data)

def _decode_key(self, data):
try:
key = serialization.load_der_private_key(
data, password=None, backend=default_backend()
)
except ValueError as e:
raise SSHException(str(e))

pkformat, data = data
if pkformat == self.PRIVATE_KEY_FORMAT_ORIGINAL:
try:
key = serialization.load_der_private_key(
data, password=None, backend=default_backend()
)
except ValueError as e:
raise SSHException(str(e))
elif pkformat == self.PRIVATE_KEY_FORMAT_OPENSSH:
n, e, d, iqmp, q, p = self._uint32_cstruct_unpack(data, "iiiiii")
public_numbers = rsa.RSAPublicNumbers(e=e, n=n)
key = rsa.RSAPrivateNumbers(
p=p,
q=q,
d=d,
dmp1=d % (p - 1),
dmq1=d % (q - 1),
iqmp=iqmp,
public_numbers=public_numbers,
).private_key(default_backend())
else:
raise SSHException("unknown private key format.")
assert isinstance(key, rsa.RSAPrivateKey)
self.key = key
22 changes: 22 additions & 0 deletions tests/test_dss_1k_o.key
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAsyq4pxL
R5sOprPDHGpvzxAAAAEAAAAAEAAAGxAAAAB3NzaC1kc3MAAACBAL8XEx7F9xuwBNles+vW
pNF+YcofrBhjX1r5QhpBe0eoYWLHRcroN6lxwCdGYRfgOoRjTncBiixQX/uUxAY96zDh3i
r492s2BcJt4ihvNn/AY0I0OTuX/2IwGk9CGzafjaeZNVYxMa8lcVt0hSOTjkPQ7gVuk6bJ
zMInvie+VWKLAAAAFQDUgYdY+rhR0SkKbC09BS/SIHcB+wAAAIB44+4zpCNcd0CGvZlowH
99zyPX8uxQtmTLQFuR2O8O0FgVVuCdDgD0D9W8CLOp32oatpM0jyyN89EdvSWzjHzZJ+L6
H1FtZps7uhpDFWHdva1R25vyGecLMUuXjo5t/D7oCDih+HwHoSAxoi0QvsPd8/qqHQVznN
JKtR6thUpXEwAAAIAG4DCBjbgTTgpBw0egRkJwBSz0oTt+1IcapNU2jA6N8urMSk9YXHEQ
HKN68BAF3YJ59q2Ujv3LOXmBqGd1T+kzwUszfMlgzq8MMu19Yfzse6AIK1Agn1Vj6F7YXL
sXDN+T4KszX5+FJa7t/Zsp3nALWy6l0f4WKivEF5Y2QpEFcQAAAgCH6XUl1hYWB6kgCSHV
a4C+vQHrgFNgNwEQnE074LXHXlAhxC+Dm8XTGqVPX1KRPWzadq9/+v6pqLFqiRueB86uRb
J5WtAbUs3WwxAaC5Mi+mn42MBfL9PIwWPWCvstrAq9Nyj3EBMeX3XFLxN3RuGXIQnY/5rF
f5hriUVxhWDQGIVbBKhkpn7Geqg6nLpn7iqQhzFmFGjPmAdrllgdVGJRLyIN6BRsaltDdy
vxufkvGzKudvQ85QvsaoFJQ6K1d0S7907pexvxmWpcO7zchXb6i09BITWOAKIcHpVkbNQw
+8pzSdpggsAwCRbfk/Jkezz8sXVUCfmmJ23NFUw04/0ZbilCADRsUaPfafgVPeDznBnuCm
tfXa4JSrVUvPdwoex3SKZmYsFXwsuOEQnFkhUGHfWwTbmOmxzy6dtC24KYhnWG5OGFVJXh
3B8jQJGGs2ANfusI/Z0o15tAnQy5fqsLf9TT3RX7RG2ujIiDBsU+A1g//IXmSxxkUOQMZs
v+cMI8KfODAXmQtB30+yAgoV03Zb/bdptv+HqPT4eeecstJUxzEGYADt1mDq3uV7fQbNmo
80bppU52JjztrJb7hBmXsXHPRRK6spQ1FCatqvu1ggZeXZpEifNsHeqCljt87ueXsQsORY
pvhLzjTbTKZmjLDPuB+GxUNLEKh1ZNyAqKng==
-----END OPENSSH PRIVATE KEY-----
Loading