| 1 |
# Authors: |
| 2 |
# Jan Cholasta <[email protected]> |
| 3 |
# |
| 4 |
# Copyright (C) 2012 Red Hat |
| 5 |
# see file 'COPYING' for use and warranty information |
| 6 |
# |
| 7 |
# This program is free software; you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# This program is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
# |
| 20 |
|
| 21 |
""" |
| 22 |
SSH utilities. |
| 23 |
""" |
| 24 |
|
| 25 |
import base64 |
| 26 |
import re |
| 27 |
import struct |
| 28 |
from hashlib import sha1 |
| 29 |
from hashlib import sha256 |
| 30 |
|
| 31 |
import six |
| 32 |
|
| 33 |
if six.PY3: |
| 34 |
unicode = str |
| 35 |
|
| 36 |
__all__ = ['SSHPublicKey'] |
| 37 |
|
| 38 |
OPENSSH_BASE_REGEX = re.compile(r'^[\t ]*(?P<keytype>[^\x00\n\r]+?) [\t ]*(?P<key>[^\x00\n\r]+?)(?:[\t ]+(?P<comment>[^\x00\n\r]*?)[\t ]*)?$') |
| 39 |
OPENSSH_OPTIONS_REGEX = re.compile(r'(?P<name>[-0-9A-Za-z]+)(?:="(?P<value>(?:\\"|[^\x00\n\r"])*)")?') |
| 40 |
|
| 41 |
|
| 42 |
class SSHPublicKey: |
| 43 |
""" |
| 44 |
SSH public key object. |
| 45 |
""" |
| 46 |
|
| 47 |
__slots__ = ('_key', '_keytype', '_comment', '_options') |
| 48 |
|
| 49 |
def __init__(self, key, comment=None, options=None, encoding='utf-8'): |
| 50 |
if isinstance(key, SSHPublicKey): |
| 51 |
self._key = key._key |
| 52 |
self._keytype = key._keytype |
| 53 |
self._comment = key._comment |
| 54 |
self._options = key._options |
| 55 |
return |
| 56 |
|
| 57 |
if not isinstance(key, (bytes, unicode)): |
| 58 |
raise TypeError("argument must be bytes or unicode, got %s" % type(key).__name__) |
| 59 |
|
| 60 |
# All valid public key blobs start with 3 null bytes (see RFC 4253 |
| 61 |
# section 6.6, RFC 4251 section 5 and RFC 4250 section 4.6) |
| 62 |
if isinstance(key, bytes) and key[:3] != b'\0\0\0': |
| 63 |
key = key.decode(encoding) |
| 64 |
|
| 65 |
valid = self._parse_raw(key) or self._parse_base64(key) or self._parse_openssh(key) |
| 66 |
|
| 67 |
if not valid: |
| 68 |
raise ValueError("not a valid SSH public key") |
| 69 |
|
| 70 |
if comment is not None: |
| 71 |
self._comment = comment |
| 72 |
if options is not None: |
| 73 |
self._options = options |
| 74 |
|
| 75 |
def _parse_raw(self, key): |
| 76 |
if not isinstance(key, bytes): |
| 77 |
return False |
| 78 |
|
| 79 |
try: |
| 80 |
(ktlen,) = struct.unpack('>I', key[:4]) |
| 81 |
except struct.error: |
| 82 |
return False |
| 83 |
|
| 84 |
if ktlen < 1 or ktlen > len(key) - 4: |
| 85 |
return False |
| 86 |
|
| 87 |
try: |
| 88 |
keytype = key[4:ktlen+4].decode('ascii') |
| 89 |
except UnicodeDecodeError: |
| 90 |
return False |
| 91 |
|
| 92 |
self._key = key |
| 93 |
self._keytype = keytype |
| 94 |
self._options = {} |
| 95 |
self._comment = None |
| 96 |
|
| 97 |
return True |
| 98 |
|
| 99 |
def _parse_base64(self, key): |
| 100 |
if not isinstance(key, unicode): |
| 101 |
return False |
| 102 |
|
| 103 |
try: |
| 104 |
key = base64.b64decode(key) |
| 105 |
except (TypeError, ValueError): |
| 106 |
return False |
| 107 |
|
| 108 |
return self._parse_raw(key) |
| 109 |
|
| 110 |
def _parse_openssh_without_options(self, key): |
| 111 |
match = OPENSSH_BASE_REGEX.match(key) |
| 112 |
if not match: |
| 113 |
return False |
| 114 |
|
| 115 |
if not self._parse_base64(match.group('key')): |
| 116 |
return False |
| 117 |
|
| 118 |
if self._keytype != match.group('keytype'): |
| 119 |
return False |
| 120 |
|
| 121 |
self._comment = match.group('comment') |
| 122 |
|
| 123 |
return True |
| 124 |
|
| 125 |
def _parse_openssh_with_options(self, key): |
| 126 |
key = key.lstrip('\t ') |
| 127 |
|
| 128 |
# Options that allow multiple entries |
| 129 |
multiple_allowed = ('permitopen', 'permitlisten') |
| 130 |
|
| 131 |
options = {} |
| 132 |
while True: |
| 133 |
match = OPENSSH_OPTIONS_REGEX.match(key) |
| 134 |
if not match: |
| 135 |
return False |
| 136 |
|
| 137 |
name = match.group('name').lower() |
| 138 |
value = match.group('value') |
| 139 |
if value: |
| 140 |
value = value.replace('\\"', '"') |
| 141 |
|
| 142 |
if name in multiple_allowed: |
| 143 |
if name in options: |
| 144 |
options[name].append(value) |
| 145 |
else: |
| 146 |
options[name] = [value] |
| 147 |
else: |
| 148 |
options[name] = value |
| 149 |
|
| 150 |
key = key[len(match.group(0)):] |
| 151 |
key0, key = key[:1], key[1:] |
| 152 |
|
| 153 |
if key0 != ',': |
| 154 |
break |
| 155 |
|
| 156 |
if not self._parse_openssh_without_options(key): |
| 157 |
return False |
| 158 |
|
| 159 |
self._options = options |
| 160 |
|
| 161 |
return True |
| 162 |
|
| 163 |
def _parse_openssh(self, key): |
| 164 |
if not isinstance(key, unicode): |
| 165 |
return False |
| 166 |
|
| 167 |
if self._parse_openssh_without_options(key): |
| 168 |
return True |
| 169 |
else: |
| 170 |
return self._parse_openssh_with_options(key) |
| 171 |
|
| 172 |
def keytype(self): |
| 173 |
return self._keytype |
| 174 |
|
| 175 |
def comment(self): |
| 176 |
return self._comment |
| 177 |
|
| 178 |
def has_options(self): |
| 179 |
return bool(self._options) |
| 180 |
|
| 181 |
def openssh(self): |
| 182 |
key = base64.b64encode(self._key).decode('ascii') |
| 183 |
out = u'%s %s' % (self._keytype, key) |
| 184 |
|
| 185 |
if self._options: |
| 186 |
options = [] |
| 187 |
for name in sorted(self._options): |
| 188 |
value = self._options[name] |
| 189 |
if value is None: |
| 190 |
options.append(name) |
| 191 |
elif type(value) is list: |
| 192 |
for v in value: |
| 193 |
v = v.replace('"', '\\"') |
| 194 |
options.append(u'%s="%s"' % (name, v)) |
| 195 |
else: |
| 196 |
value = value.replace('"', '\\"') |
| 197 |
options.append(u'%s="%s"' % (name, value)) |
| 198 |
options = u','.join(options) |
| 199 |
|
| 200 |
out = u'%s %s' % (options, out) |
| 201 |
|
| 202 |
if self._comment: |
| 203 |
out = u'%s %s' % (out, self._comment) |
| 204 |
|
| 205 |
return out |
| 206 |
|
| 207 |
def fingerprint_hex_sha256(self): |
| 208 |
# OpenSSH trims the trailing '=' of base64 sha256 FP representation |
| 209 |
fp = base64.b64encode(sha256(self._key).digest()).rstrip(b'=') |
| 210 |
return u'SHA256:{fp}'.format(fp=fp.decode('utf-8')) |
| 211 |
|
| 212 |
def _fingerprint_dns(self, fpfunc, fptype): |
| 213 |
if self._keytype == 'ssh-rsa': |
| 214 |
keytype = 1 |
| 215 |
elif self._keytype == 'ssh-dss': |
| 216 |
keytype = 2 |
| 217 |
elif self._keytype.startswith('ecdsa-sha2-') and '@' not in self._keytype: |
| 218 |
keytype = 3 |
| 219 |
elif self._keytype == 'ssh-ed25519': |
| 220 |
keytype = 4 |
| 221 |
else: |
| 222 |
return None |
| 223 |
fp = fpfunc(self._key).hexdigest().upper() |
| 224 |
return u'%d %d %s' % (keytype, fptype, fp) |
| 225 |
|
| 226 |
def fingerprint_dns_sha1(self): |
| 227 |
return self._fingerprint_dns(sha1, 1) |
| 228 |
|
| 229 |
def fingerprint_dns_sha256(self): |
| 230 |
return self._fingerprint_dns(sha256, 2) |