Development of an internal social media platform with personalised dashboards for students
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. # Normalize the PEM bundle's line endings.
  93. pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
  94. der_certs = [
  95. base64.b64decode(match.group(1))
  96. for match in _PEM_CERTS_RE.finditer(pem_bundle)
  97. ]
  98. if not der_certs:
  99. raise ssl.SSLError("No root certificates specified")
  100. cert_array = CoreFoundation.CFArrayCreateMutable(
  101. CoreFoundation.kCFAllocatorDefault,
  102. 0,
  103. ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)
  104. )
  105. if not cert_array:
  106. raise ssl.SSLError("Unable to allocate memory!")
  107. try:
  108. for der_bytes in der_certs:
  109. certdata = _cf_data_from_bytes(der_bytes)
  110. if not certdata:
  111. raise ssl.SSLError("Unable to allocate memory!")
  112. cert = Security.SecCertificateCreateWithData(
  113. CoreFoundation.kCFAllocatorDefault, certdata
  114. )
  115. CoreFoundation.CFRelease(certdata)
  116. if not cert:
  117. raise ssl.SSLError("Unable to build cert object!")
  118. CoreFoundation.CFArrayAppendValue(cert_array, cert)
  119. CoreFoundation.CFRelease(cert)
  120. except Exception:
  121. # We need to free the array before the exception bubbles further.
  122. # We only want to do that if an error occurs: otherwise, the caller
  123. # should free.
  124. CoreFoundation.CFRelease(cert_array)
  125. return cert_array
  126. def _is_cert(item):
  127. """
  128. Returns True if a given CFTypeRef is a certificate.
  129. """
  130. expected = Security.SecCertificateGetTypeID()
  131. return CoreFoundation.CFGetTypeID(item) == expected
  132. def _is_identity(item):
  133. """
  134. Returns True if a given CFTypeRef is an identity.
  135. """
  136. expected = Security.SecIdentityGetTypeID()
  137. return CoreFoundation.CFGetTypeID(item) == expected
  138. def _temporary_keychain():
  139. """
  140. This function creates a temporary Mac keychain that we can use to work with
  141. credentials. This keychain uses a one-time password and a temporary file to
  142. store the data. We expect to have one keychain per socket. The returned
  143. SecKeychainRef must be freed by the caller, including calling
  144. SecKeychainDelete.
  145. Returns a tuple of the SecKeychainRef and the path to the temporary
  146. directory that contains it.
  147. """
  148. # Unfortunately, SecKeychainCreate requires a path to a keychain. This
  149. # means we cannot use mkstemp to use a generic temporary file. Instead,
  150. # we're going to create a temporary directory and a filename to use there.
  151. # This filename will be 8 random bytes expanded into base64. We also need
  152. # some random bytes to password-protect the keychain we're creating, so we
  153. # ask for 40 random bytes.
  154. random_bytes = os.urandom(40)
  155. filename = base64.b16encode(random_bytes[:8]).decode('utf-8')
  156. password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8
  157. tempdirectory = tempfile.mkdtemp()
  158. keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')
  159. # We now want to create the keychain itself.
  160. keychain = Security.SecKeychainRef()
  161. status = Security.SecKeychainCreate(
  162. keychain_path,
  163. len(password),
  164. password,
  165. False,
  166. None,
  167. ctypes.byref(keychain)
  168. )
  169. _assert_no_error(status)
  170. # Having created the keychain, we want to pass it off to the caller.
  171. return keychain, tempdirectory
  172. def _load_items_from_file(keychain, path):
  173. """
  174. Given a single file, loads all the trust objects from it into arrays and
  175. the keychain.
  176. Returns a tuple of lists: the first list is a list of identities, the
  177. second a list of certs.
  178. """
  179. certificates = []
  180. identities = []
  181. result_array = None
  182. with open(path, 'rb') as f:
  183. raw_filedata = f.read()
  184. try:
  185. filedata = CoreFoundation.CFDataCreate(
  186. CoreFoundation.kCFAllocatorDefault,
  187. raw_filedata,
  188. len(raw_filedata)
  189. )
  190. result_array = CoreFoundation.CFArrayRef()
  191. result = Security.SecItemImport(
  192. filedata, # cert data
  193. None, # Filename, leaving it out for now
  194. None, # What the type of the file is, we don't care
  195. None, # what's in the file, we don't care
  196. 0, # import flags
  197. None, # key params, can include passphrase in the future
  198. keychain, # The keychain to insert into
  199. ctypes.byref(result_array) # Results
  200. )
  201. _assert_no_error(result)
  202. # A CFArray is not very useful to us as an intermediary
  203. # representation, so we are going to extract the objects we want
  204. # and then free the array. We don't need to keep hold of keys: the
  205. # keychain already has them!
  206. result_count = CoreFoundation.CFArrayGetCount(result_array)
  207. for index in range(result_count):
  208. item = CoreFoundation.CFArrayGetValueAtIndex(
  209. result_array, index
  210. )
  211. item = ctypes.cast(item, CoreFoundation.CFTypeRef)
  212. if _is_cert(item):
  213. CoreFoundation.CFRetain(item)
  214. certificates.append(item)
  215. elif _is_identity(item):
  216. CoreFoundation.CFRetain(item)
  217. identities.append(item)
  218. finally:
  219. if result_array:
  220. CoreFoundation.CFRelease(result_array)
  221. CoreFoundation.CFRelease(filedata)
  222. return (identities, certificates)
  223. def _load_client_cert_chain(keychain, *paths):
  224. """
  225. Load certificates and maybe keys from a number of files. Has the end goal
  226. of returning a CFArray containing one SecIdentityRef, and then zero or more
  227. SecCertificateRef objects, suitable for use as a client certificate trust
  228. chain.
  229. """
  230. # Ok, the strategy.
  231. #
  232. # This relies on knowing that macOS will not give you a SecIdentityRef
  233. # unless you have imported a key into a keychain. This is a somewhat
  234. # artificial limitation of macOS (for example, it doesn't necessarily
  235. # affect iOS), but there is nothing inside Security.framework that lets you
  236. # get a SecIdentityRef without having a key in a keychain.
  237. #
  238. # So the policy here is we take all the files and iterate them in order.
  239. # Each one will use SecItemImport to have one or more objects loaded from
  240. # it. We will also point at a keychain that macOS can use to work with the
  241. # private key.
  242. #
  243. # Once we have all the objects, we'll check what we actually have. If we
  244. # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,
  245. # we'll take the first certificate (which we assume to be our leaf) and
  246. # ask the keychain to give us a SecIdentityRef with that cert's associated
  247. # key.
  248. #
  249. # We'll then return a CFArray containing the trust chain: one
  250. # SecIdentityRef and then zero-or-more SecCertificateRef objects. The
  251. # responsibility for freeing this CFArray will be with the caller. This
  252. # CFArray must remain alive for the entire connection, so in practice it
  253. # will be stored with a single SSLSocket, along with the reference to the
  254. # keychain.
  255. certificates = []
  256. identities = []
  257. # Filter out bad paths.
  258. paths = (path for path in paths if path)
  259. try:
  260. for file_path in paths:
  261. new_identities, new_certs = _load_items_from_file(
  262. keychain, file_path
  263. )
  264. identities.extend(new_identities)
  265. certificates.extend(new_certs)
  266. # Ok, we have everything. The question is: do we have an identity? If
  267. # not, we want to grab one from the first cert we have.
  268. if not identities:
  269. new_identity = Security.SecIdentityRef()
  270. status = Security.SecIdentityCreateWithCertificate(
  271. keychain,
  272. certificates[0],
  273. ctypes.byref(new_identity)
  274. )
  275. _assert_no_error(status)
  276. identities.append(new_identity)
  277. # We now want to release the original certificate, as we no longer
  278. # need it.
  279. CoreFoundation.CFRelease(certificates.pop(0))
  280. # We now need to build a new CFArray that holds the trust chain.
  281. trust_chain = CoreFoundation.CFArrayCreateMutable(
  282. CoreFoundation.kCFAllocatorDefault,
  283. 0,
  284. ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
  285. )
  286. for item in itertools.chain(identities, certificates):
  287. # ArrayAppendValue does a CFRetain on the item. That's fine,
  288. # because the finally block will release our other refs to them.
  289. CoreFoundation.CFArrayAppendValue(trust_chain, item)
  290. return trust_chain
  291. finally:
  292. for obj in itertools.chain(identities, certificates):
  293. CoreFoundation.CFRelease(obj)