You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

low_level.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. """
  2. Low-level helpers for the SecureTransport bindings.
  3. These are Python functions that are not directly related to the high-level APIs
  4. but are necessary to get them to work. They include a whole bunch of low-level
  5. CoreFoundation messing about and memory management. The concerns in this module
  6. are almost entirely about trying to avoid memory leaks and providing
  7. appropriate and useful assistance to the higher-level code.
  8. """
  9. import base64
  10. import ctypes
  11. import itertools
  12. import re
  13. import os
  14. import ssl
  15. import tempfile
  16. from .bindings import Security, CoreFoundation, CFConst
  17. # This regular expression is used to grab PEM data out of a PEM bundle.
  18. _PEM_CERTS_RE = re.compile(
  19. b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL
  20. )
  21. def _cf_data_from_bytes(bytestring):
  22. """
  23. Given a bytestring, create a CFData object from it. This CFData object must
  24. be CFReleased by the caller.
  25. """
  26. return CoreFoundation.CFDataCreate(
  27. CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)
  28. )
  29. def _cf_dictionary_from_tuples(tuples):
  30. """
  31. Given a list of Python tuples, create an associated CFDictionary.
  32. """
  33. dictionary_size = len(tuples)
  34. # We need to get the dictionary keys and values out in the same order.
  35. keys = (t[0] for t in tuples)
  36. values = (t[1] for t in tuples)
  37. cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)
  38. cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)
  39. return CoreFoundation.CFDictionaryCreate(
  40. CoreFoundation.kCFAllocatorDefault,
  41. cf_keys,
  42. cf_values,
  43. dictionary_size,
  44. CoreFoundation.kCFTypeDictionaryKeyCallBacks,
  45. CoreFoundation.kCFTypeDictionaryValueCallBacks,
  46. )
  47. def _cf_string_to_unicode(value):
  48. """
  49. Creates a Unicode string from a CFString object. Used entirely for error
  50. reporting.
  51. Yes, it annoys me quite a lot that this function is this complex.
  52. """
  53. value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
  54. string = CoreFoundation.CFStringGetCStringPtr(
  55. value_as_void_p,
  56. CFConst.kCFStringEncodingUTF8
  57. )
  58. if string is None:
  59. buffer = ctypes.create_string_buffer(1024)
  60. result = CoreFoundation.CFStringGetCString(
  61. value_as_void_p,
  62. buffer,
  63. 1024,
  64. CFConst.kCFStringEncodingUTF8
  65. )
  66. if not result:
  67. raise OSError('Error copying C string from CFStringRef')
  68. string = buffer.value
  69. if string is not None:
  70. string = string.decode('utf-8')
  71. return string
  72. def _assert_no_error(error, exception_class=None):
  73. """
  74. Checks the return code and throws an exception if there is an error to
  75. report
  76. """
  77. if error == 0:
  78. return
  79. cf_error_string = Security.SecCopyErrorMessageString(error, None)
  80. output = _cf_string_to_unicode(cf_error_string)
  81. CoreFoundation.CFRelease(cf_error_string)
  82. if output is None or output == u'':
  83. output = u'OSStatus %s' % error
  84. if exception_class is None:
  85. exception_class = ssl.SSLError
  86. raise exception_class(output)
  87. def _cert_array_from_pem(pem_bundle):
  88. """
  89. Given a bundle of certs in PEM format, turns them into a CFArray of certs
  90. that can be used to validate a cert chain.
  91. """
  92. der_certs = [
  93. base64.b64decode(match.group(1))
  94. for match in _PEM_CERTS_RE.finditer(pem_bundle)
  95. ]
  96. if not der_certs:
  97. raise ssl.SSLError("No root certificates specified")
  98. cert_array = CoreFoundation.CFArrayCreateMutable(
  99. CoreFoundation.kCFAllocatorDefault,
  100. 0,
  101. ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)
  102. )
  103. if not cert_array:
  104. raise ssl.SSLError("Unable to allocate memory!")
  105. try:
  106. for der_bytes in der_certs:
  107. certdata = _cf_data_from_bytes(der_bytes)
  108. if not certdata:
  109. raise ssl.SSLError("Unable to allocate memory!")
  110. cert = Security.SecCertificateCreateWithData(
  111. CoreFoundation.kCFAllocatorDefault, certdata
  112. )
  113. CoreFoundation.CFRelease(certdata)
  114. if not cert:
  115. raise ssl.SSLError("Unable to build cert object!")
  116. CoreFoundation.CFArrayAppendValue(cert_array, cert)
  117. CoreFoundation.CFRelease(cert)
  118. except Exception:
  119. # We need to free the array before the exception bubbles further.
  120. # We only want to do that if an error occurs: otherwise, the caller
  121. # should free.
  122. CoreFoundation.CFRelease(cert_array)
  123. return cert_array
  124. def _is_cert(item):
  125. """
  126. Returns True if a given CFTypeRef is a certificate.
  127. """
  128. expected = Security.SecCertificateGetTypeID()
  129. return CoreFoundation.CFGetTypeID(item) == expected
  130. def _is_identity(item):
  131. """
  132. Returns True if a given CFTypeRef is an identity.
  133. """
  134. expected = Security.SecIdentityGetTypeID()
  135. return CoreFoundation.CFGetTypeID(item) == expected
  136. def _temporary_keychain():
  137. """
  138. This function creates a temporary Mac keychain that we can use to work with
  139. credentials. This keychain uses a one-time password and a temporary file to
  140. store the data. We expect to have one keychain per socket. The returned
  141. SecKeychainRef must be freed by the caller, including calling
  142. SecKeychainDelete.
  143. Returns a tuple of the SecKeychainRef and the path to the temporary
  144. directory that contains it.
  145. """
  146. # Unfortunately, SecKeychainCreate requires a path to a keychain. This
  147. # means we cannot use mkstemp to use a generic temporary file. Instead,
  148. # we're going to create a temporary directory and a filename to use there.
  149. # This filename will be 8 random bytes expanded into base64. We also need
  150. # some random bytes to password-protect the keychain we're creating, so we
  151. # ask for 40 random bytes.
  152. random_bytes = os.urandom(40)
  153. filename = base64.b64encode(random_bytes[:8]).decode('utf-8')
  154. password = base64.b64encode(random_bytes[8:]) # Must be valid UTF-8
  155. tempdirectory = tempfile.mkdtemp()
  156. keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')
  157. # We now want to create the keychain itself.
  158. keychain = Security.SecKeychainRef()
  159. status = Security.SecKeychainCreate(
  160. keychain_path,
  161. len(password),
  162. password,
  163. False,
  164. None,
  165. ctypes.byref(keychain)
  166. )
  167. _assert_no_error(status)
  168. # Having created the keychain, we want to pass it off to the caller.
  169. return keychain, tempdirectory
  170. def _load_items_from_file(keychain, path):
  171. """
  172. Given a single file, loads all the trust objects from it into arrays and
  173. the keychain.
  174. Returns a tuple of lists: the first list is a list of identities, the
  175. second a list of certs.
  176. """
  177. certificates = []
  178. identities = []
  179. result_array = None
  180. with open(path, 'rb') as f:
  181. raw_filedata = f.read()
  182. try:
  183. filedata = CoreFoundation.CFDataCreate(
  184. CoreFoundation.kCFAllocatorDefault,
  185. raw_filedata,
  186. len(raw_filedata)
  187. )
  188. result_array = CoreFoundation.CFArrayRef()
  189. result = Security.SecItemImport(
  190. filedata, # cert data
  191. None, # Filename, leaving it out for now
  192. None, # What the type of the file is, we don't care
  193. None, # what's in the file, we don't care
  194. 0, # import flags
  195. None, # key params, can include passphrase in the future
  196. keychain, # The keychain to insert into
  197. ctypes.byref(result_array) # Results
  198. )
  199. _assert_no_error(result)
  200. # A CFArray is not very useful to us as an intermediary
  201. # representation, so we are going to extract the objects we want
  202. # and then free the array. We don't need to keep hold of keys: the
  203. # keychain already has them!
  204. result_count = CoreFoundation.CFArrayGetCount(result_array)
  205. for index in range(result_count):
  206. item = CoreFoundation.CFArrayGetValueAtIndex(
  207. result_array, index
  208. )
  209. item = ctypes.cast(item, CoreFoundation.CFTypeRef)
  210. if _is_cert(item):
  211. CoreFoundation.CFRetain(item)
  212. certificates.append(item)
  213. elif _is_identity(item):
  214. CoreFoundation.CFRetain(item)
  215. identities.append(item)
  216. finally:
  217. if result_array:
  218. CoreFoundation.CFRelease(result_array)
  219. CoreFoundation.CFRelease(filedata)
  220. return (identities, certificates)
  221. def _load_client_cert_chain(keychain, *paths):
  222. """
  223. Load certificates and maybe keys from a number of files. Has the end goal
  224. of returning a CFArray containing one SecIdentityRef, and then zero or more
  225. SecCertificateRef objects, suitable for use as a client certificate trust
  226. chain.
  227. """
  228. # Ok, the strategy.
  229. #
  230. # This relies on knowing that macOS will not give you a SecIdentityRef
  231. # unless you have imported a key into a keychain. This is a somewhat
  232. # artificial limitation of macOS (for example, it doesn't necessarily
  233. # affect iOS), but there is nothing inside Security.framework that lets you
  234. # get a SecIdentityRef without having a key in a keychain.
  235. #
  236. # So the policy here is we take all the files and iterate them in order.
  237. # Each one will use SecItemImport to have one or more objects loaded from
  238. # it. We will also point at a keychain that macOS can use to work with the
  239. # private key.
  240. #
  241. # Once we have all the objects, we'll check what we actually have. If we
  242. # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,
  243. # we'll take the first certificate (which we assume to be our leaf) and
  244. # ask the keychain to give us a SecIdentityRef with that cert's associated
  245. # key.
  246. #
  247. # We'll then return a CFArray containing the trust chain: one
  248. # SecIdentityRef and then zero-or-more SecCertificateRef objects. The
  249. # responsibility for freeing this CFArray will be with the caller. This
  250. # CFArray must remain alive for the entire connection, so in practice it
  251. # will be stored with a single SSLSocket, along with the reference to the
  252. # keychain.
  253. certificates = []
  254. identities = []
  255. # Filter out bad paths.
  256. paths = (path for path in paths if path)
  257. try:
  258. for file_path in paths:
  259. new_identities, new_certs = _load_items_from_file(
  260. keychain, file_path
  261. )
  262. identities.extend(new_identities)
  263. certificates.extend(new_certs)
  264. # Ok, we have everything. The question is: do we have an identity? If
  265. # not, we want to grab one from the first cert we have.
  266. if not identities:
  267. new_identity = Security.SecIdentityRef()
  268. status = Security.SecIdentityCreateWithCertificate(
  269. keychain,
  270. certificates[0],
  271. ctypes.byref(new_identity)
  272. )
  273. _assert_no_error(status)
  274. identities.append(new_identity)
  275. # We now want to release the original certificate, as we no longer
  276. # need it.
  277. CoreFoundation.CFRelease(certificates.pop(0))
  278. # We now need to build a new CFArray that holds the trust chain.
  279. trust_chain = CoreFoundation.CFArrayCreateMutable(
  280. CoreFoundation.kCFAllocatorDefault,
  281. 0,
  282. ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
  283. )
  284. for item in itertools.chain(identities, certificates):
  285. # ArrayAppendValue does a CFRetain on the item. That's fine,
  286. # because the finally block will release our other refs to them.
  287. CoreFoundation.CFArrayAppendValue(trust_chain, item)
  288. return trust_chain
  289. finally:
  290. for obj in itertools.chain(identities, certificates):
  291. CoreFoundation.CFRelease(obj)