| 1 |
import sys |
| 2 |
from _thread import allocate_lock as Lock |
| 3 |
from enum import IntEnum as _IntEnum |
| 4 |
from functools import cache |
| 5 |
from _pypy_openssl import ffi, lib |
| 6 |
from _cffi_ssl._stdssl.utility import (_str_to_ffi_buffer, _bytes_with_len, |
| 7 |
_str_from_buf) |
| 8 |
|
| 9 |
try: from __pypy__ import builtinify |
| 10 |
except ImportError: builtinify = lambda f: f |
| 11 |
|
| 12 |
class UnsupportedDigestmodError(ValueError): |
| 13 |
pass |
| 14 |
|
| 15 |
class _Py_hash_type(_IntEnum): |
| 16 |
Py_ht_evp = 0 |
| 17 |
Py_ht_evp_nosecurity = 1 |
| 18 |
Py_ht_mac = 2 |
| 19 |
Py_ht_pbkdf2 = 3 |
| 20 |
globals().update(_Py_hash_type.__members__) |
| 21 |
|
| 22 |
def get_errstr(): |
| 23 |
|
| 24 |
errcode = lib.ERR_peek_last_error(); |
| 25 |
if not errcode: |
| 26 |
return "unknown reasons" |
| 27 |
|
| 28 |
errlib = lib.ERR_lib_error_string(errcode) |
| 29 |
func = lib.ERR_func_error_string(errcode) |
| 30 |
reason = lib.ERR_reason_error_string(errcode) |
| 31 |
|
| 32 |
if errlib and func: |
| 33 |
return "[%s: %s] %s" % (_str_from_buf(errlib), _str_from_buf(func), _str_from_buf(reason)) |
| 34 |
elif errlib: |
| 35 |
return "[%s] %s" % (_str_from_buf(errlib), _str_from_buf(reason)) |
| 36 |
else: |
| 37 |
return _str_from_buf(reason) |
| 38 |
|
| 39 |
|
| 40 |
def new(name, string=b'', usedforsecurity=True): |
| 41 |
if string: |
| 42 |
|
| 43 |
name_lower = str(name).lower() |
| 44 |
py_ht = Py_ht_evp if usedforsecurity else Py_ht_evp_nosecurity |
| 45 |
dtype = py_digest_by_name(name_lower, py_ht) |
| 46 |
buf = ffi.from_buffer(string) |
| 47 |
digest_size = lib.EVP_MD_size(dtype) |
| 48 |
md = ffi.new("unsigned char[]", digest_size) |
| 49 |
if lib.EVP_Digest(buf, len(buf), md, ffi.NULL, dtype, ffi.NULL): |
| 50 |
return _OneShotHash(name_lower, digest_size, |
| 51 |
_bytes_with_len(md, digest_size), |
| 52 |
string, usedforsecurity) |
| 53 |
h = HASH(name, usedforsecurity=usedforsecurity) |
| 54 |
h.update(string) |
| 55 |
return h |
| 56 |
|
| 57 |
class _OneShotHash: |
| 58 |
"""Lightweight result of new(name, data) using EVP_Digest. |
| 59 |
|
| 60 |
Avoids EVP_MD_CTX allocation, ffi.gc, and Lock for the common |
| 61 |
hashlib.new(name, data).hexdigest() pattern. Lazily upgrades to a |
| 62 |
full HASH object if update() or copy() is called. |
| 63 |
""" |
| 64 |
__slots__ = ('name', 'digest_size', '_digest', '_data', '_usedforsecurity', '_hash') |
| 65 |
|
| 66 |
def __init__(self, name, digest_size, digest, data, usedforsecurity): |
| 67 |
self.name = name |
| 68 |
self.digest_size = digest_size |
| 69 |
self._digest = digest |
| 70 |
self._data = data |
| 71 |
self._usedforsecurity = usedforsecurity |
| 72 |
self._hash = None |
| 73 |
|
| 74 |
def _upgrade(self): |
| 75 |
h = HASH(self.name, usedforsecurity=self._usedforsecurity) |
| 76 |
h.update(self._data) |
| 77 |
self._hash = h |
| 78 |
|
| 79 |
def digest(self): |
| 80 |
if self._hash is not None: |
| 81 |
return self._hash.digest() |
| 82 |
return self._digest |
| 83 |
|
| 84 |
def hexdigest(self): |
| 85 |
if self._hash is not None: |
| 86 |
return self._hash.hexdigest() |
| 87 |
return self._digest.hex() |
| 88 |
|
| 89 |
def update(self, string): |
| 90 |
if self._hash is None: |
| 91 |
self._upgrade() |
| 92 |
self._hash.update(string) |
| 93 |
self._digest = None |
| 94 |
|
| 95 |
def copy(self): |
| 96 |
if self._hash is not None: |
| 97 |
return self._hash.copy() |
| 98 |
return new(self.name, self._data, usedforsecurity=self._usedforsecurity) |
| 99 |
|
| 100 |
@property |
| 101 |
def block_size(self): |
| 102 |
if self._hash is not None: |
| 103 |
return self._hash.block_size |
| 104 |
|
| 105 |
return HASH(self.name, usedforsecurity=self._usedforsecurity).block_size |
| 106 |
|
| 107 |
|
| 108 |
class Immutable(type): |
| 109 |
def __init__(cls, name, bases, dct): |
| 110 |
type.__setattr__(cls,"attr",set(dct.keys())) |
| 111 |
type.__init__(cls, name, bases, dct) |
| 112 |
|
| 113 |
def __setattr__(cls, name, value): |
| 114 |
|
| 115 |
qualname = '.'.join([cls.__module__, cls.__name__]) |
| 116 |
raise TypeError(f"cannot set '{name}' attribute of immutable type '{qualname}'") |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
class HASH(object, metaclass=Immutable): |
| 121 |
|
| 122 |
def __init__(self, name=None, copy_from=None, usedforsecurity=True): |
| 123 |
if name is None: |
| 124 |
qualname = '.'.join([type(self).__module__, type(self).__name__]) |
| 125 |
raise TypeError(f"cannot create '{qualname}' instances") |
| 126 |
self.ctx = ffi.NULL |
| 127 |
self.ctx = ffi.NULL |
| 128 |
self.name = str(name).lower() |
| 129 |
digest_type = py_digest_by_name(self.name, |
| 130 |
Py_ht_evp if usedforsecurity else Py_ht_evp_nosecurity) |
| 131 |
self.digest_size = lib.EVP_MD_size(digest_type) |
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
self.lock = Lock() |
| 137 |
|
| 138 |
self._init_ctx(copy_from, digest_type) |
| 139 |
if not usedforsecurity and lib.EVP_MD_CTX_FLAG_NON_FIPS_ALLOW: |
| 140 |
lib.EVP_MD_CTX_set_flags(self.ctx, lib.EVP_MD_CTX_FLAG_NON_FIPS_ALLOW) |
| 141 |
|
| 142 |
def _init_ctx(self, copy_from, digest_type): |
| 143 |
|
| 144 |
|
| 145 |
ctx = lib.EVP_MD_CTX_new() |
| 146 |
if ctx == ffi.NULL: |
| 147 |
raise MemoryError |
| 148 |
ctx = ffi.gc(ctx, lib.EVP_MD_CTX_free) |
| 149 |
|
| 150 |
try: |
| 151 |
if copy_from is not None: |
| 152 |
|
| 153 |
if not lib.EVP_MD_CTX_copy_ex(ctx, copy_from): |
| 154 |
raise ValueError |
| 155 |
else: |
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
template = _get_ctx_template(digest_type) |
| 160 |
if not lib.EVP_MD_CTX_copy_ex(ctx, template): |
| 161 |
raise ValueError(get_errstr()) |
| 162 |
self.ctx = ctx |
| 163 |
except: |
| 164 |
|
| 165 |
raise |
| 166 |
|
| 167 |
def digest_type_by_name(self): |
| 168 |
ssl_name = _inverse_name_mapping.get(self.name, self.name) |
| 169 |
c_name = _str_to_ffi_buffer(ssl_name) |
| 170 |
digest_type = lib.EVP_get_digestbyname(c_name) |
| 171 |
if not digest_type: |
| 172 |
raise ValueError("unknown hash function") |
| 173 |
|
| 174 |
return digest_type |
| 175 |
|
| 176 |
def __repr__(self): |
| 177 |
return "<%s %s object at 0x%s>" % (self.name, type(self), id(self)) |
| 178 |
|
| 179 |
def update(self, string): |
| 180 |
if isinstance(string, str): |
| 181 |
raise TypeError("Unicode-objects must be encoded before hashing") |
| 182 |
elif isinstance(string, memoryview): |
| 183 |
|
| 184 |
string = string.tobytes() |
| 185 |
buf = ffi.from_buffer(string) |
| 186 |
self._update(buf) |
| 187 |
|
| 188 |
def _update(self, buf): |
| 189 |
with self.lock: |
| 190 |
|
| 191 |
if lib.EVP_DigestUpdate(self.ctx, buf, len(buf)) == 0: |
| 192 |
raise ValueError(get_errstr()) |
| 193 |
|
| 194 |
def copy(self): |
| 195 |
"""Return a copy of the hash object.""" |
| 196 |
with self.lock: |
| 197 |
return type(self)(self.name, copy_from=self.ctx) |
| 198 |
|
| 199 |
def digest(self): |
| 200 |
"""Return the digest value as a string of binary data.""" |
| 201 |
return self._digest() |
| 202 |
|
| 203 |
def hexdigest(self): |
| 204 |
"""Return the digest value as a string of hexadecimal digits.""" |
| 205 |
return self._digest().hex() |
| 206 |
|
| 207 |
@property |
| 208 |
def block_size(self): |
| 209 |
return lib.EVP_MD_CTX_block_size(self.ctx) |
| 210 |
|
| 211 |
def _digest(self): |
| 212 |
|
| 213 |
ctx = lib.EVP_MD_CTX_new() |
| 214 |
if ctx == ffi.NULL: |
| 215 |
raise MemoryError |
| 216 |
try: |
| 217 |
with self.lock: |
| 218 |
if not lib.EVP_MD_CTX_copy_ex(ctx, self.ctx): |
| 219 |
raise ValueError |
| 220 |
digest_size = self.digest_size |
| 221 |
buf = ffi.new("unsigned char[]", digest_size) |
| 222 |
lib.EVP_DigestFinal_ex(ctx, buf, ffi.NULL) |
| 223 |
return _bytes_with_len(buf, digest_size) |
| 224 |
finally: |
| 225 |
lib.EVP_MD_CTX_free(ctx) |
| 226 |
|
| 227 |
|
| 228 |
class HASHXOF(HASH): |
| 229 |
pass |
| 230 |
|
| 231 |
|
| 232 |
class HMAC(HASH): |
| 233 |
def __init__(self, name=None, copy_from=None, usedforsecurity=True): |
| 234 |
HASH.__init__(self, name=name, copy_from=copy_from, usedforsecurity=usedforsecurity) |
| 235 |
digest_type = py_digest_by_name(self.name, |
| 236 |
Py_ht_evp if usedforsecurity else Py_ht_evp_nosecurity) |
| 237 |
self.digest_size = lib.EVP_MD_size(digest_type) |
| 238 |
self._name = name |
| 239 |
self.name = f"hmac-{name}" |
| 240 |
|
| 241 |
@property |
| 242 |
def block_size(self): |
| 243 |
md = lib.HMAC_CTX_get_md(self.ctx) |
| 244 |
if not md: |
| 245 |
raise ValueError("could not get EVP_MD from HMAC_CTX") |
| 246 |
return lib.EVP_MD_block_size(md) |
| 247 |
|
| 248 |
def _digest(self): |
| 249 |
|
| 250 |
temp_ctx = lib.HMAC_CTX_new() |
| 251 |
if temp_ctx == ffi.NULL: |
| 252 |
raise MemoryError |
| 253 |
try: |
| 254 |
with self.lock: |
| 255 |
if not lib.HMAC_CTX_copy(temp_ctx, self.ctx): |
| 256 |
raise ValueError |
| 257 |
digest_size = self.digest_size |
| 258 |
buf = ffi.new("unsigned char[]", digest_size) |
| 259 |
lib.HMAC_Final(temp_ctx, buf, ffi.NULL) |
| 260 |
return _bytes_with_len(buf, digest_size) |
| 261 |
finally: |
| 262 |
lib.HMAC_CTX_free(temp_ctx) |
| 263 |
|
| 264 |
def _init_ctx(self, copy_from, digest_type): |
| 265 |
ctx = lib.HMAC_CTX_new() |
| 266 |
if ctx == ffi.NULL: |
| 267 |
raise MemoryError |
| 268 |
ctx = ffi.gc(ctx, lib.HMAC_CTX_free) |
| 269 |
|
| 270 |
try: |
| 271 |
if copy_from is not None: |
| 272 |
if not lib.HMAC_CTX_copy(ctx, copy_from): |
| 273 |
raise ValueError |
| 274 |
else: |
| 275 |
if lib.HMAC_Init_ex(ctx, _str_to_ffi_buffer(""), 0, digest_type, ffi.NULL) == 0: |
| 276 |
raise ValueError(get_errstr()) |
| 277 |
self.ctx = ctx |
| 278 |
except: |
| 279 |
|
| 280 |
raise |
| 281 |
|
| 282 |
def _update(self, buf): |
| 283 |
with self.lock: |
| 284 |
|
| 285 |
if lib.HMAC_Update(self.ctx, buf, len(buf)) == 0: |
| 286 |
raise ValueError(get_errstr()) |
| 287 |
|
| 288 |
def copy(self): |
| 289 |
"""Return a copy of the hash object.""" |
| 290 |
with self.lock: |
| 291 |
return type(self)(self._name, copy_from=self.ctx) |
| 292 |
|
| 293 |
|
| 294 |
_algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', |
| 295 |
'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512') |
| 296 |
|
| 297 |
class NameFetcher: |
| 298 |
def __init__(self): |
| 299 |
self.meth_names = [] |
| 300 |
self.error = None |
| 301 |
|
| 302 |
|
| 303 |
def _fetch_names(): |
| 304 |
name_fetcher = NameFetcher() |
| 305 |
handle = ffi.new_handle(name_fetcher) |
| 306 |
if lib.OPENSSL_VERSION_NUMBER >= int(0x30000000): |
| 307 |
lib.EVP_MD_do_all_provided(ffi.cast("OSSL_LIB_CTX*", 0), |
| 308 |
_openssl_hash_name_mapper, handle) |
| 309 |
else: |
| 310 |
lib.EVP_MD_do_all(_openssl_hash_name_mapper, handle) |
| 311 |
if name_fetcher.error: |
| 312 |
raise name_fetcher.error |
| 313 |
meth_names = name_fetcher.meth_names |
| 314 |
name_fetcher.meth_names = None |
| 315 |
return frozenset(meth_names) |
| 316 |
|
| 317 |
_name_mapping = { |
| 318 |
'blake2s256': 'blake2s', |
| 319 |
'blake2b512': 'blake2b', |
| 320 |
'md5-sha1': 'md5_sha1', |
| 321 |
'sha512-224': 'sha512_224', |
| 322 |
'sha512-256': 'sha512_256', |
| 323 |
'sha3-224': 'sha3_224', |
| 324 |
'sha3-256': 'sha3_256', |
| 325 |
'sha3-384': 'sha3_384', |
| 326 |
'sha3-512': 'sha3_512', |
| 327 |
} |
| 328 |
|
| 329 |
_inverse_name_mapping = {value: key for key, value in _name_mapping.items()} |
| 330 |
|
| 331 |
if lib.OPENSSL_VERSION_NUMBER >= int(0x30000000): |
| 332 |
@ffi.callback("void(EVP_MD*, void*)") |
| 333 |
def _openssl_hash_name_mapper(evp_md, userdata): |
| 334 |
return __openssl_hash_name_mapper(evp_md, userdata) |
| 335 |
|
| 336 |
def PY_EVP_MD_fetch(algorithm, properties): |
| 337 |
return lib.EVP_MD_fetch(ffi.NULL, algorithm, properties) |
| 338 |
def PY_EVP_MD_free(md): |
| 339 |
lib.EVP_MD_free(md) |
| 340 |
else: |
| 341 |
@ffi.callback("void(EVP_MD*, const char *, const char *, void*)") |
| 342 |
def _openssl_hash_name_mapper(evp_md, from_name, to_name, userdata): |
| 343 |
return __openssl_hash_name_mapper(evp_md, userdata) |
| 344 |
|
| 345 |
def PY_EVP_MD_fetch(algorithm, properties): |
| 346 |
return lib.EVP_get_digestbyname(algorithm) |
| 347 |
def PY_EVP_MD_free(md): |
| 348 |
pass |
| 349 |
|
| 350 |
def __openssl_hash_name_mapper(evp_md, userdata): |
| 351 |
if not evp_md: |
| 352 |
return |
| 353 |
nid = lib.EVP_MD_nid(evp_md) |
| 354 |
if nid == lib.NID_undef: |
| 355 |
return |
| 356 |
from_name = lib.OBJ_nid2ln(nid) |
| 357 |
lowered = _str_from_buf(from_name).lower().replace('-', '_') |
| 358 |
name = _name_mapping.get(lowered, lowered) |
| 359 |
name_fetcher = ffi.from_handle(userdata) |
| 360 |
name_fetcher.meth_names.append(name) |
| 361 |
|
| 362 |
|
| 363 |
openssl_md_meth_names = _fetch_names() |
| 364 |
del _fetch_names |
| 365 |
|
| 366 |
|
| 367 |
def make_new_hash(name, funcname): |
| 368 |
def new_hash(string=b'', usedforsecurity=True): |
| 369 |
return new(name, string, usedforsecurity=True) |
| 370 |
new_hash.__name__ = funcname |
| 371 |
return builtinify(new_hash) |
| 372 |
|
| 373 |
for _name in _algorithms: |
| 374 |
_newname = 'openssl_%s' % (_name,) |
| 375 |
globals()[_newname] = make_new_hash(_name, _newname) |
| 376 |
|
| 377 |
if hasattr(lib, 'PKCS5_PBKDF2_HMAC'): |
| 378 |
@builtinify |
| 379 |
def pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None): |
| 380 |
if not isinstance(hash_name, str): |
| 381 |
raise TypeError("expected 'str' for name, but got %s" % type(hash_name)) |
| 382 |
c_name = _str_to_ffi_buffer(hash_name) |
| 383 |
digest = lib.EVP_get_digestbyname(c_name) |
| 384 |
if digest == ffi.NULL: |
| 385 |
raise UnsupportedDigestmodError("unsupported hash type") |
| 386 |
if dklen is None: |
| 387 |
dklen = lib.EVP_MD_size(digest) |
| 388 |
if dklen < 1: |
| 389 |
raise ValueError("key length must be greater than 0.") |
| 390 |
if dklen >= sys.maxsize: |
| 391 |
raise OverflowError("key length is too great.") |
| 392 |
if iterations < 1: |
| 393 |
raise ValueError("iteration value must be greater than 0.") |
| 394 |
if iterations >= sys.maxsize: |
| 395 |
raise OverflowError("iteration value is too great.") |
| 396 |
key = ffi.new("unsigned char[]", dklen) |
| 397 |
c_password = ffi.from_buffer(bytes(password)) |
| 398 |
c_salt = ffi.from_buffer(bytes(salt)) |
| 399 |
r = lib.PKCS5_PBKDF2_HMAC(c_password, len(c_password), |
| 400 |
ffi.cast("unsigned char*",c_salt), len(c_salt), |
| 401 |
iterations, digest, dklen, key) |
| 402 |
if r == 0: |
| 403 |
raise ValueError |
| 404 |
return _bytes_with_len(key, dklen) |
| 405 |
|
| 406 |
@builtinify |
| 407 |
def scrypt(password, *, salt, n=None, r=None, p=None, maxmem=0, dklen=64): |
| 408 |
int_max = (2 ** 31) - 1 |
| 409 |
if len(password) > int_max: |
| 410 |
raise OverflowError("password is too long") |
| 411 |
if len(salt) > int_max: |
| 412 |
raise OverflowError("salt is too long") |
| 413 |
def asint(val, name): |
| 414 |
try: |
| 415 |
return int(val) |
| 416 |
except TypeError: |
| 417 |
raise TypeError("%s is required and must be a unsigned int" % name) |
| 418 |
n = asint(n, 'n') |
| 419 |
if n < 2 or (n & (n - 1)): |
| 420 |
raise TypeError("n must be a power of 2.") |
| 421 |
r = asint(r, "r") |
| 422 |
p = asint(p, "p") |
| 423 |
if maxmem < 0 or maxmem > int_max: |
| 424 |
|
| 425 |
|
| 426 |
raise ValueError("maxmem must be positive and smaller than %d" % int_max) |
| 427 |
if dklen <= 0 or dklen > int_max: |
| 428 |
raise ValueError("dklen must be greater than 0 and smaller than %d" % int_max) |
| 429 |
|
| 430 |
void_p = ffi.cast("char *", 0) |
| 431 |
retval = lib.EVP_PBE_scrypt(void_p, 0, void_p, 0, n, r, p, maxmem, void_p, 0) |
| 432 |
if not retval: |
| 433 |
ValueError("Invalid parameter combination for n, r, p, maxmem.") |
| 434 |
key = ffi.new("unsigned char[]", dklen) |
| 435 |
c_password = ffi.from_buffer(password) |
| 436 |
c_salt = ffi.from_buffer(salt) |
| 437 |
reval = lib.EVP_PBE_scrypt(c_password, len(password), c_salt, len(salt), |
| 438 |
n, r, p, maxmem, key, dklen) |
| 439 |
if not retval: |
| 440 |
raise ValueError() |
| 441 |
return _bytes_with_len(key, dklen) |
| 442 |
|
| 443 |
def compare_digest(a, b): |
| 444 |
"""Return 'a == b'. |
| 445 |
|
| 446 |
This function uses an approach designed to prevent |
| 447 |
timing analysis, making it appropriate for cryptography. |
| 448 |
|
| 449 |
a and b must both be of the same type: either str (ASCII only), |
| 450 |
or any bytes-like object. |
| 451 |
|
| 452 |
Note: If a and b are of different lengths, or if an error occurs, |
| 453 |
a timing attack could theoretically reveal information about the |
| 454 |
types and lengths of a and b--but not their values.""" |
| 455 |
|
| 456 |
res = True |
| 457 |
if isinstance(a, str) and isinstance(b, str): |
| 458 |
|
| 459 |
try: |
| 460 |
c_a = ffi.from_buffer(a.encode("ascii")) |
| 461 |
c_b = ffi.from_buffer(b.encode("ascii")) |
| 462 |
except Exception: |
| 463 |
raise TypeError("comparing strings with non-ASCII characters is " |
| 464 |
"not supported") |
| 465 |
length_a = len(a) |
| 466 |
length_b = len(b) |
| 467 |
|
| 468 |
else: |
| 469 |
try: |
| 470 |
b_a = memoryview(a) |
| 471 |
b_b = memoryview(b) |
| 472 |
except Exception: |
| 473 |
raise TypeError("unsupported operand types(s) or combination of " |
| 474 |
f"types: '{type(a)}' and '{type(b)}'") |
| 475 |
if b_a.ndim > 1: |
| 476 |
raise BufferError("Buffer must be a single dimension") |
| 477 |
if b_b.ndim > 1: |
| 478 |
raise BufferError("Buffer must be a single dimension") |
| 479 |
c_a = ffi.from_buffer(b_a.tobytes()) |
| 480 |
c_b = ffi.from_buffer(b_b.tobytes()) |
| 481 |
length_a = len(b_a) |
| 482 |
length_b = len(b_b) |
| 483 |
if length_a != length_b: |
| 484 |
res = False |
| 485 |
return (lib.CRYPTO_memcmp(c_a, c_b, length_b) == 0) and res |
| 486 |
|
| 487 |
|
| 488 |
def get_fips_mode(): |
| 489 |
"""Determine the OpenSSL FIPS mode of operation. |
| 490 |
|
| 491 |
For OpenSSL 3.0.0 and newer it returns the state of the default provider |
| 492 |
in the default OSSL context. It's not quite the same as FIPS_mode() but good |
| 493 |
enough for unittests. |
| 494 |
|
| 495 |
Effectively any non-zero return value indicates FIPS mode; |
| 496 |
values other than 1 may have additional significance.""" |
| 497 |
|
| 498 |
if lib.OPENSSL_VERSION_NUMBER > 0x30000000: |
| 499 |
return lib.EVP_default_properties_is_fips_enabled(ffi.NULL) |
| 500 |
lib.ERR_clear_error() |
| 501 |
result = lib.FIPS_mode() |
| 502 |
if result == 0: |
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
errcode = lib.ERR_peek_last_error(); |
| 508 |
if errcode: |
| 509 |
raise ValueError("could not call FIPS_mode") |
| 510 |
return result |
| 511 |
|
| 512 |
@cache |
| 513 |
def py_digest_by_name(name, py_ht): |
| 514 |
"""Get EVP_MD by HID and purpose""" |
| 515 |
|
| 516 |
ssl_name = _inverse_name_mapping.get(name, name) |
| 517 |
c_name = _str_to_ffi_buffer(ssl_name) |
| 518 |
if py_ht in (Py_ht_evp, Py_ht_mac, Py_ht_pbkdf2): |
| 519 |
digest = PY_EVP_MD_fetch(c_name, ffi.NULL) |
| 520 |
elif py_ht == Py_ht_evp_nosecurity: |
| 521 |
digest = PY_EVP_MD_fetch(c_name, _str_to_ffi_buffer("-fips")) |
| 522 |
if not digest: |
| 523 |
raise UnsupportedDigestmodError(f"unsupported hash type {name}") |
| 524 |
ffi.gc(digest, PY_EVP_MD_free) |
| 525 |
return digest |
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
_ctx_templates = {} |
| 532 |
|
| 533 |
def _get_ctx_template(digest_type): |
| 534 |
"""Return a cached pre-initialised EVP_MD_CTX for use as a copy_ex source.""" |
| 535 |
key = id(digest_type) |
| 536 |
template = _ctx_templates.get(key) |
| 537 |
if template is None: |
| 538 |
template = lib.EVP_MD_CTX_new() |
| 539 |
if template == ffi.NULL: |
| 540 |
raise MemoryError |
| 541 |
if lib.EVP_DigestInit_ex(template, digest_type, ffi.NULL) == 0: |
| 542 |
lib.EVP_MD_CTX_free(template) |
| 543 |
raise ValueError(get_errstr()) |
| 544 |
_ctx_templates[key] = template |
| 545 |
return template |
| 546 |
|
| 547 |
def py_digest_by_digestmod(digestmod): |
| 548 |
"""Get digest EVP from object""" |
| 549 |
if isinstance(digestmod, str): |
| 550 |
name_obj = digestmod |
| 551 |
else: |
| 552 |
name_obj = digestmod.__name__ |
| 553 |
if name_obj.startswith('openssl_'): |
| 554 |
name_obj = name_obj[8:] |
| 555 |
if not name_obj: |
| 556 |
raise UnsupportedDigestmodError(f"Unsupported digestemod {digestmod}") |
| 557 |
return py_digest_by_name(name_obj, Py_ht_mac), name_obj |
| 558 |
|
| 559 |
|
| 560 |
def hmac_digest(key, msg, digest): |
| 561 |
"""Single-shot HMAC""" |
| 562 |
if len(key) > sys.maxsize: |
| 563 |
raise OverflowError("key is too long") |
| 564 |
if len(msg) > sys.maxsize: |
| 565 |
raise OverflowError("msg is too long") |
| 566 |
evp, _ = py_digest_by_digestmod(digest) |
| 567 |
md = ffi.new("unsigned char[]", lib.EVP_MAX_MD_SIZE) |
| 568 |
md_len = ffi.new("unsigned int[1]", [0]) |
| 569 |
result = lib.HMAC(evp, _str_to_ffi_buffer(key), len(key), |
| 570 |
msg, len(msg), md, md_len) |
| 571 |
|
| 572 |
if not result: |
| 573 |
raise ValueError("could not call lib.HMAC") |
| 574 |
return _bytes_with_len(md, md_len[0]) |
| 575 |
|
| 576 |
def hmac_new(key, msg=b"", digestmod=None): |
| 577 |
"""Return a new HMAC object""" |
| 578 |
if len(key) > sys.maxsize: |
| 579 |
raise OverflowError("key is too long") |
| 580 |
if not digestmod: |
| 581 |
raise TypeError("Missing required parameter 'digestmod'") |
| 582 |
|
| 583 |
digest, digestmod = py_digest_by_digestmod(digestmod) |
| 584 |
ctx = lib.HMAC_CTX_new() |
| 585 |
if not ctx: |
| 586 |
raise ValueError("Could not allocate HMAC_CTX") |
| 587 |
r = lib.HMAC_Init_ex(ctx, _str_to_ffi_buffer(key), len(key), digest, ffi.NULL) |
| 588 |
if r == 0: |
| 589 |
raise ValueError("Could not initialize HMAC_CTX") |
| 590 |
self = HMAC(digestmod) |
| 591 |
self.ctx = ctx |
| 592 |
if msg: |
| 593 |
|
| 594 |
view = memoryview(msg) |
| 595 |
if len(view) > 2048: |
| 596 |
with self.lock: |
| 597 |
result = lib.HMAC_Update(ctx, _str_to_ffi_buffer(msg), len(view)) |
| 598 |
else: |
| 599 |
result = lib.HMAC_Update(ctx, _str_to_ffi_buffer(msg), len(view)) |
| 600 |
if r == 0: |
| 601 |
raise ValueError(f"could not hash msg '{msg}'") |
| 602 |
return self |