Repository navigation
add support for new OpenSSH private key format #1343
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bitprophet
merged 9 commits into
paramiko:master
from
carta:feature-new-openssh-pk-format
Dec 3, 2019
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
eff204f
add support for new OpenSSH private key format
jaredhobbs e72aeaf
blacken
jaredhobbs 6b374a3
blacken
jaredhobbs 2dcdba7
blacken, tests
jaredhobbs 79a6bbf
try to fix test
jaredhobbs 242be1a
ignore few rounds in bcrypt kdf call
jaredhobbs 8d57be2
handle exception that can occur if no regex match
jaredhobbs f9d8c03
add noqa comments
jaredhobbs 25de1a7
Use raw string
jaredhobbs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,3 +9,4 @@ demos/*.log | |
| _build | ||
| .coverage | ||
| .cache | ||
| .idea | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
||
|
|
@@ -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): | ||
| """ | ||
|
|
@@ -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]))) | ||
|
|
@@ -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] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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----- |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this doesn't work:
sigkeyneeds to be an integer, andcurveneeds to be translated into one of the Curve objects in_ECDSA_CURVESnoticed 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