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
|
# Copyright (c) 2020-2023 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
# GNU General Public License, Version 2.0, or any later versions of
# that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""PKCS#11 smart card handler"""
from types import TracebackType
from typing import Dict, List, Optional, Sequence, Tuple, Type, Union, cast
try:
import pkcs11
from pkcs11 import Attribute, KeyType, Mechanism, ObjectClass
from pkcs11 import PrivateKey, Token
from pkcs11.util.rsa import encode_rsa_public_key
from pkcs11.util.ec import encode_ec_public_key
pkcs11_available = True
except (ImportError, ModuleNotFoundError): # pragma: no cover
pkcs11_available = False
from .misc import BytesOrStr
from .packet import MPInt, String
from .public_key import SSHCertificate, SSHKey, SSHKeyPair
from .public_key import import_certificate_chain, import_public_key
_AttrDict = Dict['Attribute', Union[bool, bytes, str, 'ObjectClass']]
_TokenID = Tuple[str, bytes]
_SessionMap = Dict[_TokenID, 'SSHPKCS11Session']
if pkcs11_available:
encoders = {KeyType.RSA: encode_rsa_public_key,
KeyType.EC: encode_ec_public_key}
mechanisms = {b'ssh-rsa': Mechanism.SHA1_RSA_PKCS,
b'rsa-sha2-256': Mechanism.SHA256_RSA_PKCS,
b'rsa-sha2-512': Mechanism.SHA512_RSA_PKCS,
b'ssh-rsa-sha224@ssh.com': Mechanism.SHA224_RSA_PKCS,
b'ssh-rsa-sha256@ssh.com': Mechanism.SHA256_RSA_PKCS,
b'ssh-rsa-sha384@ssh.com': Mechanism.SHA384_RSA_PKCS,
b'ssh-rsa-sha512@ssh.com': Mechanism.SHA512_RSA_PKCS,
b'rsa1024-sha1': Mechanism.SHA1_RSA_PKCS,
b'rsa2048-sha256': Mechanism.SHA256_RSA_PKCS,
b'ecdsa-sha2-nistp256': Mechanism.ECDSA_SHA256,
b'ecdsa-sha2-nistp384': Mechanism.ECDSA_SHA384,
b'ecdsa-sha2-nistp521': Mechanism.ECDSA_SHA512}
class SSHPKCS11KeyPair(SSHKeyPair):
"""Surrogate for a key accessed via a PKCS#11 provider"""
_key_type = 'pkcs11'
def __init__(self, session: 'SSHPKCS11Session', privkey: PrivateKey,
pubkey: SSHKey, cert: Optional[SSHCertificate] = None):
super().__init__(pubkey.algorithm, pubkey.algorithm,
pubkey.sig_algorithms, pubkey.sig_algorithms,
pubkey.public_data, privkey.label, cert,
use_executor=True)
self._session = session
self._privkey = privkey
def __del__(self) -> None:
self._session.close()
def sign(self, data: bytes) -> bytes:
"""Sign a block of data with this private key"""
sig_algorithm = self.sig_algorithm
if sig_algorithm.startswith(b'x509v3-'):
sig_algorithm = sig_algorithm[7:]
sig = self._privkey.sign(data, mechanism=mechanisms[sig_algorithm])
if self._privkey.key_type == KeyType.EC:
length = len(sig) // 2
r = int.from_bytes(sig[:length], 'big')
s = int.from_bytes(sig[length:], 'big')
sig = MPInt(r) + MPInt(s)
return String(sig_algorithm) + String(sig)
class SSHPKCS11Session:
"""Work around PKCS#11 sessions not supporting simultaneous opens"""
_sessions: _SessionMap = {}
def __init__(self, token_id: _TokenID, token: Token,
pin: Optional[str]):
self._token_id = token_id
self._session = token.open(user_pin=pin)
self._refcount = 0
def __enter__(self) -> 'SSHPKCS11Session':
"""Allow SSHPKCS11Session to be used as a context manager"""
return self
def __exit__(self, _exc_type: Type[BaseException],
_exc_value: BaseException,
_traceback: TracebackType) -> None:
"""Drop one reference to the session when exiting"""
self.close()
@classmethod
def open(cls, token: Token, pin: Optional[str]) -> 'SSHPKCS11Session':
"""Open a new session, or return an already-open one"""
token_id = (token.manufacturer_id, token.serial)
try:
session = cls._sessions[token_id]
except KeyError:
session = cls(token_id, token, pin)
cls._sessions[token_id] = session
session._refcount += 1
return session
def close(self) -> None:
"""Drop one reference to an open session"""
self._refcount -= 1
if self._refcount == 0:
self._session.close()
del self._sessions[self._token_id]
def get_keys(self, load_certs: bool, key_label: Optional[str],
key_id: Optional[BytesOrStr]) -> \
Sequence[SSHPKCS11KeyPair]:
"""Return the private keys found on this token"""
if isinstance(key_id, str):
key_id = bytes.fromhex(key_id)
key_attrs: _AttrDict = {Attribute.CLASS: ObjectClass.PRIVATE_KEY,
Attribute.SIGN: True}
if key_label is not None:
key_attrs[Attribute.LABEL] = key_label
if key_id is not None:
key_attrs[Attribute.OBJECT_ID] = key_id
cert_attrs: _AttrDict = {Attribute.CLASS: ObjectClass.CERTIFICATE}
if load_certs:
certs = [import_certificate_chain(
cast(bytes, cert[Attribute.VALUE]))
for cert in self._session.get_objects(cert_attrs)]
certdict = {cert.key.public_data: cert for cert in certs
if cert and 'Attest' not in str(cert.subject)}
else:
certdict = {}
keys = []
for key in self._session.get_objects(key_attrs):
privkey = cast(PrivateKey, key)
encoder = encoders.get(privkey.key_type)
if encoder:
pubkey = import_public_key(encoder(privkey))
cert = certdict.get(pubkey.public_data)
if cert:
keys.append(SSHPKCS11KeyPair(self, privkey,
pubkey, cert))
keys.append(SSHPKCS11KeyPair(self, privkey, pubkey))
self._refcount += len(keys)
return keys
def load_pkcs11_keys(provider: str, pin: Optional[str] = None, *,
load_certs: bool = True,
token_label: Optional[str] = None,
token_serial: Optional[BytesOrStr] = None,
key_label: Optional[str] = None,
key_id: Optional[BytesOrStr] = None) -> \
Sequence[SSHPKCS11KeyPair]:
"""Load PIV keys and X.509 certificates from a PKCS#11 token
This function loads a list of SSH keypairs with optional X.509
cerificates from attached PKCS#11 security tokens. The PKCS#11
provider must be specified, along with a user PIN if the
tokens are set to require one.
By default, this function loads both private key handles
and the X.509 certificates associated with them, allowing for
X.509 certificate based auth to SSH servers that support it.
To disable loading of these certificates and perform only
key-based authentication, load_certs may be set to `False`.
If token_label and/or token_serial are specified, only tokens
matching those values will be accessed.
If key_label and/or key_id are specified, only keys matching
those values will be loaded. Key IDs can be specified as
either raw bytes or a string containing hex digits.
.. note:: If you have an active asyncio event loop at
the time you call this function, you may want
to consider running it via a call to
:meth:`asyncio.AbstractEventLoop.run_in_executor`.
While retrieving the keys generally takes only a
fraction of a second, calling this function
directly could block asyncio event processing
until it completes.
:param provider:
The path to the PKCS#11 provider's shared library.
:param pin: (optional)
The PIN to use when accessing tokens, if needed.
:param load_certs: (optional)
Whether or not to load X.509 certificates from the
security tokens.
:param token_label: (optional)
A token label to match against. If set, only security
tokens with this label will be accessed.
:param token_serial: (optional)
A token serial number to match against. If set, only
security tokens with this serial number will be accessed.
:param key_label: (optional)
A key label to match against. If set, only keys with this
label will be loaded.
:param key_id: (optional)
A key ID to match against. If set, only keys with this ID
will be loaded.
:type provider: `str`
:type pin: `str`
:type load_certs: `bool`
:type token_label: `str`
:type token_serial: `bytes` or `str`
:type key_label: `str`
:type key_id: `bytes` or `str`
:returns: list of class:`SSHKeyPair`
"""
lib = pkcs11.lib(provider)
keys: List[SSHPKCS11KeyPair] = []
if isinstance(token_serial, str):
token_serial = token_serial.encode('utf-8')
for token in lib.get_tokens(token_label=token_label,
token_serial=token_serial):
with SSHPKCS11Session.open(token, pin) as session:
keys.extend(session.get_keys(load_certs, key_label, key_id))
return keys
else: # pragma: no cover
def load_pkcs11_keys(provider: str, pin: Optional[str] = None, *,
load_certs: bool = True,
token_label: Optional[str] = None,
token_serial: Optional[BytesOrStr] = None,
key_label: Optional[str] = None,
key_id: Optional[BytesOrStr] = None) -> \
Sequence['SSHPKCS11KeyPair']:
"""Report that PKCS#11 support is not available"""
raise ValueError('PKCS#11 support not available') from None
|