binding.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import annotations
  5. import os
  6. import sys
  7. import threading
  8. import types
  9. import typing
  10. import warnings
  11. from collections.abc import Callable
  12. import cryptography
  13. from cryptography.exceptions import InternalError
  14. from cryptography.hazmat.bindings._rust import _openssl, openssl
  15. from cryptography.hazmat.bindings.openssl._conditional import CONDITIONAL_NAMES
  16. def _openssl_assert(ok: bool) -> None:
  17. if not ok:
  18. errors = openssl.capture_error_stack()
  19. raise InternalError(
  20. "Unknown OpenSSL error. This error is commonly encountered when "
  21. "another library is not cleaning up the OpenSSL error stack. If "
  22. "you are using cryptography with another library that uses "
  23. "OpenSSL try disabling it before reporting a bug. Otherwise "
  24. "please file an issue at https://github.com/pyca/cryptography/"
  25. "issues with information on how to reproduce "
  26. f"this. ({errors!r})",
  27. errors,
  28. )
  29. def build_conditional_library(
  30. lib: typing.Any,
  31. conditional_names: dict[str, Callable[[], list[str]]],
  32. ) -> typing.Any:
  33. conditional_lib = types.ModuleType("lib")
  34. conditional_lib._original_lib = lib # type: ignore[attr-defined]
  35. excluded_names = set()
  36. for condition, names_cb in conditional_names.items():
  37. if not getattr(lib, condition):
  38. excluded_names.update(names_cb())
  39. for attr in dir(lib):
  40. if attr not in excluded_names:
  41. setattr(conditional_lib, attr, getattr(lib, attr))
  42. return conditional_lib
  43. class Binding:
  44. """
  45. OpenSSL API wrapper.
  46. """
  47. lib: typing.ClassVar[typing.Any] = None
  48. ffi: typing.Any = _openssl.ffi
  49. _lib_loaded = False
  50. _init_lock = threading.Lock()
  51. def __init__(self) -> None:
  52. self._ensure_ffi_initialized()
  53. @classmethod
  54. def _ensure_ffi_initialized(cls) -> None:
  55. with cls._init_lock:
  56. if not cls._lib_loaded:
  57. cls.lib = build_conditional_library(
  58. _openssl.lib, CONDITIONAL_NAMES
  59. )
  60. cls._lib_loaded = True
  61. @classmethod
  62. def init_static_locks(cls) -> None:
  63. cls._ensure_ffi_initialized()
  64. def _verify_package_version(version: str) -> None:
  65. # Occasionally we run into situations where the version of the Python
  66. # package does not match the version of the shared object that is loaded.
  67. # This may occur in environments where multiple versions of cryptography
  68. # are installed and available in the python path. To avoid errors cropping
  69. # up later this code checks that the currently imported package and the
  70. # shared object that were loaded have the same version and raise an
  71. # ImportError if they do not
  72. so_package_version = _openssl.ffi.string(
  73. _openssl.lib.CRYPTOGRAPHY_PACKAGE_VERSION
  74. )
  75. if version.encode("ascii") != so_package_version:
  76. raise ImportError(
  77. "The version of cryptography does not match the loaded "
  78. "shared object. This can happen if you have multiple copies of "
  79. "cryptography installed in your Python path. Please try creating "
  80. "a new virtual environment to resolve this issue. "
  81. f"Loaded python version: {version}, "
  82. f"shared object version: {so_package_version}"
  83. )
  84. _openssl_assert(
  85. _openssl.lib.OpenSSL_version_num() == openssl.openssl_version(),
  86. )
  87. _verify_package_version(cryptography.__version__)
  88. Binding.init_static_locks()
  89. if (
  90. sys.platform == "win32"
  91. and os.environ.get("PROCESSOR_ARCHITEW6432") is not None
  92. ):
  93. warnings.warn(
  94. "You are using cryptography on a 32-bit Python on a 64-bit Windows "
  95. "Operating System. Cryptography will be significantly faster if you "
  96. "switch to using a 64-bit Python.",
  97. UserWarning,
  98. stacklevel=2,
  99. )