low_level.py 14 KB

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