_raw_api.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 abc
  31. import sys
  32. import platform
  33. from Cryptodome.Util.py3compat import byte_string
  34. from Cryptodome.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. if sys.version_info[0] == 2 and sys.version_info[1] < 7:
  49. _buffer_type = (bytearray)
  50. else:
  51. _buffer_type = (bytearray, memoryview)
  52. class _VoidPointer(object):
  53. @abc.abstractmethod
  54. def get(self):
  55. """Return the memory location we point to"""
  56. return
  57. @abc.abstractmethod
  58. def address_of(self):
  59. """Return a raw pointer to this pointer"""
  60. return
  61. try:
  62. if sys.version_info[0] == 2 and sys.version_info[1] < 7:
  63. raise ImportError("CFFI is only supported with Python 2.7+")
  64. # Starting from v2.18, pycparser (used by cffi for in-line ABI mode)
  65. # stops working correctly when PYOPTIMIZE==2 or the parameter -OO is
  66. # passed. In that case, we fall back to ctypes.
  67. # Note that PyPy ships with an old version of pycparser so we can keep
  68. # using cffi there.
  69. # See https://github.com/Legrandin/pycryptodome/issues/228
  70. if platform.python_implementation() != "PyPy" and sys.flags.optimize == 2:
  71. raise ImportError("CFFI with optimize=2 fails due to pycparser bug.")
  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. lib = ffi.dlopen(name)
  84. ffi.cdef(cdecl)
  85. return lib
  86. def c_ulong(x):
  87. """Convert a Python integer to unsigned long"""
  88. return x
  89. c_ulonglong = c_ulong
  90. def c_size_t(x):
  91. """Convert a Python integer to size_t"""
  92. return x
  93. def create_string_buffer(init_or_size, size=None):
  94. """Allocate the given amount of bytes (initially set to 0)"""
  95. if isinstance(init_or_size, bytes):
  96. size = max(len(init_or_size) + 1, size)
  97. result = ffi.new("uint8_t[]", size)
  98. result[:] = init_or_size
  99. else:
  100. if size:
  101. raise ValueError("Size must be specified once only")
  102. result = ffi.new("uint8_t[]", init_or_size)
  103. return result
  104. def get_c_string(c_string):
  105. """Convert a C string into a Python byte sequence"""
  106. return ffi.string(c_string)
  107. def get_raw_buffer(buf):
  108. """Convert a C buffer into a Python byte sequence"""
  109. return ffi.buffer(buf)[:]
  110. def c_uint8_ptr(data):
  111. if isinstance(data, _buffer_type):
  112. # This only works for cffi >= 1.7
  113. return ffi.cast(uint8_t_type, ffi.from_buffer(data))
  114. elif byte_string(data) or isinstance(data, _Array):
  115. return data
  116. else:
  117. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  118. class VoidPointer_cffi(_VoidPointer):
  119. """Model a newly allocated pointer to void"""
  120. def __init__(self):
  121. self._pp = ffi.new("void *[1]")
  122. def get(self):
  123. return self._pp[0]
  124. def address_of(self):
  125. return self._pp
  126. def VoidPointer():
  127. return VoidPointer_cffi()
  128. backend = "cffi"
  129. except ImportError:
  130. import ctypes
  131. from ctypes import (CDLL, c_void_p, byref, c_ulong, c_ulonglong, c_size_t,
  132. create_string_buffer, c_ubyte)
  133. from ctypes.util import find_library
  134. from ctypes import Array as _Array
  135. null_pointer = None
  136. def load_lib(name, cdecl):
  137. import platform
  138. bits, linkage = platform.architecture()
  139. if "." not in name and not linkage.startswith("Win"):
  140. full_name = find_library(name)
  141. if full_name is None:
  142. raise OSError("Cannot load library '%s'" % name)
  143. name = full_name
  144. return CDLL(name)
  145. def get_c_string(c_string):
  146. return c_string.value
  147. def get_raw_buffer(buf):
  148. return buf.raw
  149. # ---- Get raw pointer ---
  150. if sys.version_info[0] == 2 and sys.version_info[1] == 6:
  151. # ctypes in 2.6 does not define c_ssize_t. Replacing it
  152. # with c_size_t keeps the structure correctely laid out
  153. _c_ssize_t = c_size_t
  154. else:
  155. _c_ssize_t = ctypes.c_ssize_t
  156. _PyBUF_SIMPLE = 0
  157. _PyObject_GetBuffer = ctypes.pythonapi.PyObject_GetBuffer
  158. _py_object = ctypes.py_object
  159. _c_ssize_p = ctypes.POINTER(_c_ssize_t)
  160. # See Include/object.h for CPython
  161. # and https://github.com/pallets/click/blob/master/click/_winconsole.py
  162. class _Py_buffer(ctypes.Structure):
  163. _fields_ = [
  164. ('buf', c_void_p),
  165. ('obj', ctypes.py_object),
  166. ('len', _c_ssize_t),
  167. ('itemsize', _c_ssize_t),
  168. ('readonly', ctypes.c_int),
  169. ('ndim', ctypes.c_int),
  170. ('format', ctypes.c_char_p),
  171. ('shape', _c_ssize_p),
  172. ('strides', _c_ssize_p),
  173. ('suboffsets', _c_ssize_p),
  174. ('internal', c_void_p)
  175. ]
  176. # Extra field for CPython 2.6/2.7
  177. if sys.version_info[0] == 2:
  178. _fields_.insert(-1, ('smalltable', _c_ssize_t * 2))
  179. def c_uint8_ptr(data):
  180. if byte_string(data) or isinstance(data, _Array):
  181. return data
  182. elif isinstance(data, _buffer_type):
  183. obj = _py_object(data)
  184. buf = _Py_buffer()
  185. _PyObject_GetBuffer(obj, byref(buf), _PyBUF_SIMPLE)
  186. buffer_type = c_ubyte * buf.len
  187. return buffer_type.from_address(buf.buf)
  188. else:
  189. raise TypeError("Object type %s cannot be passed to C code" % type(data))
  190. # ---
  191. class VoidPointer_ctypes(_VoidPointer):
  192. """Model a newly allocated pointer to void"""
  193. def __init__(self):
  194. self._p = c_void_p()
  195. def get(self):
  196. return self._p
  197. def address_of(self):
  198. return byref(self._p)
  199. def VoidPointer():
  200. return VoidPointer_ctypes()
  201. backend = "ctypes"
  202. del ctypes
  203. class SmartPointer(object):
  204. """Class to hold a non-managed piece of memory"""
  205. def __init__(self, raw_pointer, destructor):
  206. self._raw_pointer = raw_pointer
  207. self._destructor = destructor
  208. def get(self):
  209. return self._raw_pointer
  210. def release(self):
  211. rp, self._raw_pointer = self._raw_pointer, None
  212. return rp
  213. def __del__(self):
  214. try:
  215. if self._raw_pointer is not None:
  216. self._destructor(self._raw_pointer)
  217. self._raw_pointer = None
  218. except AttributeError:
  219. pass
  220. def load_pycryptodome_raw_lib(name, cdecl):
  221. """Load a shared library and return a handle to it.
  222. @name, the name of the library expressed as a PyCryptodome module,
  223. for instance Cryptodome.Cipher._raw_cbc.
  224. @cdecl, the C function declarations.
  225. """
  226. split = name.split(".")
  227. dir_comps, basename = split[:-1], split[-1]
  228. attempts = []
  229. for ext in extension_suffixes:
  230. try:
  231. filename = basename + ext
  232. return load_lib(pycryptodome_filename(dir_comps, filename),
  233. cdecl)
  234. except OSError as exp:
  235. attempts.append("Trying '%s': %s" % (filename, str(exp)))
  236. raise OSError("Cannot load native module '%s': %s" % (name, ", ".join(attempts)))
  237. if sys.version_info[:2] != (2, 6):
  238. def is_buffer(x):
  239. """Return True if object x supports the buffer interface"""
  240. return isinstance(x, (bytes, bytearray, memoryview))
  241. def is_writeable_buffer(x):
  242. return (isinstance(x, bytearray) or
  243. (isinstance(x, memoryview) and not x.readonly))
  244. else:
  245. def is_buffer(x):
  246. return isinstance(x, (bytes, bytearray))
  247. def is_writeable_buffer(x):
  248. return isinstance(x, bytearray)