_raw_api.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. import os
  31. import abc
  32. import sys
  33. from Crypto.Util.py3compat import byte_string
  34. from Crypto.Util._file_system import pycryptodome_filename
  35. #
  36. # List of file suffixes for Python extensions
  37. #
  38. if sys.version_info[0] < 3:
  39. import imp
  40. extension_suffixes = []
  41. for ext, mod, typ in imp.get_suffixes():
  42. if typ == imp.C_EXTENSION:
  43. extension_suffixes.append(ext)
  44. else:
  45. from importlib import machinery
  46. extension_suffixes = machinery.EXTENSION_SUFFIXES
  47. # Which types with buffer interface we support (apart from byte strings)
  48. _buffer_type = (bytearray, memoryview)
  49. class _VoidPointer(object):
  50. @abc.abstractmethod
  51. def get(self):
  52. """Return the memory location we point to"""
  53. return
  54. @abc.abstractmethod
  55. def address_of(self):
  56. """Return a raw pointer to this pointer"""
  57. return
  58. try:
  59. # Starting from v2.18, pycparser (used by cffi for in-line ABI mode)
  60. # stops working correctly when PYOPTIMIZE==2 or the parameter -OO is
  61. # passed. In that case, we fall back to ctypes.
  62. # Note that PyPy ships with an old version of pycparser so we can keep
  63. # using cffi there.
  64. # See https://github.com/Legrandin/pycryptodome/issues/228
  65. if '__pypy__' not in sys.builtin_module_names and sys.flags.optimize == 2:
  66. raise ImportError("CFFI with optimize=2 fails due to pycparser bug.")
  67. # cffi still uses PyUnicode_GetSize, which was removed in Python 3.12
  68. # thus leading to a crash on cffi.dlopen()
  69. # See https://groups.google.com/u/1/g/python-cffi/c/oZkOIZ_zi5k
  70. if sys.version_info >= (3, 12) and os.name == "nt":
  71. raise ImportError("CFFI is not compatible with Python 3.12 on Windows")
  72. from cffi import FFI
  73. ffi = FFI()
  74. null_pointer = ffi.NULL
  75. uint8_t_type = ffi.typeof(ffi.new("const uint8_t*"))
  76. _Array = ffi.new("uint8_t[1]").__class__.__bases__
  77. def load_lib(name, cdecl):
  78. """Load a shared library and return a handle to it.
  79. @name, either an absolute path or the name of a library
  80. in the system search path.
  81. @cdecl, the C function declarations.
  82. """
  83. if hasattr(ffi, "RTLD_DEEPBIND") and not os.getenv('PYCRYPTODOME_DISABLE_DEEPBIND'):
  84. lib = ffi.dlopen(name, ffi.RTLD_DEEPBIND)
  85. else:
  86. lib = ffi.dlopen(name)
  87. ffi.cdef(cdecl)
  88. return lib
  89. def c_ulong(x):
  90. """Convert a Python integer to unsigned long"""
  91. return x
  92. c_ulonglong = c_ulong
  93. c_uint = c_ulong
  94. c_ubyte = c_ulong
  95. def c_size_t(x):
  96. """Convert a Python integer to size_t"""
  97. return x
  98. def create_string_buffer(init_or_size, size=None):
  99. """Allocate the given amount of bytes (initially set to 0)"""
  100. if isinstance(init_or_size, bytes):
  101. size = max(len(init_or_size) + 1, size)
  102. result = ffi.new("uint8_t[]", size)
  103. result[:] = init_or_size
  104. else:
  105. if size:
  106. raise ValueError("Size must be specified once only")
  107. result = ffi.new("uint8_t[]", init_or_size)
  108. return result
  109. def get_c_string(c_string):
  110. """Convert a C string into a Python byte sequence"""
  111. return ffi.string(c_string)
  112. def get_raw_buffer(buf):
  113. """Convert a C buffer into a Python byte sequence"""
  114. return ffi.buffer(buf)[:]
  115. def c_uint8_ptr(data):
  116. if isinstance(data, _buffer_type):
  117. # This only works for cffi >= 1.7
  118. return ffi.cast(uint8_t_type, ffi.from_buffer(data))
  119. elif byte_string(data) or isinstance(data, _Array):
  120. return data
  121. else:
  122. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  123. class VoidPointer_cffi(_VoidPointer):
  124. """Model a newly allocated pointer to void"""
  125. def __init__(self):
  126. self._pp = ffi.new("void *[1]")
  127. def get(self):
  128. return self._pp[0]
  129. def address_of(self):
  130. return self._pp
  131. def VoidPointer():
  132. return VoidPointer_cffi()
  133. backend = "cffi"
  134. except ImportError:
  135. import ctypes
  136. from ctypes import (CDLL, c_void_p, byref, c_ulong, c_ulonglong, c_size_t,
  137. create_string_buffer, c_ubyte, c_uint)
  138. from ctypes.util import find_library
  139. from ctypes import Array as _Array
  140. null_pointer = None
  141. cached_architecture = []
  142. def c_ubyte(c):
  143. if not (0 <= c < 256):
  144. raise OverflowError()
  145. return ctypes.c_ubyte(c)
  146. def load_lib(name, cdecl):
  147. if not cached_architecture:
  148. # platform.architecture() creates a subprocess, so caching the
  149. # result makes successive imports faster.
  150. import platform
  151. cached_architecture[:] = platform.architecture()
  152. bits, linkage = cached_architecture
  153. if "." not in name and not linkage.startswith("Win"):
  154. full_name = find_library(name)
  155. if full_name is None:
  156. raise OSError("Cannot load library '%s'" % name)
  157. name = full_name
  158. return CDLL(name)
  159. def get_c_string(c_string):
  160. return c_string.value
  161. def get_raw_buffer(buf):
  162. return buf.raw
  163. # ---- Get raw pointer ---
  164. _c_ssize_t = ctypes.c_ssize_t
  165. _PyBUF_SIMPLE = 0
  166. _PyObject_GetBuffer = ctypes.pythonapi.PyObject_GetBuffer
  167. _PyBuffer_Release = ctypes.pythonapi.PyBuffer_Release
  168. _py_object = ctypes.py_object
  169. _c_ssize_p = ctypes.POINTER(_c_ssize_t)
  170. # See Include/object.h for CPython
  171. # and https://github.com/pallets/click/blob/master/src/click/_winconsole.py
  172. class _Py_buffer(ctypes.Structure):
  173. _fields_ = [
  174. ('buf', c_void_p),
  175. ('obj', ctypes.py_object),
  176. ('len', _c_ssize_t),
  177. ('itemsize', _c_ssize_t),
  178. ('readonly', ctypes.c_int),
  179. ('ndim', ctypes.c_int),
  180. ('format', ctypes.c_char_p),
  181. ('shape', _c_ssize_p),
  182. ('strides', _c_ssize_p),
  183. ('suboffsets', _c_ssize_p),
  184. ('internal', c_void_p)
  185. ]
  186. # Extra field for CPython 2.6/2.7
  187. if sys.version_info[0] == 2:
  188. _fields_.insert(-1, ('smalltable', _c_ssize_t * 2))
  189. def c_uint8_ptr(data):
  190. if byte_string(data) or isinstance(data, _Array):
  191. return data
  192. elif isinstance(data, _buffer_type):
  193. obj = _py_object(data)
  194. buf = _Py_buffer()
  195. _PyObject_GetBuffer(obj, byref(buf), _PyBUF_SIMPLE)
  196. try:
  197. buffer_type = ctypes.c_ubyte * buf.len
  198. return buffer_type.from_address(buf.buf)
  199. finally:
  200. _PyBuffer_Release(byref(buf))
  201. else:
  202. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  203. # ---
  204. class VoidPointer_ctypes(_VoidPointer):
  205. """Model a newly allocated pointer to void"""
  206. def __init__(self):
  207. self._p = c_void_p()
  208. def get(self):
  209. return self._p
  210. def address_of(self):
  211. return byref(self._p)
  212. def VoidPointer():
  213. return VoidPointer_ctypes()
  214. backend = "ctypes"
  215. class SmartPointer(object):
  216. """Class to hold a non-managed piece of memory"""
  217. def __init__(self, raw_pointer, destructor):
  218. self._raw_pointer = raw_pointer
  219. self._destructor = destructor
  220. def get(self):
  221. return self._raw_pointer
  222. def release(self):
  223. rp, self._raw_pointer = self._raw_pointer, None
  224. return rp
  225. def __del__(self):
  226. try:
  227. if self._raw_pointer is not None:
  228. self._destructor(self._raw_pointer)
  229. self._raw_pointer = None
  230. except AttributeError:
  231. pass
  232. def load_pycryptodome_raw_lib(name, cdecl):
  233. """Load a shared library and return a handle to it.
  234. @name, the name of the library expressed as a PyCryptodome module,
  235. for instance Crypto.Cipher._raw_cbc.
  236. @cdecl, the C function declarations.
  237. """
  238. split = name.split(".")
  239. dir_comps, basename = split[:-1], split[-1]
  240. attempts = []
  241. for ext in extension_suffixes:
  242. try:
  243. filename = basename + ext
  244. full_name = pycryptodome_filename(dir_comps, filename)
  245. if not os.path.isfile(full_name):
  246. attempts.append("Not found '%s'" % filename)
  247. continue
  248. return load_lib(full_name, cdecl)
  249. except OSError as exp:
  250. attempts.append("Cannot load '%s': %s" % (filename, str(exp)))
  251. raise OSError("Cannot load native module '%s': %s" % (name, ", ".join(attempts)))
  252. def is_buffer(x):
  253. """Return True if object x supports the buffer interface"""
  254. return isinstance(x, (bytes, bytearray, memoryview))
  255. def is_writeable_buffer(x):
  256. return (isinstance(x, bytearray) or
  257. (isinstance(x, memoryview) and not x.readonly))