SSL.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. from sys import platform
  2. from functools import wraps, partial
  3. from itertools import count, chain
  4. from weakref import WeakValueDictionary
  5. from errno import errorcode
  6. from six import text_type as _text_type
  7. from six import binary_type as _binary_type
  8. from six import integer_types as integer_types
  9. from six import int2byte, indexbytes
  10. from OpenSSL._util import (
  11. ffi as _ffi,
  12. lib as _lib,
  13. exception_from_error_queue as _exception_from_error_queue,
  14. native as _native,
  15. text_to_bytes_and_warn as _text_to_bytes_and_warn,
  16. path_string as _path_string,
  17. UNSPECIFIED as _UNSPECIFIED,
  18. )
  19. from OpenSSL.crypto import (
  20. FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
  21. try:
  22. _memoryview = memoryview
  23. except NameError:
  24. class _memoryview(object):
  25. pass
  26. try:
  27. _buffer = buffer
  28. except NameError:
  29. class _buffer(object):
  30. pass
  31. OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
  32. SSLEAY_VERSION = _lib.SSLEAY_VERSION
  33. SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
  34. SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
  35. SSLEAY_DIR = _lib.SSLEAY_DIR
  36. SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
  37. SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
  38. RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
  39. SSLv2_METHOD = 1
  40. SSLv3_METHOD = 2
  41. SSLv23_METHOD = 3
  42. TLSv1_METHOD = 4
  43. TLSv1_1_METHOD = 5
  44. TLSv1_2_METHOD = 6
  45. OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
  46. OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
  47. OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
  48. OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
  49. OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
  50. try:
  51. MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
  52. except AttributeError:
  53. pass
  54. OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
  55. OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
  56. OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
  57. OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
  58. OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
  59. OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
  60. OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
  61. try:
  62. OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
  63. except AttributeError:
  64. pass
  65. OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
  66. OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
  67. OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
  68. OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  69. OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
  70. OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
  71. OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
  72. OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
  73. OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
  74. OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG= _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
  75. try:
  76. OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
  77. except AttributeError:
  78. pass
  79. OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
  80. OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
  81. try:
  82. OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
  83. except AttributeError:
  84. pass
  85. OP_ALL = _lib.SSL_OP_ALL
  86. VERIFY_PEER = _lib.SSL_VERIFY_PEER
  87. VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  88. VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
  89. VERIFY_NONE = _lib.SSL_VERIFY_NONE
  90. SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
  91. SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
  92. SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
  93. SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
  94. SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
  95. SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
  96. SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
  97. SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
  98. SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
  99. SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
  100. SSL_ST_MASK = _lib.SSL_ST_MASK
  101. SSL_ST_INIT = _lib.SSL_ST_INIT
  102. SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
  103. SSL_ST_OK = _lib.SSL_ST_OK
  104. SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
  105. SSL_CB_LOOP = _lib.SSL_CB_LOOP
  106. SSL_CB_EXIT = _lib.SSL_CB_EXIT
  107. SSL_CB_READ = _lib.SSL_CB_READ
  108. SSL_CB_WRITE = _lib.SSL_CB_WRITE
  109. SSL_CB_ALERT = _lib.SSL_CB_ALERT
  110. SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
  111. SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
  112. SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
  113. SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
  114. SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
  115. SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
  116. SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
  117. SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
  118. class Error(Exception):
  119. """
  120. An error occurred in an `OpenSSL.SSL` API.
  121. """
  122. _raise_current_error = partial(_exception_from_error_queue, Error)
  123. class WantReadError(Error):
  124. pass
  125. class WantWriteError(Error):
  126. pass
  127. class WantX509LookupError(Error):
  128. pass
  129. class ZeroReturnError(Error):
  130. pass
  131. class SysCallError(Error):
  132. pass
  133. class _CallbackExceptionHelper(object):
  134. """
  135. A base class for wrapper classes that allow for intelligent exception
  136. handling in OpenSSL callbacks.
  137. :ivar list _problems: Any exceptions that occurred while executing in a
  138. context where they could not be raised in the normal way. Typically
  139. this is because OpenSSL has called into some Python code and requires a
  140. return value. The exceptions are saved to be raised later when it is
  141. possible to do so.
  142. """
  143. def __init__(self):
  144. self._problems = []
  145. def raise_if_problem(self):
  146. """
  147. Raise an exception from the OpenSSL error queue or that was previously
  148. captured whe running a callback.
  149. """
  150. if self._problems:
  151. try:
  152. _raise_current_error()
  153. except Error:
  154. pass
  155. raise self._problems.pop(0)
  156. class _VerifyHelper(_CallbackExceptionHelper):
  157. """
  158. Wrap a callback such that it can be used as a certificate verification
  159. callback.
  160. """
  161. def __init__(self, callback):
  162. _CallbackExceptionHelper.__init__(self)
  163. @wraps(callback)
  164. def wrapper(ok, store_ctx):
  165. cert = X509.__new__(X509)
  166. cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
  167. error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
  168. error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
  169. index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
  170. ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
  171. connection = Connection._reverse_mapping[ssl]
  172. try:
  173. result = callback(connection, cert, error_number, error_depth, ok)
  174. except Exception as e:
  175. self._problems.append(e)
  176. return 0
  177. else:
  178. if result:
  179. _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
  180. return 1
  181. else:
  182. return 0
  183. self.callback = _ffi.callback(
  184. "int (*)(int, X509_STORE_CTX *)", wrapper)
  185. class _NpnAdvertiseHelper(_CallbackExceptionHelper):
  186. """
  187. Wrap a callback such that it can be used as an NPN advertisement callback.
  188. """
  189. def __init__(self, callback):
  190. _CallbackExceptionHelper.__init__(self)
  191. @wraps(callback)
  192. def wrapper(ssl, out, outlen, arg):
  193. try:
  194. conn = Connection._reverse_mapping[ssl]
  195. protos = callback(conn)
  196. # Join the protocols into a Python bytestring, length-prefixing
  197. # each element.
  198. protostr = b''.join(
  199. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  200. )
  201. # Save our callback arguments on the connection object. This is
  202. # done to make sure that they don't get freed before OpenSSL
  203. # uses them. Then, return them appropriately in the output
  204. # parameters.
  205. conn._npn_advertise_callback_args = [
  206. _ffi.new("unsigned int *", len(protostr)),
  207. _ffi.new("unsigned char[]", protostr),
  208. ]
  209. outlen[0] = conn._npn_advertise_callback_args[0][0]
  210. out[0] = conn._npn_advertise_callback_args[1]
  211. return 0
  212. except Exception as e:
  213. self._problems.append(e)
  214. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  215. self.callback = _ffi.callback(
  216. "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
  217. wrapper
  218. )
  219. class _NpnSelectHelper(_CallbackExceptionHelper):
  220. """
  221. Wrap a callback such that it can be used as an NPN selection callback.
  222. """
  223. def __init__(self, callback):
  224. _CallbackExceptionHelper.__init__(self)
  225. @wraps(callback)
  226. def wrapper(ssl, out, outlen, in_, inlen, arg):
  227. try:
  228. conn = Connection._reverse_mapping[ssl]
  229. # The string passed to us is actually made up of multiple
  230. # length-prefixed bytestrings. We need to split that into a
  231. # list.
  232. instr = _ffi.buffer(in_, inlen)[:]
  233. protolist = []
  234. while instr:
  235. l = indexbytes(instr, 0)
  236. proto = instr[1:l+1]
  237. protolist.append(proto)
  238. instr = instr[l+1:]
  239. # Call the callback
  240. outstr = callback(conn, protolist)
  241. # Save our callback arguments on the connection object. This is
  242. # done to make sure that they don't get freed before OpenSSL
  243. # uses them. Then, return them appropriately in the output
  244. # parameters.
  245. conn._npn_select_callback_args = [
  246. _ffi.new("unsigned char *", len(outstr)),
  247. _ffi.new("unsigned char[]", outstr),
  248. ]
  249. outlen[0] = conn._npn_select_callback_args[0][0]
  250. out[0] = conn._npn_select_callback_args[1]
  251. return 0
  252. except Exception as e:
  253. self._problems.append(e)
  254. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  255. self.callback = _ffi.callback(
  256. "int (*)(SSL *, unsigned char **, unsigned char *, "
  257. "const unsigned char *, unsigned int, void *)",
  258. wrapper
  259. )
  260. class _ALPNSelectHelper(_CallbackExceptionHelper):
  261. """
  262. Wrap a callback such that it can be used as an ALPN selection callback.
  263. """
  264. def __init__(self, callback):
  265. _CallbackExceptionHelper.__init__(self)
  266. @wraps(callback)
  267. def wrapper(ssl, out, outlen, in_, inlen, arg):
  268. try:
  269. conn = Connection._reverse_mapping[ssl]
  270. # The string passed to us is made up of multiple
  271. # length-prefixed bytestrings. We need to split that into a
  272. # list.
  273. instr = _ffi.buffer(in_, inlen)[:]
  274. protolist = []
  275. while instr:
  276. encoded_len = indexbytes(instr, 0)
  277. proto = instr[1:encoded_len + 1]
  278. protolist.append(proto)
  279. instr = instr[encoded_len + 1:]
  280. # Call the callback
  281. outstr = callback(conn, protolist)
  282. if not isinstance(outstr, _binary_type):
  283. raise TypeError("ALPN callback must return a bytestring.")
  284. # Save our callback arguments on the connection object to make
  285. # sure that they don't get freed before OpenSSL can use them.
  286. # Then, return them in the appropriate output parameters.
  287. conn._alpn_select_callback_args = [
  288. _ffi.new("unsigned char *", len(outstr)),
  289. _ffi.new("unsigned char[]", outstr),
  290. ]
  291. outlen[0] = conn._alpn_select_callback_args[0][0]
  292. out[0] = conn._alpn_select_callback_args[1]
  293. return 0
  294. except Exception as e:
  295. self._problems.append(e)
  296. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  297. self.callback = _ffi.callback(
  298. "int (*)(SSL *, unsigned char **, unsigned char *, "
  299. "const unsigned char *, unsigned int, void *)",
  300. wrapper
  301. )
  302. def _asFileDescriptor(obj):
  303. fd = None
  304. if not isinstance(obj, integer_types):
  305. meth = getattr(obj, "fileno", None)
  306. if meth is not None:
  307. obj = meth()
  308. if isinstance(obj, integer_types):
  309. fd = obj
  310. if not isinstance(fd, integer_types):
  311. raise TypeError("argument must be an int, or have a fileno() method.")
  312. elif fd < 0:
  313. raise ValueError(
  314. "file descriptor cannot be a negative integer (%i)" % (fd,))
  315. return fd
  316. def SSLeay_version(type):
  317. """
  318. Return a string describing the version of OpenSSL in use.
  319. :param type: One of the SSLEAY_ constants defined in this module.
  320. """
  321. return _ffi.string(_lib.SSLeay_version(type))
  322. def _requires_npn(func):
  323. """
  324. Wraps any function that requires NPN support in OpenSSL, ensuring that
  325. NotImplementedError is raised if NPN is not present.
  326. """
  327. @wraps(func)
  328. def wrapper(*args, **kwargs):
  329. if not _lib.Cryptography_HAS_NEXTPROTONEG:
  330. raise NotImplementedError("NPN not available.")
  331. return func(*args, **kwargs)
  332. return wrapper
  333. def _requires_alpn(func):
  334. """
  335. Wraps any function that requires ALPN support in OpenSSL, ensuring that
  336. NotImplementedError is raised if ALPN support is not present.
  337. """
  338. @wraps(func)
  339. def wrapper(*args, **kwargs):
  340. if not _lib.Cryptography_HAS_ALPN:
  341. raise NotImplementedError("ALPN not available.")
  342. return func(*args, **kwargs)
  343. return wrapper
  344. class Session(object):
  345. pass
  346. class Context(object):
  347. """
  348. :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting up
  349. new SSL connections.
  350. """
  351. _methods = {
  352. SSLv2_METHOD: "SSLv2_method",
  353. SSLv3_METHOD: "SSLv3_method",
  354. SSLv23_METHOD: "SSLv23_method",
  355. TLSv1_METHOD: "TLSv1_method",
  356. TLSv1_1_METHOD: "TLSv1_1_method",
  357. TLSv1_2_METHOD: "TLSv1_2_method",
  358. }
  359. _methods = dict(
  360. (identifier, getattr(_lib, name))
  361. for (identifier, name) in _methods.items()
  362. if getattr(_lib, name, None) is not None)
  363. def __init__(self, method):
  364. """
  365. :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
  366. TLSv1_METHOD.
  367. """
  368. if not isinstance(method, integer_types):
  369. raise TypeError("method must be an integer")
  370. try:
  371. method_func = self._methods[method]
  372. except KeyError:
  373. raise ValueError("No such protocol")
  374. method_obj = method_func()
  375. if method_obj == _ffi.NULL:
  376. # TODO: This is untested.
  377. _raise_current_error()
  378. context = _lib.SSL_CTX_new(method_obj)
  379. if context == _ffi.NULL:
  380. # TODO: This is untested.
  381. _raise_current_error()
  382. context = _ffi.gc(context, _lib.SSL_CTX_free)
  383. self._context = context
  384. self._passphrase_helper = None
  385. self._passphrase_callback = None
  386. self._passphrase_userdata = None
  387. self._verify_helper = None
  388. self._verify_callback = None
  389. self._info_callback = None
  390. self._tlsext_servername_callback = None
  391. self._app_data = None
  392. self._npn_advertise_helper = None
  393. self._npn_advertise_callback = None
  394. self._npn_select_helper = None
  395. self._npn_select_callback = None
  396. self._alpn_select_helper = None
  397. self._alpn_select_callback = None
  398. # SSL_CTX_set_app_data(self->ctx, self);
  399. # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
  400. # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
  401. # SSL_MODE_AUTO_RETRY);
  402. self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
  403. def load_verify_locations(self, cafile, capath=None):
  404. """
  405. Let SSL know where we can find trusted certificates for the certificate
  406. chain
  407. :param cafile: In which file we can find the certificates (``bytes`` or
  408. ``unicode``).
  409. :param capath: In which directory we can find the certificates
  410. (``bytes`` or ``unicode``).
  411. :return: None
  412. """
  413. if cafile is None:
  414. cafile = _ffi.NULL
  415. else:
  416. cafile = _path_string(cafile)
  417. if capath is None:
  418. capath = _ffi.NULL
  419. else:
  420. capath = _path_string(capath)
  421. load_result = _lib.SSL_CTX_load_verify_locations(self._context, cafile, capath)
  422. if not load_result:
  423. _raise_current_error()
  424. def _wrap_callback(self, callback):
  425. @wraps(callback)
  426. def wrapper(size, verify, userdata):
  427. return callback(size, verify, self._passphrase_userdata)
  428. return _PassphraseHelper(
  429. FILETYPE_PEM, wrapper, more_args=True, truncate=True)
  430. def set_passwd_cb(self, callback, userdata=None):
  431. """
  432. Set the passphrase callback
  433. :param callback: The Python callback to use
  434. :param userdata: (optional) A Python object which will be given as
  435. argument to the callback
  436. :return: None
  437. """
  438. if not callable(callback):
  439. raise TypeError("callback must be callable")
  440. self._passphrase_helper = self._wrap_callback(callback)
  441. self._passphrase_callback = self._passphrase_helper.callback
  442. _lib.SSL_CTX_set_default_passwd_cb(
  443. self._context, self._passphrase_callback)
  444. self._passphrase_userdata = userdata
  445. def set_default_verify_paths(self):
  446. """
  447. Use the platform-specific CA certificate locations
  448. :return: None
  449. """
  450. set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
  451. if not set_result:
  452. # TODO: This is untested.
  453. _raise_current_error()
  454. def use_certificate_chain_file(self, certfile):
  455. """
  456. Load a certificate chain from a file
  457. :param certfile: The name of the certificate chain file (``bytes`` or
  458. ``unicode``).
  459. :return: None
  460. """
  461. certfile = _path_string(certfile)
  462. result = _lib.SSL_CTX_use_certificate_chain_file(self._context, certfile)
  463. if not result:
  464. _raise_current_error()
  465. def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
  466. """
  467. Load a certificate from a file
  468. :param certfile: The name of the certificate file (``bytes`` or
  469. ``unicode``).
  470. :param filetype: (optional) The encoding of the file, default is PEM
  471. :return: None
  472. """
  473. certfile = _path_string(certfile)
  474. if not isinstance(filetype, integer_types):
  475. raise TypeError("filetype must be an integer")
  476. use_result = _lib.SSL_CTX_use_certificate_file(self._context, certfile, filetype)
  477. if not use_result:
  478. _raise_current_error()
  479. def use_certificate(self, cert):
  480. """
  481. Load a certificate from a X509 object
  482. :param cert: The X509 object
  483. :return: None
  484. """
  485. if not isinstance(cert, X509):
  486. raise TypeError("cert must be an X509 instance")
  487. use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
  488. if not use_result:
  489. _raise_current_error()
  490. def add_extra_chain_cert(self, certobj):
  491. """
  492. Add certificate to chain
  493. :param certobj: The X509 certificate object to add to the chain
  494. :return: None
  495. """
  496. if not isinstance(certobj, X509):
  497. raise TypeError("certobj must be an X509 instance")
  498. copy = _lib.X509_dup(certobj._x509)
  499. add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
  500. if not add_result:
  501. # TODO: This is untested.
  502. _lib.X509_free(copy)
  503. _raise_current_error()
  504. def _raise_passphrase_exception(self):
  505. if self._passphrase_helper is None:
  506. _raise_current_error()
  507. exception = self._passphrase_helper.raise_if_problem(Error)
  508. if exception is not None:
  509. raise exception
  510. def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
  511. """
  512. Load a private key from a file
  513. :param keyfile: The name of the key file (``bytes`` or ``unicode``)
  514. :param filetype: (optional) The encoding of the file, default is PEM
  515. :return: None
  516. """
  517. keyfile = _path_string(keyfile)
  518. if filetype is _UNSPECIFIED:
  519. filetype = FILETYPE_PEM
  520. elif not isinstance(filetype, integer_types):
  521. raise TypeError("filetype must be an integer")
  522. use_result = _lib.SSL_CTX_use_PrivateKey_file(
  523. self._context, keyfile, filetype)
  524. if not use_result:
  525. self._raise_passphrase_exception()
  526. def use_privatekey(self, pkey):
  527. """
  528. Load a private key from a PKey object
  529. :param pkey: The PKey object
  530. :return: None
  531. """
  532. if not isinstance(pkey, PKey):
  533. raise TypeError("pkey must be a PKey instance")
  534. use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
  535. if not use_result:
  536. self._raise_passphrase_exception()
  537. def check_privatekey(self):
  538. """
  539. Check that the private key and certificate match up
  540. :return: None (raises an exception if something's wrong)
  541. """
  542. if not _lib.SSL_CTX_check_private_key(self._context):
  543. _raise_current_error()
  544. def load_client_ca(self, cafile):
  545. """
  546. Load the trusted certificates that will be sent to the client (basically
  547. telling the client "These are the guys I trust"). Does not actually
  548. imply any of the certificates are trusted; that must be configured
  549. separately.
  550. :param cafile: The name of the certificates file
  551. :return: None
  552. """
  553. def set_session_id(self, buf):
  554. """
  555. Set the session identifier. This is needed if you want to do session
  556. resumption.
  557. :param buf: A Python object that can be safely converted to a string
  558. :returns: None
  559. """
  560. def set_session_cache_mode(self, mode):
  561. """
  562. Enable/disable session caching and specify the mode used.
  563. :param mode: One or more of the SESS_CACHE_* flags (combine using
  564. bitwise or)
  565. :returns: The previously set caching mode.
  566. """
  567. if not isinstance(mode, integer_types):
  568. raise TypeError("mode must be an integer")
  569. return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
  570. def get_session_cache_mode(self):
  571. """
  572. :returns: The currently used cache mode.
  573. """
  574. return _lib.SSL_CTX_get_session_cache_mode(self._context)
  575. def set_verify(self, mode, callback):
  576. """
  577. Set the verify mode and verify callback
  578. :param mode: The verify mode, this is either VERIFY_NONE or
  579. VERIFY_PEER combined with possible other flags
  580. :param callback: The Python callback to use
  581. :return: None
  582. See SSL_CTX_set_verify(3SSL) for further details.
  583. """
  584. if not isinstance(mode, integer_types):
  585. raise TypeError("mode must be an integer")
  586. if not callable(callback):
  587. raise TypeError("callback must be callable")
  588. self._verify_helper = _VerifyHelper(callback)
  589. self._verify_callback = self._verify_helper.callback
  590. _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
  591. def set_verify_depth(self, depth):
  592. """
  593. Set the verify depth
  594. :param depth: An integer specifying the verify depth
  595. :return: None
  596. """
  597. if not isinstance(depth, integer_types):
  598. raise TypeError("depth must be an integer")
  599. _lib.SSL_CTX_set_verify_depth(self._context, depth)
  600. def get_verify_mode(self):
  601. """
  602. Get the verify mode
  603. :return: The verify mode
  604. """
  605. return _lib.SSL_CTX_get_verify_mode(self._context)
  606. def get_verify_depth(self):
  607. """
  608. Get the verify depth
  609. :return: The verify depth
  610. """
  611. return _lib.SSL_CTX_get_verify_depth(self._context)
  612. def load_tmp_dh(self, dhfile):
  613. """
  614. Load parameters for Ephemeral Diffie-Hellman
  615. :param dhfile: The file to load EDH parameters from (``bytes`` or
  616. ``unicode``).
  617. :return: None
  618. """
  619. dhfile = _path_string(dhfile)
  620. bio = _lib.BIO_new_file(dhfile, b"r")
  621. if bio == _ffi.NULL:
  622. _raise_current_error()
  623. bio = _ffi.gc(bio, _lib.BIO_free)
  624. dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  625. dh = _ffi.gc(dh, _lib.DH_free)
  626. _lib.SSL_CTX_set_tmp_dh(self._context, dh)
  627. def set_tmp_ecdh(self, curve):
  628. """
  629. Select a curve to use for ECDHE key exchange.
  630. :param curve: A curve object to use as returned by either
  631. :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
  632. :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
  633. :return: None
  634. """
  635. _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
  636. def set_cipher_list(self, cipher_list):
  637. """
  638. Change the cipher list
  639. :param cipher_list: A cipher list, see ciphers(1)
  640. :return: None
  641. """
  642. if isinstance(cipher_list, _text_type):
  643. cipher_list = cipher_list.encode("ascii")
  644. if not isinstance(cipher_list, bytes):
  645. raise TypeError("cipher_list must be bytes or unicode")
  646. result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
  647. if not result:
  648. _raise_current_error()
  649. def set_client_ca_list(self, certificate_authorities):
  650. """
  651. Set the list of preferred client certificate signers for this server context.
  652. This list of certificate authorities will be sent to the client when the
  653. server requests a client certificate.
  654. :param certificate_authorities: a sequence of X509Names.
  655. :return: None
  656. """
  657. name_stack = _lib.sk_X509_NAME_new_null()
  658. if name_stack == _ffi.NULL:
  659. # TODO: This is untested.
  660. _raise_current_error()
  661. try:
  662. for ca_name in certificate_authorities:
  663. if not isinstance(ca_name, X509Name):
  664. raise TypeError(
  665. "client CAs must be X509Name objects, not %s objects" % (
  666. type(ca_name).__name__,))
  667. copy = _lib.X509_NAME_dup(ca_name._name)
  668. if copy == _ffi.NULL:
  669. # TODO: This is untested.
  670. _raise_current_error()
  671. push_result = _lib.sk_X509_NAME_push(name_stack, copy)
  672. if not push_result:
  673. _lib.X509_NAME_free(copy)
  674. _raise_current_error()
  675. except:
  676. _lib.sk_X509_NAME_free(name_stack)
  677. raise
  678. _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
  679. def add_client_ca(self, certificate_authority):
  680. """
  681. Add the CA certificate to the list of preferred signers for this context.
  682. The list of certificate authorities will be sent to the client when the
  683. server requests a client certificate.
  684. :param certificate_authority: certificate authority's X509 certificate.
  685. :return: None
  686. """
  687. if not isinstance(certificate_authority, X509):
  688. raise TypeError("certificate_authority must be an X509 instance")
  689. add_result = _lib.SSL_CTX_add_client_CA(
  690. self._context, certificate_authority._x509)
  691. if not add_result:
  692. # TODO: This is untested.
  693. _raise_current_error()
  694. def set_timeout(self, timeout):
  695. """
  696. Set session timeout
  697. :param timeout: The timeout in seconds
  698. :return: The previous session timeout
  699. """
  700. if not isinstance(timeout, integer_types):
  701. raise TypeError("timeout must be an integer")
  702. return _lib.SSL_CTX_set_timeout(self._context, timeout)
  703. def get_timeout(self):
  704. """
  705. Get the session timeout
  706. :return: The session timeout
  707. """
  708. return _lib.SSL_CTX_get_timeout(self._context)
  709. def set_info_callback(self, callback):
  710. """
  711. Set the info callback
  712. :param callback: The Python callback to use
  713. :return: None
  714. """
  715. @wraps(callback)
  716. def wrapper(ssl, where, return_code):
  717. callback(Connection._reverse_mapping[ssl], where, return_code)
  718. self._info_callback = _ffi.callback(
  719. "void (*)(const SSL *, int, int)", wrapper)
  720. _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
  721. def get_app_data(self):
  722. """
  723. Get the application data (supplied via set_app_data())
  724. :return: The application data
  725. """
  726. return self._app_data
  727. def set_app_data(self, data):
  728. """
  729. Set the application data (will be returned from get_app_data())
  730. :param data: Any Python object
  731. :return: None
  732. """
  733. self._app_data = data
  734. def get_cert_store(self):
  735. """
  736. Get the certificate store for the context.
  737. :return: A X509Store object or None if it does not have one.
  738. """
  739. store = _lib.SSL_CTX_get_cert_store(self._context)
  740. if store == _ffi.NULL:
  741. # TODO: This is untested.
  742. return None
  743. pystore = X509Store.__new__(X509Store)
  744. pystore._store = store
  745. return pystore
  746. def set_options(self, options):
  747. """
  748. Add options. Options set before are not cleared!
  749. :param options: The options to add.
  750. :return: The new option bitmask.
  751. """
  752. if not isinstance(options, integer_types):
  753. raise TypeError("options must be an integer")
  754. return _lib.SSL_CTX_set_options(self._context, options)
  755. def set_mode(self, mode):
  756. """
  757. Add modes via bitmask. Modes set before are not cleared!
  758. :param mode: The mode to add.
  759. :return: The new mode bitmask.
  760. """
  761. if not isinstance(mode, integer_types):
  762. raise TypeError("mode must be an integer")
  763. return _lib.SSL_CTX_set_mode(self._context, mode)
  764. def set_tlsext_servername_callback(self, callback):
  765. """
  766. Specify a callback function to be called when clients specify a server name.
  767. :param callback: The callback function. It will be invoked with one
  768. argument, the Connection instance.
  769. """
  770. @wraps(callback)
  771. def wrapper(ssl, alert, arg):
  772. callback(Connection._reverse_mapping[ssl])
  773. return 0
  774. self._tlsext_servername_callback = _ffi.callback(
  775. "int (*)(const SSL *, int *, void *)", wrapper)
  776. _lib.SSL_CTX_set_tlsext_servername_callback(
  777. self._context, self._tlsext_servername_callback)
  778. @_requires_npn
  779. def set_npn_advertise_callback(self, callback):
  780. """
  781. Specify a callback function that will be called when offering `Next
  782. Protocol Negotiation
  783. <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
  784. :param callback: The callback function. It will be invoked with one
  785. argument, the Connection instance. It should return a list of
  786. bytestrings representing the advertised protocols, like
  787. ``[b'http/1.1', b'spdy/2']``.
  788. """
  789. self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
  790. self._npn_advertise_callback = self._npn_advertise_helper.callback
  791. _lib.SSL_CTX_set_next_protos_advertised_cb(
  792. self._context, self._npn_advertise_callback, _ffi.NULL)
  793. @_requires_npn
  794. def set_npn_select_callback(self, callback):
  795. """
  796. Specify a callback function that will be called when a server offers
  797. Next Protocol Negotiation options.
  798. :param callback: The callback function. It will be invoked with two
  799. arguments: the Connection, and a list of offered protocols as
  800. bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
  801. one of those bytestrings, the chosen protocol.
  802. """
  803. self._npn_select_helper = _NpnSelectHelper(callback)
  804. self._npn_select_callback = self._npn_select_helper.callback
  805. _lib.SSL_CTX_set_next_proto_select_cb(
  806. self._context, self._npn_select_callback, _ffi.NULL)
  807. @_requires_alpn
  808. def set_alpn_protos(self, protos):
  809. """
  810. Specify the clients ALPN protocol list.
  811. These protocols are offered to the server during protocol negotiation.
  812. :param protos: A list of the protocols to be offered to the server.
  813. This list should be a Python list of bytestrings representing the
  814. protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
  815. """
  816. # Take the list of protocols and join them together, prefixing them
  817. # with their lengths.
  818. protostr = b''.join(
  819. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  820. )
  821. # Build a C string from the list. We don't need to save this off
  822. # because OpenSSL immediately copies the data out.
  823. input_str = _ffi.new("unsigned char[]", protostr)
  824. input_str_len = _ffi.cast("unsigned", len(protostr))
  825. _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
  826. @_requires_alpn
  827. def set_alpn_select_callback(self, callback):
  828. """
  829. Set the callback to handle ALPN protocol choice.
  830. :param callback: The callback function. It will be invoked with two
  831. arguments: the Connection, and a list of offered protocols as
  832. bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
  833. one of those bytestrings, the chosen protocol.
  834. """
  835. self._alpn_select_helper = _ALPNSelectHelper(callback)
  836. self._alpn_select_callback = self._alpn_select_helper.callback
  837. _lib.SSL_CTX_set_alpn_select_cb(
  838. self._context, self._alpn_select_callback, _ffi.NULL)
  839. ContextType = Context
  840. class Connection(object):
  841. """
  842. """
  843. _reverse_mapping = WeakValueDictionary()
  844. def __init__(self, context, socket=None):
  845. """
  846. Create a new Connection object, using the given OpenSSL.SSL.Context
  847. instance and socket.
  848. :param context: An SSL Context to use for this connection
  849. :param socket: The socket to use for transport layer
  850. """
  851. if not isinstance(context, Context):
  852. raise TypeError("context must be a Context instance")
  853. ssl = _lib.SSL_new(context._context)
  854. self._ssl = _ffi.gc(ssl, _lib.SSL_free)
  855. self._context = context
  856. # References to strings used for Next Protocol Negotiation. OpenSSL's
  857. # header files suggest that these might get copied at some point, but
  858. # doesn't specify when, so we store them here to make sure they don't
  859. # get freed before OpenSSL uses them.
  860. self._npn_advertise_callback_args = None
  861. self._npn_select_callback_args = None
  862. # References to strings used for Application Layer Protocol
  863. # Negotiation. These strings get copied at some point but it's well
  864. # after the callback returns, so we have to hang them somewhere to
  865. # avoid them getting freed.
  866. self._alpn_select_callback_args = None
  867. self._reverse_mapping[self._ssl] = self
  868. if socket is None:
  869. self._socket = None
  870. # Don't set up any gc for these, SSL_free will take care of them.
  871. self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
  872. self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
  873. if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
  874. # TODO: This is untested.
  875. _raise_current_error()
  876. _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
  877. else:
  878. self._into_ssl = None
  879. self._from_ssl = None
  880. self._socket = socket
  881. set_result = _lib.SSL_set_fd(self._ssl, _asFileDescriptor(self._socket))
  882. if not set_result:
  883. # TODO: This is untested.
  884. _raise_current_error()
  885. def __getattr__(self, name):
  886. """
  887. Look up attributes on the wrapped socket object if they are not found on
  888. the Connection object.
  889. """
  890. return getattr(self._socket, name)
  891. def _raise_ssl_error(self, ssl, result):
  892. if self._context._verify_helper is not None:
  893. self._context._verify_helper.raise_if_problem()
  894. if self._context._npn_advertise_helper is not None:
  895. self._context._npn_advertise_helper.raise_if_problem()
  896. if self._context._npn_select_helper is not None:
  897. self._context._npn_select_helper.raise_if_problem()
  898. if self._context._alpn_select_helper is not None:
  899. self._context._alpn_select_helper.raise_if_problem()
  900. error = _lib.SSL_get_error(ssl, result)
  901. if error == _lib.SSL_ERROR_WANT_READ:
  902. raise WantReadError()
  903. elif error == _lib.SSL_ERROR_WANT_WRITE:
  904. raise WantWriteError()
  905. elif error == _lib.SSL_ERROR_ZERO_RETURN:
  906. raise ZeroReturnError()
  907. elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
  908. # TODO: This is untested.
  909. raise WantX509LookupError()
  910. elif error == _lib.SSL_ERROR_SYSCALL:
  911. if _lib.ERR_peek_error() == 0:
  912. if result < 0:
  913. if platform == "win32":
  914. errno = _ffi.getwinerror()[0]
  915. else:
  916. errno = _ffi.errno
  917. raise SysCallError(errno, errorcode.get(errno))
  918. else:
  919. raise SysCallError(-1, "Unexpected EOF")
  920. else:
  921. # TODO: This is untested.
  922. _raise_current_error()
  923. elif error == _lib.SSL_ERROR_NONE:
  924. pass
  925. else:
  926. _raise_current_error()
  927. def get_context(self):
  928. """
  929. Get session context
  930. """
  931. return self._context
  932. def set_context(self, context):
  933. """
  934. Switch this connection to a new session context
  935. :param context: A :py:class:`Context` instance giving the new session
  936. context to use.
  937. """
  938. if not isinstance(context, Context):
  939. raise TypeError("context must be a Context instance")
  940. _lib.SSL_set_SSL_CTX(self._ssl, context._context)
  941. self._context = context
  942. def get_servername(self):
  943. """
  944. Retrieve the servername extension value if provided in the client hello
  945. message, or None if there wasn't one.
  946. :return: A byte string giving the server name or :py:data:`None`.
  947. """
  948. name = _lib.SSL_get_servername(self._ssl, _lib.TLSEXT_NAMETYPE_host_name)
  949. if name == _ffi.NULL:
  950. return None
  951. return _ffi.string(name)
  952. def set_tlsext_host_name(self, name):
  953. """
  954. Set the value of the servername extension to send in the client hello.
  955. :param name: A byte string giving the name.
  956. """
  957. if not isinstance(name, bytes):
  958. raise TypeError("name must be a byte string")
  959. elif b"\0" in name:
  960. raise TypeError("name must not contain NUL byte")
  961. # XXX I guess this can fail sometimes?
  962. _lib.SSL_set_tlsext_host_name(self._ssl, name)
  963. def pending(self):
  964. """
  965. Get the number of bytes that can be safely read from the connection
  966. :return: The number of bytes available in the receive buffer.
  967. """
  968. return _lib.SSL_pending(self._ssl)
  969. def send(self, buf, flags=0):
  970. """
  971. Send data on the connection. NOTE: If you get one of the WantRead,
  972. WantWrite or WantX509Lookup exceptions on this, you have to call the
  973. method again with the SAME buffer.
  974. :param buf: The string, buffer or memoryview to send
  975. :param flags: (optional) Included for compatibility with the socket
  976. API, the value is ignored
  977. :return: The number of bytes written
  978. """
  979. # Backward compatibility
  980. buf = _text_to_bytes_and_warn("buf", buf)
  981. if isinstance(buf, _memoryview):
  982. buf = buf.tobytes()
  983. if isinstance(buf, _buffer):
  984. buf = str(buf)
  985. if not isinstance(buf, bytes):
  986. raise TypeError("data must be a memoryview, buffer or byte string")
  987. result = _lib.SSL_write(self._ssl, buf, len(buf))
  988. self._raise_ssl_error(self._ssl, result)
  989. return result
  990. write = send
  991. def sendall(self, buf, flags=0):
  992. """
  993. Send "all" data on the connection. This calls send() repeatedly until
  994. all data is sent. If an error occurs, it's impossible to tell how much
  995. data has been sent.
  996. :param buf: The string, buffer or memoryview to send
  997. :param flags: (optional) Included for compatibility with the socket
  998. API, the value is ignored
  999. :return: The number of bytes written
  1000. """
  1001. buf = _text_to_bytes_and_warn("buf", buf)
  1002. if isinstance(buf, _memoryview):
  1003. buf = buf.tobytes()
  1004. if isinstance(buf, _buffer):
  1005. buf = str(buf)
  1006. if not isinstance(buf, bytes):
  1007. raise TypeError("buf must be a memoryview, buffer or byte string")
  1008. left_to_send = len(buf)
  1009. total_sent = 0
  1010. data = _ffi.new("char[]", buf)
  1011. while left_to_send:
  1012. result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
  1013. self._raise_ssl_error(self._ssl, result)
  1014. total_sent += result
  1015. left_to_send -= result
  1016. def recv(self, bufsiz, flags=None):
  1017. """
  1018. Receive data on the connection. NOTE: If you get one of the WantRead,
  1019. WantWrite or WantX509Lookup exceptions on this, you have to call the
  1020. method again with the SAME buffer.
  1021. :param bufsiz: The maximum number of bytes to read
  1022. :param flags: (optional) Included for compatibility with the socket
  1023. API, the value is ignored
  1024. :return: The string read from the Connection
  1025. """
  1026. buf = _ffi.new("char[]", bufsiz)
  1027. result = _lib.SSL_read(self._ssl, buf, bufsiz)
  1028. self._raise_ssl_error(self._ssl, result)
  1029. return _ffi.buffer(buf, result)[:]
  1030. read = recv
  1031. def recv_into(self, buffer, nbytes=None, flags=None):
  1032. """
  1033. Receive data on the connection and store the data into a buffer rather
  1034. than creating a new string.
  1035. :param buffer: The buffer to copy into.
  1036. :param nbytes: (optional) The maximum number of bytes to read into the
  1037. buffer. If not present, defaults to the size of the buffer. If
  1038. larger than the size of the buffer, is reduced to the size of the
  1039. buffer.
  1040. :param flags: (optional) Included for compatibility with the socket
  1041. API, the value is ignored.
  1042. :return: The number of bytes read into the buffer.
  1043. """
  1044. if nbytes is None:
  1045. nbytes = len(buffer)
  1046. else:
  1047. nbytes = min(nbytes, len(buffer))
  1048. # We need to create a temporary buffer. This is annoying, it would be
  1049. # better if we could pass memoryviews straight into the SSL_read call,
  1050. # but right now we can't. Revisit this if CFFI gets that ability.
  1051. buf = _ffi.new("char[]", nbytes)
  1052. result = _lib.SSL_read(self._ssl, buf, nbytes)
  1053. self._raise_ssl_error(self._ssl, result)
  1054. # This strange line is all to avoid a memory copy. The buffer protocol
  1055. # should allow us to assign a CFFI buffer to the LHS of this line, but
  1056. # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
  1057. # wrap it in a memoryview, except on Python 2.6 which doesn't have a
  1058. # memoryview type.
  1059. try:
  1060. buffer[:result] = memoryview(_ffi.buffer(buf, result))
  1061. except NameError:
  1062. buffer[:result] = _ffi.buffer(buf, result)
  1063. return result
  1064. def _handle_bio_errors(self, bio, result):
  1065. if _lib.BIO_should_retry(bio):
  1066. if _lib.BIO_should_read(bio):
  1067. raise WantReadError()
  1068. elif _lib.BIO_should_write(bio):
  1069. # TODO: This is untested.
  1070. raise WantWriteError()
  1071. elif _lib.BIO_should_io_special(bio):
  1072. # TODO: This is untested. I think io_special means the socket
  1073. # BIO has a not-yet connected socket.
  1074. raise ValueError("BIO_should_io_special")
  1075. else:
  1076. # TODO: This is untested.
  1077. raise ValueError("unknown bio failure")
  1078. else:
  1079. # TODO: This is untested.
  1080. _raise_current_error()
  1081. def bio_read(self, bufsiz):
  1082. """
  1083. When using non-socket connections this function reads the "dirty" data
  1084. that would have traveled away on the network.
  1085. :param bufsiz: The maximum number of bytes to read
  1086. :return: The string read.
  1087. """
  1088. if self._from_ssl is None:
  1089. raise TypeError("Connection sock was not None")
  1090. if not isinstance(bufsiz, integer_types):
  1091. raise TypeError("bufsiz must be an integer")
  1092. buf = _ffi.new("char[]", bufsiz)
  1093. result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
  1094. if result <= 0:
  1095. self._handle_bio_errors(self._from_ssl, result)
  1096. return _ffi.buffer(buf, result)[:]
  1097. def bio_write(self, buf):
  1098. """
  1099. When using non-socket connections this function sends "dirty" data that
  1100. would have traveled in on the network.
  1101. :param buf: The string to put into the memory BIO.
  1102. :return: The number of bytes written
  1103. """
  1104. buf = _text_to_bytes_and_warn("buf", buf)
  1105. if self._into_ssl is None:
  1106. raise TypeError("Connection sock was not None")
  1107. if not isinstance(buf, bytes):
  1108. raise TypeError("buf must be a byte string")
  1109. result = _lib.BIO_write(self._into_ssl, buf, len(buf))
  1110. if result <= 0:
  1111. self._handle_bio_errors(self._into_ssl, result)
  1112. return result
  1113. def renegotiate(self):
  1114. """
  1115. Renegotiate the session
  1116. :return: True if the renegotiation can be started, false otherwise
  1117. """
  1118. def do_handshake(self):
  1119. """
  1120. Perform an SSL handshake (usually called after renegotiate() or one of
  1121. set_*_state()). This can raise the same exceptions as send and recv.
  1122. :return: None.
  1123. """
  1124. result = _lib.SSL_do_handshake(self._ssl)
  1125. self._raise_ssl_error(self._ssl, result)
  1126. def renegotiate_pending(self):
  1127. """
  1128. Check if there's a renegotiation in progress, it will return false once
  1129. a renegotiation is finished.
  1130. :return: Whether there's a renegotiation in progress
  1131. """
  1132. def total_renegotiations(self):
  1133. """
  1134. Find out the total number of renegotiations.
  1135. :return: The number of renegotiations.
  1136. """
  1137. return _lib.SSL_total_renegotiations(self._ssl)
  1138. def connect(self, addr):
  1139. """
  1140. Connect to remote host and set up client-side SSL
  1141. :param addr: A remote address
  1142. :return: What the socket's connect method returns
  1143. """
  1144. _lib.SSL_set_connect_state(self._ssl)
  1145. return self._socket.connect(addr)
  1146. def connect_ex(self, addr):
  1147. """
  1148. Connect to remote host and set up client-side SSL. Note that if the socket's
  1149. connect_ex method doesn't return 0, SSL won't be initialized.
  1150. :param addr: A remove address
  1151. :return: What the socket's connect_ex method returns
  1152. """
  1153. connect_ex = self._socket.connect_ex
  1154. self.set_connect_state()
  1155. return connect_ex(addr)
  1156. def accept(self):
  1157. """
  1158. Accept incoming connection and set up SSL on it
  1159. :return: A (conn,addr) pair where conn is a Connection and addr is an
  1160. address
  1161. """
  1162. client, addr = self._socket.accept()
  1163. conn = Connection(self._context, client)
  1164. conn.set_accept_state()
  1165. return (conn, addr)
  1166. def bio_shutdown(self):
  1167. """
  1168. When using non-socket connections this function signals end of
  1169. data on the input for this connection.
  1170. :return: None
  1171. """
  1172. if self._from_ssl is None:
  1173. raise TypeError("Connection sock was not None")
  1174. _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
  1175. def shutdown(self):
  1176. """
  1177. Send closure alert
  1178. :return: True if the shutdown completed successfully (i.e. both sides
  1179. have sent closure alerts), false otherwise (i.e. you have to
  1180. wait for a ZeroReturnError on a recv() method call
  1181. """
  1182. result = _lib.SSL_shutdown(self._ssl)
  1183. if result < 0:
  1184. self._raise_ssl_error(self._ssl, result)
  1185. elif result > 0:
  1186. return True
  1187. else:
  1188. return False
  1189. def get_cipher_list(self):
  1190. """
  1191. Get the session cipher list
  1192. :return: A list of cipher strings
  1193. """
  1194. ciphers = []
  1195. for i in count():
  1196. result = _lib.SSL_get_cipher_list(self._ssl, i)
  1197. if result == _ffi.NULL:
  1198. break
  1199. ciphers.append(_native(_ffi.string(result)))
  1200. return ciphers
  1201. def get_client_ca_list(self):
  1202. """
  1203. Get CAs whose certificates are suggested for client authentication.
  1204. :return: If this is a server connection, a list of X509Names representing
  1205. the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
  1206. :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,
  1207. the list of such X509Names sent by the server, or an empty list if that
  1208. has not yet happened.
  1209. """
  1210. ca_names = _lib.SSL_get_client_CA_list(self._ssl)
  1211. if ca_names == _ffi.NULL:
  1212. # TODO: This is untested.
  1213. return []
  1214. result = []
  1215. for i in range(_lib.sk_X509_NAME_num(ca_names)):
  1216. name = _lib.sk_X509_NAME_value(ca_names, i)
  1217. copy = _lib.X509_NAME_dup(name)
  1218. if copy == _ffi.NULL:
  1219. # TODO: This is untested.
  1220. _raise_current_error()
  1221. pyname = X509Name.__new__(X509Name)
  1222. pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
  1223. result.append(pyname)
  1224. return result
  1225. def makefile(self):
  1226. """
  1227. The makefile() method is not implemented, since there is no dup semantics
  1228. for SSL connections
  1229. :raise: NotImplementedError
  1230. """
  1231. raise NotImplementedError("Cannot make file object of OpenSSL.SSL.Connection")
  1232. def get_app_data(self):
  1233. """
  1234. Get application data
  1235. :return: The application data
  1236. """
  1237. return self._app_data
  1238. def set_app_data(self, data):
  1239. """
  1240. Set application data
  1241. :param data - The application data
  1242. :return: None
  1243. """
  1244. self._app_data = data
  1245. def get_shutdown(self):
  1246. """
  1247. Get shutdown state
  1248. :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
  1249. """
  1250. return _lib.SSL_get_shutdown(self._ssl)
  1251. def set_shutdown(self, state):
  1252. """
  1253. Set shutdown state
  1254. :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
  1255. :return: None
  1256. """
  1257. if not isinstance(state, integer_types):
  1258. raise TypeError("state must be an integer")
  1259. _lib.SSL_set_shutdown(self._ssl, state)
  1260. def state_string(self):
  1261. """
  1262. Get a verbose state description
  1263. :return: A string representing the state
  1264. """
  1265. def server_random(self):
  1266. """
  1267. Get a copy of the server hello nonce.
  1268. :return: A string representing the state
  1269. """
  1270. if self._ssl.session == _ffi.NULL:
  1271. return None
  1272. return _ffi.buffer(
  1273. self._ssl.s3.server_random,
  1274. _lib.SSL3_RANDOM_SIZE)[:]
  1275. def client_random(self):
  1276. """
  1277. Get a copy of the client hello nonce.
  1278. :return: A string representing the state
  1279. """
  1280. if self._ssl.session == _ffi.NULL:
  1281. return None
  1282. return _ffi.buffer(
  1283. self._ssl.s3.client_random,
  1284. _lib.SSL3_RANDOM_SIZE)[:]
  1285. def master_key(self):
  1286. """
  1287. Get a copy of the master key.
  1288. :return: A string representing the state
  1289. """
  1290. if self._ssl.session == _ffi.NULL:
  1291. return None
  1292. return _ffi.buffer(
  1293. self._ssl.session.master_key,
  1294. self._ssl.session.master_key_length)[:]
  1295. def sock_shutdown(self, *args, **kwargs):
  1296. """
  1297. See shutdown(2)
  1298. :return: What the socket's shutdown() method returns
  1299. """
  1300. return self._socket.shutdown(*args, **kwargs)
  1301. def get_peer_certificate(self):
  1302. """
  1303. Retrieve the other side's certificate (if any)
  1304. :return: The peer's certificate
  1305. """
  1306. cert = _lib.SSL_get_peer_certificate(self._ssl)
  1307. if cert != _ffi.NULL:
  1308. pycert = X509.__new__(X509)
  1309. pycert._x509 = _ffi.gc(cert, _lib.X509_free)
  1310. return pycert
  1311. return None
  1312. def get_peer_cert_chain(self):
  1313. """
  1314. Retrieve the other side's certificate (if any)
  1315. :return: A list of X509 instances giving the peer's certificate chain,
  1316. or None if it does not have one.
  1317. """
  1318. cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
  1319. if cert_stack == _ffi.NULL:
  1320. return None
  1321. result = []
  1322. for i in range(_lib.sk_X509_num(cert_stack)):
  1323. # TODO could incref instead of dup here
  1324. cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
  1325. pycert = X509.__new__(X509)
  1326. pycert._x509 = _ffi.gc(cert, _lib.X509_free)
  1327. result.append(pycert)
  1328. return result
  1329. def want_read(self):
  1330. """
  1331. Checks if more data has to be read from the transport layer to complete an
  1332. operation.
  1333. :return: True iff more data has to be read
  1334. """
  1335. return _lib.SSL_want_read(self._ssl)
  1336. def want_write(self):
  1337. """
  1338. Checks if there is data to write to the transport layer to complete an
  1339. operation.
  1340. :return: True iff there is data to write
  1341. """
  1342. return _lib.SSL_want_write(self._ssl)
  1343. def set_accept_state(self):
  1344. """
  1345. Set the connection to work in server mode. The handshake will be handled
  1346. automatically by read/write.
  1347. :return: None
  1348. """
  1349. _lib.SSL_set_accept_state(self._ssl)
  1350. def set_connect_state(self):
  1351. """
  1352. Set the connection to work in client mode. The handshake will be handled
  1353. automatically by read/write.
  1354. :return: None
  1355. """
  1356. _lib.SSL_set_connect_state(self._ssl)
  1357. def get_session(self):
  1358. """
  1359. Returns the Session currently used.
  1360. @return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if
  1361. no session exists.
  1362. """
  1363. session = _lib.SSL_get1_session(self._ssl)
  1364. if session == _ffi.NULL:
  1365. return None
  1366. pysession = Session.__new__(Session)
  1367. pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
  1368. return pysession
  1369. def set_session(self, session):
  1370. """
  1371. Set the session to be used when the TLS/SSL connection is established.
  1372. :param session: A Session instance representing the session to use.
  1373. :returns: None
  1374. """
  1375. if not isinstance(session, Session):
  1376. raise TypeError("session must be a Session instance")
  1377. result = _lib.SSL_set_session(self._ssl, session._session)
  1378. if not result:
  1379. _raise_current_error()
  1380. def _get_finished_message(self, function):
  1381. """
  1382. Helper to implement :py:meth:`get_finished` and
  1383. :py:meth:`get_peer_finished`.
  1384. :param function: Either :py:data:`SSL_get_finished`: or
  1385. :py:data:`SSL_get_peer_finished`.
  1386. :return: :py:data:`None` if the desired message has not yet been
  1387. received, otherwise the contents of the message.
  1388. :rtype: :py:class:`bytes` or :py:class:`NoneType`
  1389. """
  1390. # The OpenSSL documentation says nothing about what might happen if the
  1391. # count argument given is zero. Specifically, it doesn't say whether
  1392. # the output buffer may be NULL in that case or not. Inspection of the
  1393. # implementation reveals that it calls memcpy() unconditionally.
  1394. # Section 7.1.4, paragraph 1 of the C standard suggests that
  1395. # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
  1396. # alone desirable) behavior (though it probably does on just about
  1397. # every implementation...)
  1398. #
  1399. # Allocate a tiny buffer to pass in (instead of just passing NULL as
  1400. # one might expect) for the initial call so as to be safe against this
  1401. # potentially undefined behavior.
  1402. empty = _ffi.new("char[]", 0)
  1403. size = function(self._ssl, empty, 0)
  1404. if size == 0:
  1405. # No Finished message so far.
  1406. return None
  1407. buf = _ffi.new("char[]", size)
  1408. function(self._ssl, buf, size)
  1409. return _ffi.buffer(buf, size)[:]
  1410. def get_finished(self):
  1411. """
  1412. Obtain the latest `handshake finished` message sent to the peer.
  1413. :return: The contents of the message or :py:obj:`None` if the TLS
  1414. handshake has not yet completed.
  1415. :rtype: :py:class:`bytes` or :py:class:`NoneType`
  1416. """
  1417. return self._get_finished_message(_lib.SSL_get_finished)
  1418. def get_peer_finished(self):
  1419. """
  1420. Obtain the latest `handshake finished` message received from the peer.
  1421. :return: The contents of the message or :py:obj:`None` if the TLS
  1422. handshake has not yet completed.
  1423. :rtype: :py:class:`bytes` or :py:class:`NoneType`
  1424. """
  1425. return self._get_finished_message(_lib.SSL_get_peer_finished)
  1426. def get_cipher_name(self):
  1427. """
  1428. Obtain the name of the currently used cipher.
  1429. :returns: The name of the currently used cipher or :py:obj:`None`
  1430. if no connection has been established.
  1431. :rtype: :py:class:`unicode` or :py:class:`NoneType`
  1432. """
  1433. cipher = _lib.SSL_get_current_cipher(self._ssl)
  1434. if cipher == _ffi.NULL:
  1435. return None
  1436. else:
  1437. name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
  1438. return name.decode("utf-8")
  1439. def get_cipher_bits(self):
  1440. """
  1441. Obtain the number of secret bits of the currently used cipher.
  1442. :returns: The number of secret bits of the currently used cipher
  1443. or :py:obj:`None` if no connection has been established.
  1444. :rtype: :py:class:`int` or :py:class:`NoneType`
  1445. """
  1446. cipher = _lib.SSL_get_current_cipher(self._ssl)
  1447. if cipher == _ffi.NULL:
  1448. return None
  1449. else:
  1450. return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
  1451. def get_cipher_version(self):
  1452. """
  1453. Obtain the protocol version of the currently used cipher.
  1454. :returns: The protocol name of the currently used cipher
  1455. or :py:obj:`None` if no connection has been established.
  1456. :rtype: :py:class:`unicode` or :py:class:`NoneType`
  1457. """
  1458. cipher = _lib.SSL_get_current_cipher(self._ssl)
  1459. if cipher == _ffi.NULL:
  1460. return None
  1461. else:
  1462. version =_ffi.string(_lib.SSL_CIPHER_get_version(cipher))
  1463. return version.decode("utf-8")
  1464. @_requires_npn
  1465. def get_next_proto_negotiated(self):
  1466. """
  1467. Get the protocol that was negotiated by NPN.
  1468. """
  1469. data = _ffi.new("unsigned char **")
  1470. data_len = _ffi.new("unsigned int *")
  1471. _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
  1472. return _ffi.buffer(data[0], data_len[0])[:]
  1473. @_requires_alpn
  1474. def set_alpn_protos(self, protos):
  1475. """
  1476. Specify the client's ALPN protocol list.
  1477. These protocols are offered to the server during protocol negotiation.
  1478. :param protos: A list of the protocols to be offered to the server.
  1479. This list should be a Python list of bytestrings representing the
  1480. protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
  1481. """
  1482. # Take the list of protocols and join them together, prefixing them
  1483. # with their lengths.
  1484. protostr = b''.join(
  1485. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  1486. )
  1487. # Build a C string from the list. We don't need to save this off
  1488. # because OpenSSL immediately copies the data out.
  1489. input_str = _ffi.new("unsigned char[]", protostr)
  1490. input_str_len = _ffi.cast("unsigned", len(protostr))
  1491. _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
  1492. def get_alpn_proto_negotiated(self):
  1493. """
  1494. Get the protocol that was negotiated by ALPN.
  1495. """
  1496. if not _lib.Cryptography_HAS_ALPN:
  1497. raise NotImplementedError("ALPN not available")
  1498. data = _ffi.new("unsigned char **")
  1499. data_len = _ffi.new("unsigned int *")
  1500. _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
  1501. if not data_len:
  1502. return b''
  1503. return _ffi.buffer(data[0], data_len[0])[:]
  1504. ConnectionType = Connection
  1505. # This is similar to the initialization calls at the end of OpenSSL/crypto.py
  1506. # but is exercised mostly by the Context initializer.
  1507. _lib.SSL_library_init()