SSL.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  1. import os
  2. import socket
  3. import warnings
  4. from sys import platform
  5. from functools import wraps, partial
  6. from itertools import count, chain
  7. from weakref import WeakValueDictionary
  8. from errno import errorcode
  9. from six import (
  10. binary_type as _binary_type, integer_types as integer_types, int2byte,
  11. indexbytes)
  12. from OpenSSL._util import (
  13. UNSPECIFIED as _UNSPECIFIED,
  14. exception_from_error_queue as _exception_from_error_queue,
  15. ffi as _ffi,
  16. from_buffer as _from_buffer,
  17. lib as _lib,
  18. make_assert as _make_assert,
  19. native as _native,
  20. path_string as _path_string,
  21. text_to_bytes_and_warn as _text_to_bytes_and_warn,
  22. no_zero_allocator as _no_zero_allocator,
  23. )
  24. from OpenSSL.crypto import (
  25. FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
  26. __all__ = [
  27. 'OPENSSL_VERSION_NUMBER',
  28. 'SSLEAY_VERSION',
  29. 'SSLEAY_CFLAGS',
  30. 'SSLEAY_PLATFORM',
  31. 'SSLEAY_DIR',
  32. 'SSLEAY_BUILT_ON',
  33. 'SENT_SHUTDOWN',
  34. 'RECEIVED_SHUTDOWN',
  35. 'SSLv2_METHOD',
  36. 'SSLv3_METHOD',
  37. 'SSLv23_METHOD',
  38. 'TLSv1_METHOD',
  39. 'TLSv1_1_METHOD',
  40. 'TLSv1_2_METHOD',
  41. 'OP_NO_SSLv2',
  42. 'OP_NO_SSLv3',
  43. 'OP_NO_TLSv1',
  44. 'OP_NO_TLSv1_1',
  45. 'OP_NO_TLSv1_2',
  46. 'OP_NO_TLSv1_3',
  47. 'MODE_RELEASE_BUFFERS',
  48. 'OP_SINGLE_DH_USE',
  49. 'OP_SINGLE_ECDH_USE',
  50. 'OP_EPHEMERAL_RSA',
  51. 'OP_MICROSOFT_SESS_ID_BUG',
  52. 'OP_NETSCAPE_CHALLENGE_BUG',
  53. 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
  54. 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
  55. 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
  56. 'OP_MSIE_SSLV2_RSA_PADDING',
  57. 'OP_SSLEAY_080_CLIENT_DH_BUG',
  58. 'OP_TLS_D5_BUG',
  59. 'OP_TLS_BLOCK_PADDING_BUG',
  60. 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
  61. 'OP_CIPHER_SERVER_PREFERENCE',
  62. 'OP_TLS_ROLLBACK_BUG',
  63. 'OP_PKCS1_CHECK_1',
  64. 'OP_PKCS1_CHECK_2',
  65. 'OP_NETSCAPE_CA_DN_BUG',
  66. 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
  67. 'OP_NO_COMPRESSION',
  68. 'OP_NO_QUERY_MTU',
  69. 'OP_COOKIE_EXCHANGE',
  70. 'OP_NO_TICKET',
  71. 'OP_ALL',
  72. 'VERIFY_PEER',
  73. 'VERIFY_FAIL_IF_NO_PEER_CERT',
  74. 'VERIFY_CLIENT_ONCE',
  75. 'VERIFY_NONE',
  76. 'SESS_CACHE_OFF',
  77. 'SESS_CACHE_CLIENT',
  78. 'SESS_CACHE_SERVER',
  79. 'SESS_CACHE_BOTH',
  80. 'SESS_CACHE_NO_AUTO_CLEAR',
  81. 'SESS_CACHE_NO_INTERNAL_LOOKUP',
  82. 'SESS_CACHE_NO_INTERNAL_STORE',
  83. 'SESS_CACHE_NO_INTERNAL',
  84. 'SSL_ST_CONNECT',
  85. 'SSL_ST_ACCEPT',
  86. 'SSL_ST_MASK',
  87. 'SSL_CB_LOOP',
  88. 'SSL_CB_EXIT',
  89. 'SSL_CB_READ',
  90. 'SSL_CB_WRITE',
  91. 'SSL_CB_ALERT',
  92. 'SSL_CB_READ_ALERT',
  93. 'SSL_CB_WRITE_ALERT',
  94. 'SSL_CB_ACCEPT_LOOP',
  95. 'SSL_CB_ACCEPT_EXIT',
  96. 'SSL_CB_CONNECT_LOOP',
  97. 'SSL_CB_CONNECT_EXIT',
  98. 'SSL_CB_HANDSHAKE_START',
  99. 'SSL_CB_HANDSHAKE_DONE',
  100. 'Error',
  101. 'WantReadError',
  102. 'WantWriteError',
  103. 'WantX509LookupError',
  104. 'ZeroReturnError',
  105. 'SysCallError',
  106. 'SSLeay_version',
  107. 'Session',
  108. 'Context',
  109. 'Connection'
  110. ]
  111. try:
  112. _buffer = buffer
  113. except NameError:
  114. class _buffer(object):
  115. pass
  116. OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
  117. SSLEAY_VERSION = _lib.SSLEAY_VERSION
  118. SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
  119. SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
  120. SSLEAY_DIR = _lib.SSLEAY_DIR
  121. SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
  122. SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
  123. RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
  124. SSLv2_METHOD = 1
  125. SSLv3_METHOD = 2
  126. SSLv23_METHOD = 3
  127. TLSv1_METHOD = 4
  128. TLSv1_1_METHOD = 5
  129. TLSv1_2_METHOD = 6
  130. OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
  131. OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
  132. OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
  133. OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
  134. OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
  135. try:
  136. OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
  137. except AttributeError:
  138. pass
  139. MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
  140. OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
  141. OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
  142. OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
  143. OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
  144. OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
  145. OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
  146. _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
  147. )
  148. OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
  149. OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
  150. OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
  151. OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
  152. OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
  153. OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
  154. OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  155. OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
  156. OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
  157. OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
  158. OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
  159. OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
  160. OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
  161. _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
  162. )
  163. OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
  164. OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
  165. OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
  166. OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
  167. OP_ALL = _lib.SSL_OP_ALL
  168. VERIFY_PEER = _lib.SSL_VERIFY_PEER
  169. VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  170. VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
  171. VERIFY_NONE = _lib.SSL_VERIFY_NONE
  172. SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
  173. SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
  174. SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
  175. SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
  176. SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
  177. SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
  178. SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
  179. SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
  180. SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
  181. SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
  182. SSL_ST_MASK = _lib.SSL_ST_MASK
  183. if _lib.Cryptography_HAS_SSL_ST:
  184. SSL_ST_INIT = _lib.SSL_ST_INIT
  185. SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
  186. SSL_ST_OK = _lib.SSL_ST_OK
  187. SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
  188. __all__.extend([
  189. 'SSL_ST_INIT',
  190. 'SSL_ST_BEFORE',
  191. 'SSL_ST_OK',
  192. 'SSL_ST_RENEGOTIATE',
  193. ])
  194. SSL_CB_LOOP = _lib.SSL_CB_LOOP
  195. SSL_CB_EXIT = _lib.SSL_CB_EXIT
  196. SSL_CB_READ = _lib.SSL_CB_READ
  197. SSL_CB_WRITE = _lib.SSL_CB_WRITE
  198. SSL_CB_ALERT = _lib.SSL_CB_ALERT
  199. SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
  200. SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
  201. SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
  202. SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
  203. SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
  204. SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
  205. SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
  206. SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
  207. # Taken from https://golang.org/src/crypto/x509/root_linux.go
  208. _CERTIFICATE_FILE_LOCATIONS = [
  209. "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
  210. "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
  211. "/etc/ssl/ca-bundle.pem", # OpenSUSE
  212. "/etc/pki/tls/cacert.pem", # OpenELEC
  213. "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
  214. ]
  215. _CERTIFICATE_PATH_LOCATIONS = [
  216. "/etc/ssl/certs", # SLES10/SLES11
  217. ]
  218. # These values are compared to output from cffi's ffi.string so they must be
  219. # byte strings.
  220. _CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
  221. _CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
  222. class Error(Exception):
  223. """
  224. An error occurred in an `OpenSSL.SSL` API.
  225. """
  226. _raise_current_error = partial(_exception_from_error_queue, Error)
  227. _openssl_assert = _make_assert(Error)
  228. class WantReadError(Error):
  229. pass
  230. class WantWriteError(Error):
  231. pass
  232. class WantX509LookupError(Error):
  233. pass
  234. class ZeroReturnError(Error):
  235. pass
  236. class SysCallError(Error):
  237. pass
  238. class _CallbackExceptionHelper(object):
  239. """
  240. A base class for wrapper classes that allow for intelligent exception
  241. handling in OpenSSL callbacks.
  242. :ivar list _problems: Any exceptions that occurred while executing in a
  243. context where they could not be raised in the normal way. Typically
  244. this is because OpenSSL has called into some Python code and requires a
  245. return value. The exceptions are saved to be raised later when it is
  246. possible to do so.
  247. """
  248. def __init__(self):
  249. self._problems = []
  250. def raise_if_problem(self):
  251. """
  252. Raise an exception from the OpenSSL error queue or that was previously
  253. captured whe running a callback.
  254. """
  255. if self._problems:
  256. try:
  257. _raise_current_error()
  258. except Error:
  259. pass
  260. raise self._problems.pop(0)
  261. class _VerifyHelper(_CallbackExceptionHelper):
  262. """
  263. Wrap a callback such that it can be used as a certificate verification
  264. callback.
  265. """
  266. def __init__(self, callback):
  267. _CallbackExceptionHelper.__init__(self)
  268. @wraps(callback)
  269. def wrapper(ok, store_ctx):
  270. x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
  271. _lib.X509_up_ref(x509)
  272. cert = X509._from_raw_x509_ptr(x509)
  273. error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
  274. error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
  275. index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
  276. ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
  277. connection = Connection._reverse_mapping[ssl]
  278. try:
  279. result = callback(
  280. connection, cert, error_number, error_depth, ok
  281. )
  282. except Exception as e:
  283. self._problems.append(e)
  284. return 0
  285. else:
  286. if result:
  287. _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
  288. return 1
  289. else:
  290. return 0
  291. self.callback = _ffi.callback(
  292. "int (*)(int, X509_STORE_CTX *)", wrapper)
  293. class _NpnAdvertiseHelper(_CallbackExceptionHelper):
  294. """
  295. Wrap a callback such that it can be used as an NPN advertisement callback.
  296. """
  297. def __init__(self, callback):
  298. _CallbackExceptionHelper.__init__(self)
  299. @wraps(callback)
  300. def wrapper(ssl, out, outlen, arg):
  301. try:
  302. conn = Connection._reverse_mapping[ssl]
  303. protos = callback(conn)
  304. # Join the protocols into a Python bytestring, length-prefixing
  305. # each element.
  306. protostr = b''.join(
  307. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  308. )
  309. # Save our callback arguments on the connection object. This is
  310. # done to make sure that they don't get freed before OpenSSL
  311. # uses them. Then, return them appropriately in the output
  312. # parameters.
  313. conn._npn_advertise_callback_args = [
  314. _ffi.new("unsigned int *", len(protostr)),
  315. _ffi.new("unsigned char[]", protostr),
  316. ]
  317. outlen[0] = conn._npn_advertise_callback_args[0][0]
  318. out[0] = conn._npn_advertise_callback_args[1]
  319. return 0
  320. except Exception as e:
  321. self._problems.append(e)
  322. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  323. self.callback = _ffi.callback(
  324. "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
  325. wrapper
  326. )
  327. class _NpnSelectHelper(_CallbackExceptionHelper):
  328. """
  329. Wrap a callback such that it can be used as an NPN selection callback.
  330. """
  331. def __init__(self, callback):
  332. _CallbackExceptionHelper.__init__(self)
  333. @wraps(callback)
  334. def wrapper(ssl, out, outlen, in_, inlen, arg):
  335. try:
  336. conn = Connection._reverse_mapping[ssl]
  337. # The string passed to us is actually made up of multiple
  338. # length-prefixed bytestrings. We need to split that into a
  339. # list.
  340. instr = _ffi.buffer(in_, inlen)[:]
  341. protolist = []
  342. while instr:
  343. length = indexbytes(instr, 0)
  344. proto = instr[1:length + 1]
  345. protolist.append(proto)
  346. instr = instr[length + 1:]
  347. # Call the callback
  348. outstr = callback(conn, protolist)
  349. # Save our callback arguments on the connection object. This is
  350. # done to make sure that they don't get freed before OpenSSL
  351. # uses them. Then, return them appropriately in the output
  352. # parameters.
  353. conn._npn_select_callback_args = [
  354. _ffi.new("unsigned char *", len(outstr)),
  355. _ffi.new("unsigned char[]", outstr),
  356. ]
  357. outlen[0] = conn._npn_select_callback_args[0][0]
  358. out[0] = conn._npn_select_callback_args[1]
  359. return 0
  360. except Exception as e:
  361. self._problems.append(e)
  362. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  363. self.callback = _ffi.callback(
  364. ("int (*)(SSL *, unsigned char **, unsigned char *, "
  365. "const unsigned char *, unsigned int, void *)"),
  366. wrapper
  367. )
  368. NO_OVERLAPPING_PROTOCOLS = object()
  369. class _ALPNSelectHelper(_CallbackExceptionHelper):
  370. """
  371. Wrap a callback such that it can be used as an ALPN selection callback.
  372. """
  373. def __init__(self, callback):
  374. _CallbackExceptionHelper.__init__(self)
  375. @wraps(callback)
  376. def wrapper(ssl, out, outlen, in_, inlen, arg):
  377. try:
  378. conn = Connection._reverse_mapping[ssl]
  379. # The string passed to us is made up of multiple
  380. # length-prefixed bytestrings. We need to split that into a
  381. # list.
  382. instr = _ffi.buffer(in_, inlen)[:]
  383. protolist = []
  384. while instr:
  385. encoded_len = indexbytes(instr, 0)
  386. proto = instr[1:encoded_len + 1]
  387. protolist.append(proto)
  388. instr = instr[encoded_len + 1:]
  389. # Call the callback
  390. outbytes = callback(conn, protolist)
  391. any_accepted = True
  392. if outbytes is NO_OVERLAPPING_PROTOCOLS:
  393. outbytes = b''
  394. any_accepted = False
  395. elif not isinstance(outbytes, _binary_type):
  396. raise TypeError(
  397. "ALPN callback must return a bytestring or the "
  398. "special NO_OVERLAPPING_PROTOCOLS sentinel value."
  399. )
  400. # Save our callback arguments on the connection object to make
  401. # sure that they don't get freed before OpenSSL can use them.
  402. # Then, return them in the appropriate output parameters.
  403. conn._alpn_select_callback_args = [
  404. _ffi.new("unsigned char *", len(outbytes)),
  405. _ffi.new("unsigned char[]", outbytes),
  406. ]
  407. outlen[0] = conn._alpn_select_callback_args[0][0]
  408. out[0] = conn._alpn_select_callback_args[1]
  409. if not any_accepted:
  410. return _lib.SSL_TLSEXT_ERR_NOACK
  411. return _lib.SSL_TLSEXT_ERR_OK
  412. except Exception as e:
  413. self._problems.append(e)
  414. return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
  415. self.callback = _ffi.callback(
  416. ("int (*)(SSL *, unsigned char **, unsigned char *, "
  417. "const unsigned char *, unsigned int, void *)"),
  418. wrapper
  419. )
  420. class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
  421. """
  422. Wrap a callback such that it can be used as an OCSP callback for the server
  423. side.
  424. Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
  425. ways. For servers, that callback is expected to retrieve some OCSP data and
  426. hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
  427. SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
  428. is expected to check the OCSP data, and returns a negative value on error,
  429. 0 if the response is not acceptable, or positive if it is. These are
  430. mutually exclusive return code behaviours, and they mean that we need two
  431. helpers so that we always return an appropriate error code if the user's
  432. code throws an exception.
  433. Given that we have to have two helpers anyway, these helpers are a bit more
  434. helpery than most: specifically, they hide a few more of the OpenSSL
  435. functions so that the user has an easier time writing these callbacks.
  436. This helper implements the server side.
  437. """
  438. def __init__(self, callback):
  439. _CallbackExceptionHelper.__init__(self)
  440. @wraps(callback)
  441. def wrapper(ssl, cdata):
  442. try:
  443. conn = Connection._reverse_mapping[ssl]
  444. # Extract the data if any was provided.
  445. if cdata != _ffi.NULL:
  446. data = _ffi.from_handle(cdata)
  447. else:
  448. data = None
  449. # Call the callback.
  450. ocsp_data = callback(conn, data)
  451. if not isinstance(ocsp_data, _binary_type):
  452. raise TypeError("OCSP callback must return a bytestring.")
  453. # If the OCSP data was provided, we will pass it to OpenSSL.
  454. # However, we have an early exit here: if no OCSP data was
  455. # provided we will just exit out and tell OpenSSL that there
  456. # is nothing to do.
  457. if not ocsp_data:
  458. return 3 # SSL_TLSEXT_ERR_NOACK
  459. # OpenSSL takes ownership of this data and expects it to have
  460. # been allocated by OPENSSL_malloc.
  461. ocsp_data_length = len(ocsp_data)
  462. data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
  463. _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
  464. _lib.SSL_set_tlsext_status_ocsp_resp(
  465. ssl, data_ptr, ocsp_data_length
  466. )
  467. return 0
  468. except Exception as e:
  469. self._problems.append(e)
  470. return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
  471. self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
  472. class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
  473. """
  474. Wrap a callback such that it can be used as an OCSP callback for the client
  475. side.
  476. Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
  477. ways. For servers, that callback is expected to retrieve some OCSP data and
  478. hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
  479. SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
  480. is expected to check the OCSP data, and returns a negative value on error,
  481. 0 if the response is not acceptable, or positive if it is. These are
  482. mutually exclusive return code behaviours, and they mean that we need two
  483. helpers so that we always return an appropriate error code if the user's
  484. code throws an exception.
  485. Given that we have to have two helpers anyway, these helpers are a bit more
  486. helpery than most: specifically, they hide a few more of the OpenSSL
  487. functions so that the user has an easier time writing these callbacks.
  488. This helper implements the client side.
  489. """
  490. def __init__(self, callback):
  491. _CallbackExceptionHelper.__init__(self)
  492. @wraps(callback)
  493. def wrapper(ssl, cdata):
  494. try:
  495. conn = Connection._reverse_mapping[ssl]
  496. # Extract the data if any was provided.
  497. if cdata != _ffi.NULL:
  498. data = _ffi.from_handle(cdata)
  499. else:
  500. data = None
  501. # Get the OCSP data.
  502. ocsp_ptr = _ffi.new("unsigned char **")
  503. ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
  504. if ocsp_len < 0:
  505. # No OCSP data.
  506. ocsp_data = b''
  507. else:
  508. # Copy the OCSP data, then pass it to the callback.
  509. ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
  510. valid = callback(conn, ocsp_data, data)
  511. # Return 1 on success or 0 on error.
  512. return int(bool(valid))
  513. except Exception as e:
  514. self._problems.append(e)
  515. # Return negative value if an exception is hit.
  516. return -1
  517. self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
  518. def _asFileDescriptor(obj):
  519. fd = None
  520. if not isinstance(obj, integer_types):
  521. meth = getattr(obj, "fileno", None)
  522. if meth is not None:
  523. obj = meth()
  524. if isinstance(obj, integer_types):
  525. fd = obj
  526. if not isinstance(fd, integer_types):
  527. raise TypeError("argument must be an int, or have a fileno() method.")
  528. elif fd < 0:
  529. raise ValueError(
  530. "file descriptor cannot be a negative integer (%i)" % (fd,))
  531. return fd
  532. def SSLeay_version(type):
  533. """
  534. Return a string describing the version of OpenSSL in use.
  535. :param type: One of the :const:`SSLEAY_` constants defined in this module.
  536. """
  537. return _ffi.string(_lib.SSLeay_version(type))
  538. def _warn_npn():
  539. warnings.warn("NPN is deprecated. Protocols should switch to using ALPN.",
  540. DeprecationWarning, stacklevel=3)
  541. def _make_requires(flag, error):
  542. """
  543. Builds a decorator that ensures that functions that rely on OpenSSL
  544. functions that are not present in this build raise NotImplementedError,
  545. rather than AttributeError coming out of cryptography.
  546. :param flag: A cryptography flag that guards the functions, e.g.
  547. ``Cryptography_HAS_NEXTPROTONEG``.
  548. :param error: The string to be used in the exception if the flag is false.
  549. """
  550. def _requires_decorator(func):
  551. if not flag:
  552. @wraps(func)
  553. def explode(*args, **kwargs):
  554. raise NotImplementedError(error)
  555. return explode
  556. else:
  557. return func
  558. return _requires_decorator
  559. _requires_npn = _make_requires(
  560. _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
  561. )
  562. _requires_alpn = _make_requires(
  563. _lib.Cryptography_HAS_ALPN, "ALPN not available"
  564. )
  565. class Session(object):
  566. """
  567. A class representing an SSL session. A session defines certain connection
  568. parameters which may be re-used to speed up the setup of subsequent
  569. connections.
  570. .. versionadded:: 0.14
  571. """
  572. pass
  573. class Context(object):
  574. """
  575. :class:`OpenSSL.SSL.Context` instances define the parameters for setting
  576. up new SSL connections.
  577. :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
  578. TLSv1_METHOD.
  579. """
  580. _methods = {
  581. SSLv2_METHOD: "SSLv2_method",
  582. SSLv3_METHOD: "SSLv3_method",
  583. SSLv23_METHOD: "SSLv23_method",
  584. TLSv1_METHOD: "TLSv1_method",
  585. TLSv1_1_METHOD: "TLSv1_1_method",
  586. TLSv1_2_METHOD: "TLSv1_2_method",
  587. }
  588. _methods = dict(
  589. (identifier, getattr(_lib, name))
  590. for (identifier, name) in _methods.items()
  591. if getattr(_lib, name, None) is not None)
  592. def __init__(self, method):
  593. if not isinstance(method, integer_types):
  594. raise TypeError("method must be an integer")
  595. try:
  596. method_func = self._methods[method]
  597. except KeyError:
  598. raise ValueError("No such protocol")
  599. method_obj = method_func()
  600. _openssl_assert(method_obj != _ffi.NULL)
  601. context = _lib.SSL_CTX_new(method_obj)
  602. _openssl_assert(context != _ffi.NULL)
  603. context = _ffi.gc(context, _lib.SSL_CTX_free)
  604. # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
  605. # will be auto-selected. This function was added in 1.0.2 and made a
  606. # noop in 1.1.0+ (where it is set automatically).
  607. try:
  608. res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
  609. _openssl_assert(res == 1)
  610. except AttributeError:
  611. pass
  612. self._context = context
  613. self._passphrase_helper = None
  614. self._passphrase_callback = None
  615. self._passphrase_userdata = None
  616. self._verify_helper = None
  617. self._verify_callback = None
  618. self._info_callback = None
  619. self._tlsext_servername_callback = None
  620. self._app_data = None
  621. self._npn_advertise_helper = None
  622. self._npn_advertise_callback = None
  623. self._npn_select_helper = None
  624. self._npn_select_callback = None
  625. self._alpn_select_helper = None
  626. self._alpn_select_callback = None
  627. self._ocsp_helper = None
  628. self._ocsp_callback = None
  629. self._ocsp_data = None
  630. self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
  631. def load_verify_locations(self, cafile, capath=None):
  632. """
  633. Let SSL know where we can find trusted certificates for the certificate
  634. chain. Note that the certificates have to be in PEM format.
  635. If capath is passed, it must be a directory prepared using the
  636. ``c_rehash`` tool included with OpenSSL. Either, but not both, of
  637. *pemfile* or *capath* may be :data:`None`.
  638. :param cafile: In which file we can find the certificates (``bytes`` or
  639. ``unicode``).
  640. :param capath: In which directory we can find the certificates
  641. (``bytes`` or ``unicode``).
  642. :return: None
  643. """
  644. if cafile is None:
  645. cafile = _ffi.NULL
  646. else:
  647. cafile = _path_string(cafile)
  648. if capath is None:
  649. capath = _ffi.NULL
  650. else:
  651. capath = _path_string(capath)
  652. load_result = _lib.SSL_CTX_load_verify_locations(
  653. self._context, cafile, capath
  654. )
  655. if not load_result:
  656. _raise_current_error()
  657. def _wrap_callback(self, callback):
  658. @wraps(callback)
  659. def wrapper(size, verify, userdata):
  660. return callback(size, verify, self._passphrase_userdata)
  661. return _PassphraseHelper(
  662. FILETYPE_PEM, wrapper, more_args=True, truncate=True)
  663. def set_passwd_cb(self, callback, userdata=None):
  664. """
  665. Set the passphrase callback. This function will be called
  666. when a private key with a passphrase is loaded.
  667. :param callback: The Python callback to use. This must accept three
  668. positional arguments. First, an integer giving the maximum length
  669. of the passphrase it may return. If the returned passphrase is
  670. longer than this, it will be truncated. Second, a boolean value
  671. which will be true if the user should be prompted for the
  672. passphrase twice and the callback should verify that the two values
  673. supplied are equal. Third, the value given as the *userdata*
  674. parameter to :meth:`set_passwd_cb`. The *callback* must return
  675. a byte string. If an error occurs, *callback* should return a false
  676. value (e.g. an empty string).
  677. :param userdata: (optional) A Python object which will be given as
  678. argument to the callback
  679. :return: None
  680. """
  681. if not callable(callback):
  682. raise TypeError("callback must be callable")
  683. self._passphrase_helper = self._wrap_callback(callback)
  684. self._passphrase_callback = self._passphrase_helper.callback
  685. _lib.SSL_CTX_set_default_passwd_cb(
  686. self._context, self._passphrase_callback)
  687. self._passphrase_userdata = userdata
  688. def set_default_verify_paths(self):
  689. """
  690. Specify that the platform provided CA certificates are to be used for
  691. verification purposes. This method has some caveats related to the
  692. binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
  693. * macOS will only load certificates using this method if the user has
  694. the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
  695. in the default location.
  696. * Windows will not work.
  697. * manylinux1 cryptography wheels will work on most common Linux
  698. distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
  699. manylinux1 wheel and attempts to load roots via a fallback path.
  700. :return: None
  701. """
  702. # SSL_CTX_set_default_verify_paths will attempt to load certs from
  703. # both a cafile and capath that are set at compile time. However,
  704. # it will first check environment variables and, if present, load
  705. # those paths instead
  706. set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
  707. _openssl_assert(set_result == 1)
  708. # After attempting to set default_verify_paths we need to know whether
  709. # to go down the fallback path.
  710. # First we'll check to see if any env vars have been set. If so,
  711. # we won't try to do anything else because the user has set the path
  712. # themselves.
  713. dir_env_var = _ffi.string(
  714. _lib.X509_get_default_cert_dir_env()
  715. ).decode("ascii")
  716. file_env_var = _ffi.string(
  717. _lib.X509_get_default_cert_file_env()
  718. ).decode("ascii")
  719. if not self._check_env_vars_set(dir_env_var, file_env_var):
  720. default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
  721. default_file = _ffi.string(_lib.X509_get_default_cert_file())
  722. # Now we check to see if the default_dir and default_file are set
  723. # to the exact values we use in our manylinux1 builds. If they are
  724. # then we know to load the fallbacks
  725. if (
  726. default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
  727. default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
  728. ):
  729. # This is manylinux1, let's load our fallback paths
  730. self._fallback_default_verify_paths(
  731. _CERTIFICATE_FILE_LOCATIONS,
  732. _CERTIFICATE_PATH_LOCATIONS
  733. )
  734. def _check_env_vars_set(self, dir_env_var, file_env_var):
  735. """
  736. Check to see if the default cert dir/file environment vars are present.
  737. :return: bool
  738. """
  739. return (
  740. os.environ.get(file_env_var) is not None or
  741. os.environ.get(dir_env_var) is not None
  742. )
  743. def _fallback_default_verify_paths(self, file_path, dir_path):
  744. """
  745. Default verify paths are based on the compiled version of OpenSSL.
  746. However, when pyca/cryptography is compiled as a manylinux1 wheel
  747. that compiled location can potentially be wrong. So, like Go, we
  748. will try a predefined set of paths and attempt to load roots
  749. from there.
  750. :return: None
  751. """
  752. for cafile in file_path:
  753. if os.path.isfile(cafile):
  754. self.load_verify_locations(cafile)
  755. break
  756. for capath in dir_path:
  757. if os.path.isdir(capath):
  758. self.load_verify_locations(None, capath)
  759. break
  760. def use_certificate_chain_file(self, certfile):
  761. """
  762. Load a certificate chain from a file.
  763. :param certfile: The name of the certificate chain file (``bytes`` or
  764. ``unicode``). Must be PEM encoded.
  765. :return: None
  766. """
  767. certfile = _path_string(certfile)
  768. result = _lib.SSL_CTX_use_certificate_chain_file(
  769. self._context, certfile
  770. )
  771. if not result:
  772. _raise_current_error()
  773. def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
  774. """
  775. Load a certificate from a file
  776. :param certfile: The name of the certificate file (``bytes`` or
  777. ``unicode``).
  778. :param filetype: (optional) The encoding of the file, which is either
  779. :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
  780. :const:`FILETYPE_PEM`.
  781. :return: None
  782. """
  783. certfile = _path_string(certfile)
  784. if not isinstance(filetype, integer_types):
  785. raise TypeError("filetype must be an integer")
  786. use_result = _lib.SSL_CTX_use_certificate_file(
  787. self._context, certfile, filetype
  788. )
  789. if not use_result:
  790. _raise_current_error()
  791. def use_certificate(self, cert):
  792. """
  793. Load a certificate from a X509 object
  794. :param cert: The X509 object
  795. :return: None
  796. """
  797. if not isinstance(cert, X509):
  798. raise TypeError("cert must be an X509 instance")
  799. use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
  800. if not use_result:
  801. _raise_current_error()
  802. def add_extra_chain_cert(self, certobj):
  803. """
  804. Add certificate to chain
  805. :param certobj: The X509 certificate object to add to the chain
  806. :return: None
  807. """
  808. if not isinstance(certobj, X509):
  809. raise TypeError("certobj must be an X509 instance")
  810. copy = _lib.X509_dup(certobj._x509)
  811. add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
  812. if not add_result:
  813. # TODO: This is untested.
  814. _lib.X509_free(copy)
  815. _raise_current_error()
  816. def _raise_passphrase_exception(self):
  817. if self._passphrase_helper is not None:
  818. self._passphrase_helper.raise_if_problem(Error)
  819. _raise_current_error()
  820. def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
  821. """
  822. Load a private key from a file
  823. :param keyfile: The name of the key file (``bytes`` or ``unicode``)
  824. :param filetype: (optional) The encoding of the file, which is either
  825. :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
  826. :const:`FILETYPE_PEM`.
  827. :return: None
  828. """
  829. keyfile = _path_string(keyfile)
  830. if filetype is _UNSPECIFIED:
  831. filetype = FILETYPE_PEM
  832. elif not isinstance(filetype, integer_types):
  833. raise TypeError("filetype must be an integer")
  834. use_result = _lib.SSL_CTX_use_PrivateKey_file(
  835. self._context, keyfile, filetype)
  836. if not use_result:
  837. self._raise_passphrase_exception()
  838. def use_privatekey(self, pkey):
  839. """
  840. Load a private key from a PKey object
  841. :param pkey: The PKey object
  842. :return: None
  843. """
  844. if not isinstance(pkey, PKey):
  845. raise TypeError("pkey must be a PKey instance")
  846. use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
  847. if not use_result:
  848. self._raise_passphrase_exception()
  849. def check_privatekey(self):
  850. """
  851. Check if the private key (loaded with :meth:`use_privatekey`) matches
  852. the certificate (loaded with :meth:`use_certificate`)
  853. :return: :data:`None` (raises :exc:`Error` if something's wrong)
  854. """
  855. if not _lib.SSL_CTX_check_private_key(self._context):
  856. _raise_current_error()
  857. def load_client_ca(self, cafile):
  858. """
  859. Load the trusted certificates that will be sent to the client. Does
  860. not actually imply any of the certificates are trusted; that must be
  861. configured separately.
  862. :param bytes cafile: The path to a certificates file in PEM format.
  863. :return: None
  864. """
  865. ca_list = _lib.SSL_load_client_CA_file(
  866. _text_to_bytes_and_warn("cafile", cafile)
  867. )
  868. _openssl_assert(ca_list != _ffi.NULL)
  869. _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
  870. def set_session_id(self, buf):
  871. """
  872. Set the session id to *buf* within which a session can be reused for
  873. this Context object. This is needed when doing session resumption,
  874. because there is no way for a stored session to know which Context
  875. object it is associated with.
  876. :param bytes buf: The session id.
  877. :returns: None
  878. """
  879. buf = _text_to_bytes_and_warn("buf", buf)
  880. _openssl_assert(
  881. _lib.SSL_CTX_set_session_id_context(
  882. self._context,
  883. buf,
  884. len(buf),
  885. ) == 1
  886. )
  887. def set_session_cache_mode(self, mode):
  888. """
  889. Set the behavior of the session cache used by all connections using
  890. this Context. The previously set mode is returned. See
  891. :const:`SESS_CACHE_*` for details about particular modes.
  892. :param mode: One or more of the SESS_CACHE_* flags (combine using
  893. bitwise or)
  894. :returns: The previously set caching mode.
  895. .. versionadded:: 0.14
  896. """
  897. if not isinstance(mode, integer_types):
  898. raise TypeError("mode must be an integer")
  899. return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
  900. def get_session_cache_mode(self):
  901. """
  902. Get the current session cache mode.
  903. :returns: The currently used cache mode.
  904. .. versionadded:: 0.14
  905. """
  906. return _lib.SSL_CTX_get_session_cache_mode(self._context)
  907. def set_verify(self, mode, callback):
  908. """
  909. et the verification flags for this Context object to *mode* and specify
  910. that *callback* should be used for verification callbacks.
  911. :param mode: The verify mode, this should be one of
  912. :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
  913. :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
  914. :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
  915. :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
  916. :param callback: The Python callback to use. This should take five
  917. arguments: A Connection object, an X509 object, and three integer
  918. variables, which are in turn potential error number, error depth
  919. and return code. *callback* should return True if verification
  920. passes and False otherwise.
  921. :return: None
  922. See SSL_CTX_set_verify(3SSL) for further details.
  923. """
  924. if not isinstance(mode, integer_types):
  925. raise TypeError("mode must be an integer")
  926. if not callable(callback):
  927. raise TypeError("callback must be callable")
  928. self._verify_helper = _VerifyHelper(callback)
  929. self._verify_callback = self._verify_helper.callback
  930. _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
  931. def set_verify_depth(self, depth):
  932. """
  933. Set the maximum depth for the certificate chain verification that shall
  934. be allowed for this Context object.
  935. :param depth: An integer specifying the verify depth
  936. :return: None
  937. """
  938. if not isinstance(depth, integer_types):
  939. raise TypeError("depth must be an integer")
  940. _lib.SSL_CTX_set_verify_depth(self._context, depth)
  941. def get_verify_mode(self):
  942. """
  943. Retrieve the Context object's verify mode, as set by
  944. :meth:`set_verify`.
  945. :return: The verify mode
  946. """
  947. return _lib.SSL_CTX_get_verify_mode(self._context)
  948. def get_verify_depth(self):
  949. """
  950. Retrieve the Context object's verify depth, as set by
  951. :meth:`set_verify_depth`.
  952. :return: The verify depth
  953. """
  954. return _lib.SSL_CTX_get_verify_depth(self._context)
  955. def load_tmp_dh(self, dhfile):
  956. """
  957. Load parameters for Ephemeral Diffie-Hellman
  958. :param dhfile: The file to load EDH parameters from (``bytes`` or
  959. ``unicode``).
  960. :return: None
  961. """
  962. dhfile = _path_string(dhfile)
  963. bio = _lib.BIO_new_file(dhfile, b"r")
  964. if bio == _ffi.NULL:
  965. _raise_current_error()
  966. bio = _ffi.gc(bio, _lib.BIO_free)
  967. dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  968. dh = _ffi.gc(dh, _lib.DH_free)
  969. _lib.SSL_CTX_set_tmp_dh(self._context, dh)
  970. def set_tmp_ecdh(self, curve):
  971. """
  972. Select a curve to use for ECDHE key exchange.
  973. :param curve: A curve object to use as returned by either
  974. :meth:`OpenSSL.crypto.get_elliptic_curve` or
  975. :meth:`OpenSSL.crypto.get_elliptic_curves`.
  976. :return: None
  977. """
  978. _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
  979. def set_cipher_list(self, cipher_list):
  980. """
  981. Set the list of ciphers to be used in this context.
  982. See the OpenSSL manual for more information (e.g.
  983. :manpage:`ciphers(1)`).
  984. :param bytes cipher_list: An OpenSSL cipher string.
  985. :return: None
  986. """
  987. cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
  988. if not isinstance(cipher_list, bytes):
  989. raise TypeError("cipher_list must be a byte string.")
  990. _openssl_assert(
  991. _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
  992. )
  993. # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
  994. # ciphers even if you pass an invalid cipher. Applications (like
  995. # Twisted) have tests that depend on an error being raised if an
  996. # invalid cipher string is passed, but without the following check
  997. # for the TLS 1.3 specific cipher suites it would never error.
  998. tmpconn = Connection(self, None)
  999. if (
  1000. tmpconn.get_cipher_list() == [
  1001. 'TLS_AES_256_GCM_SHA384',
  1002. 'TLS_CHACHA20_POLY1305_SHA256',
  1003. 'TLS_AES_128_GCM_SHA256'
  1004. ]
  1005. ):
  1006. raise Error(
  1007. [
  1008. (
  1009. 'SSL routines',
  1010. 'SSL_CTX_set_cipher_list',
  1011. 'no cipher match',
  1012. ),
  1013. ],
  1014. )
  1015. def set_client_ca_list(self, certificate_authorities):
  1016. """
  1017. Set the list of preferred client certificate signers for this server
  1018. context.
  1019. This list of certificate authorities will be sent to the client when
  1020. the server requests a client certificate.
  1021. :param certificate_authorities: a sequence of X509Names.
  1022. :return: None
  1023. .. versionadded:: 0.10
  1024. """
  1025. name_stack = _lib.sk_X509_NAME_new_null()
  1026. _openssl_assert(name_stack != _ffi.NULL)
  1027. try:
  1028. for ca_name in certificate_authorities:
  1029. if not isinstance(ca_name, X509Name):
  1030. raise TypeError(
  1031. "client CAs must be X509Name objects, not %s "
  1032. "objects" % (
  1033. type(ca_name).__name__,
  1034. )
  1035. )
  1036. copy = _lib.X509_NAME_dup(ca_name._name)
  1037. _openssl_assert(copy != _ffi.NULL)
  1038. push_result = _lib.sk_X509_NAME_push(name_stack, copy)
  1039. if not push_result:
  1040. _lib.X509_NAME_free(copy)
  1041. _raise_current_error()
  1042. except Exception:
  1043. _lib.sk_X509_NAME_free(name_stack)
  1044. raise
  1045. _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
  1046. def add_client_ca(self, certificate_authority):
  1047. """
  1048. Add the CA certificate to the list of preferred signers for this
  1049. context.
  1050. The list of certificate authorities will be sent to the client when the
  1051. server requests a client certificate.
  1052. :param certificate_authority: certificate authority's X509 certificate.
  1053. :return: None
  1054. .. versionadded:: 0.10
  1055. """
  1056. if not isinstance(certificate_authority, X509):
  1057. raise TypeError("certificate_authority must be an X509 instance")
  1058. add_result = _lib.SSL_CTX_add_client_CA(
  1059. self._context, certificate_authority._x509)
  1060. _openssl_assert(add_result == 1)
  1061. def set_timeout(self, timeout):
  1062. """
  1063. Set the timeout for newly created sessions for this Context object to
  1064. *timeout*. The default value is 300 seconds. See the OpenSSL manual
  1065. for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
  1066. :param timeout: The timeout in (whole) seconds
  1067. :return: The previous session timeout
  1068. """
  1069. if not isinstance(timeout, integer_types):
  1070. raise TypeError("timeout must be an integer")
  1071. return _lib.SSL_CTX_set_timeout(self._context, timeout)
  1072. def get_timeout(self):
  1073. """
  1074. Retrieve session timeout, as set by :meth:`set_timeout`. The default
  1075. is 300 seconds.
  1076. :return: The session timeout
  1077. """
  1078. return _lib.SSL_CTX_get_timeout(self._context)
  1079. def set_info_callback(self, callback):
  1080. """
  1081. Set the information callback to *callback*. This function will be
  1082. called from time to time during SSL handshakes.
  1083. :param callback: The Python callback to use. This should take three
  1084. arguments: a Connection object and two integers. The first integer
  1085. specifies where in the SSL handshake the function was called, and
  1086. the other the return code from a (possibly failed) internal
  1087. function call.
  1088. :return: None
  1089. """
  1090. @wraps(callback)
  1091. def wrapper(ssl, where, return_code):
  1092. callback(Connection._reverse_mapping[ssl], where, return_code)
  1093. self._info_callback = _ffi.callback(
  1094. "void (*)(const SSL *, int, int)", wrapper)
  1095. _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
  1096. def get_app_data(self):
  1097. """
  1098. Get the application data (supplied via :meth:`set_app_data()`)
  1099. :return: The application data
  1100. """
  1101. return self._app_data
  1102. def set_app_data(self, data):
  1103. """
  1104. Set the application data (will be returned from get_app_data())
  1105. :param data: Any Python object
  1106. :return: None
  1107. """
  1108. self._app_data = data
  1109. def get_cert_store(self):
  1110. """
  1111. Get the certificate store for the context. This can be used to add
  1112. "trusted" certificates without using the
  1113. :meth:`load_verify_locations` method.
  1114. :return: A X509Store object or None if it does not have one.
  1115. """
  1116. store = _lib.SSL_CTX_get_cert_store(self._context)
  1117. if store == _ffi.NULL:
  1118. # TODO: This is untested.
  1119. return None
  1120. pystore = X509Store.__new__(X509Store)
  1121. pystore._store = store
  1122. return pystore
  1123. def set_options(self, options):
  1124. """
  1125. Add options. Options set before are not cleared!
  1126. This method should be used with the :const:`OP_*` constants.
  1127. :param options: The options to add.
  1128. :return: The new option bitmask.
  1129. """
  1130. if not isinstance(options, integer_types):
  1131. raise TypeError("options must be an integer")
  1132. return _lib.SSL_CTX_set_options(self._context, options)
  1133. def set_mode(self, mode):
  1134. """
  1135. Add modes via bitmask. Modes set before are not cleared! This method
  1136. should be used with the :const:`MODE_*` constants.
  1137. :param mode: The mode to add.
  1138. :return: The new mode bitmask.
  1139. """
  1140. if not isinstance(mode, integer_types):
  1141. raise TypeError("mode must be an integer")
  1142. return _lib.SSL_CTX_set_mode(self._context, mode)
  1143. def set_tlsext_servername_callback(self, callback):
  1144. """
  1145. Specify a callback function to be called when clients specify a server
  1146. name.
  1147. :param callback: The callback function. It will be invoked with one
  1148. argument, the Connection instance.
  1149. .. versionadded:: 0.13
  1150. """
  1151. @wraps(callback)
  1152. def wrapper(ssl, alert, arg):
  1153. callback(Connection._reverse_mapping[ssl])
  1154. return 0
  1155. self._tlsext_servername_callback = _ffi.callback(
  1156. "int (*)(SSL *, int *, void *)", wrapper)
  1157. _lib.SSL_CTX_set_tlsext_servername_callback(
  1158. self._context, self._tlsext_servername_callback)
  1159. def set_tlsext_use_srtp(self, profiles):
  1160. """
  1161. Enable support for negotiating SRTP keying material.
  1162. :param bytes profiles: A colon delimited list of protection profile
  1163. names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
  1164. :return: None
  1165. """
  1166. if not isinstance(profiles, bytes):
  1167. raise TypeError("profiles must be a byte string.")
  1168. _openssl_assert(
  1169. _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
  1170. )
  1171. @_requires_npn
  1172. def set_npn_advertise_callback(self, callback):
  1173. """
  1174. Specify a callback function that will be called when offering `Next
  1175. Protocol Negotiation
  1176. <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
  1177. :param callback: The callback function. It will be invoked with one
  1178. argument, the :class:`Connection` instance. It should return a
  1179. list of bytestrings representing the advertised protocols, like
  1180. ``[b'http/1.1', b'spdy/2']``.
  1181. .. versionadded:: 0.15
  1182. """
  1183. _warn_npn()
  1184. self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
  1185. self._npn_advertise_callback = self._npn_advertise_helper.callback
  1186. _lib.SSL_CTX_set_next_protos_advertised_cb(
  1187. self._context, self._npn_advertise_callback, _ffi.NULL)
  1188. @_requires_npn
  1189. def set_npn_select_callback(self, callback):
  1190. """
  1191. Specify a callback function that will be called when a server offers
  1192. Next Protocol Negotiation options.
  1193. :param callback: The callback function. It will be invoked with two
  1194. arguments: the Connection, and a list of offered protocols as
  1195. bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
  1196. one of those bytestrings, the chosen protocol.
  1197. .. versionadded:: 0.15
  1198. """
  1199. _warn_npn()
  1200. self._npn_select_helper = _NpnSelectHelper(callback)
  1201. self._npn_select_callback = self._npn_select_helper.callback
  1202. _lib.SSL_CTX_set_next_proto_select_cb(
  1203. self._context, self._npn_select_callback, _ffi.NULL)
  1204. @_requires_alpn
  1205. def set_alpn_protos(self, protos):
  1206. """
  1207. Specify the protocols that the client is prepared to speak after the
  1208. TLS connection has been negotiated using Application Layer Protocol
  1209. Negotiation.
  1210. :param protos: A list of the protocols to be offered to the server.
  1211. This list should be a Python list of bytestrings representing the
  1212. protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
  1213. """
  1214. # Take the list of protocols and join them together, prefixing them
  1215. # with their lengths.
  1216. protostr = b''.join(
  1217. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  1218. )
  1219. # Build a C string from the list. We don't need to save this off
  1220. # because OpenSSL immediately copies the data out.
  1221. input_str = _ffi.new("unsigned char[]", protostr)
  1222. _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
  1223. @_requires_alpn
  1224. def set_alpn_select_callback(self, callback):
  1225. """
  1226. Specify a callback function that will be called on the server when a
  1227. client offers protocols using ALPN.
  1228. :param callback: The callback function. It will be invoked with two
  1229. arguments: the Connection, and a list of offered protocols as
  1230. bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
  1231. one of those bytestrings to indicate the chosen protocol, the
  1232. empty bytestring to terminate the TLS connection, or the
  1233. :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
  1234. protocol was selected, but that the connection should not be
  1235. aborted.
  1236. """
  1237. self._alpn_select_helper = _ALPNSelectHelper(callback)
  1238. self._alpn_select_callback = self._alpn_select_helper.callback
  1239. _lib.SSL_CTX_set_alpn_select_cb(
  1240. self._context, self._alpn_select_callback, _ffi.NULL)
  1241. def _set_ocsp_callback(self, helper, data):
  1242. """
  1243. This internal helper does the common work for
  1244. ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
  1245. almost all of it.
  1246. """
  1247. self._ocsp_helper = helper
  1248. self._ocsp_callback = helper.callback
  1249. if data is None:
  1250. self._ocsp_data = _ffi.NULL
  1251. else:
  1252. self._ocsp_data = _ffi.new_handle(data)
  1253. rc = _lib.SSL_CTX_set_tlsext_status_cb(
  1254. self._context, self._ocsp_callback
  1255. )
  1256. _openssl_assert(rc == 1)
  1257. rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
  1258. _openssl_assert(rc == 1)
  1259. def set_ocsp_server_callback(self, callback, data=None):
  1260. """
  1261. Set a callback to provide OCSP data to be stapled to the TLS handshake
  1262. on the server side.
  1263. :param callback: The callback function. It will be invoked with two
  1264. arguments: the Connection, and the optional arbitrary data you have
  1265. provided. The callback must return a bytestring that contains the
  1266. OCSP data to staple to the handshake. If no OCSP data is available
  1267. for this connection, return the empty bytestring.
  1268. :param data: Some opaque data that will be passed into the callback
  1269. function when called. This can be used to avoid needing to do
  1270. complex data lookups or to keep track of what context is being
  1271. used. This parameter is optional.
  1272. """
  1273. helper = _OCSPServerCallbackHelper(callback)
  1274. self._set_ocsp_callback(helper, data)
  1275. def set_ocsp_client_callback(self, callback, data=None):
  1276. """
  1277. Set a callback to validate OCSP data stapled to the TLS handshake on
  1278. the client side.
  1279. :param callback: The callback function. It will be invoked with three
  1280. arguments: the Connection, a bytestring containing the stapled OCSP
  1281. assertion, and the optional arbitrary data you have provided. The
  1282. callback must return a boolean that indicates the result of
  1283. validating the OCSP data: ``True`` if the OCSP data is valid and
  1284. the certificate can be trusted, or ``False`` if either the OCSP
  1285. data is invalid or the certificate has been revoked.
  1286. :param data: Some opaque data that will be passed into the callback
  1287. function when called. This can be used to avoid needing to do
  1288. complex data lookups or to keep track of what context is being
  1289. used. This parameter is optional.
  1290. """
  1291. helper = _OCSPClientCallbackHelper(callback)
  1292. self._set_ocsp_callback(helper, data)
  1293. class Connection(object):
  1294. """
  1295. """
  1296. _reverse_mapping = WeakValueDictionary()
  1297. def __init__(self, context, socket=None):
  1298. """
  1299. Create a new Connection object, using the given OpenSSL.SSL.Context
  1300. instance and socket.
  1301. :param context: An SSL Context to use for this connection
  1302. :param socket: The socket to use for transport layer
  1303. """
  1304. if not isinstance(context, Context):
  1305. raise TypeError("context must be a Context instance")
  1306. ssl = _lib.SSL_new(context._context)
  1307. self._ssl = _ffi.gc(ssl, _lib.SSL_free)
  1308. # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
  1309. # an SSL_ERROR_WANT_READ when processing a non-application data packet
  1310. # even though there is still data on the underlying transport.
  1311. # See https://github.com/openssl/openssl/issues/6234 for more details.
  1312. _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
  1313. self._context = context
  1314. self._app_data = None
  1315. # References to strings used for Next Protocol Negotiation. OpenSSL's
  1316. # header files suggest that these might get copied at some point, but
  1317. # doesn't specify when, so we store them here to make sure they don't
  1318. # get freed before OpenSSL uses them.
  1319. self._npn_advertise_callback_args = None
  1320. self._npn_select_callback_args = None
  1321. # References to strings used for Application Layer Protocol
  1322. # Negotiation. These strings get copied at some point but it's well
  1323. # after the callback returns, so we have to hang them somewhere to
  1324. # avoid them getting freed.
  1325. self._alpn_select_callback_args = None
  1326. self._reverse_mapping[self._ssl] = self
  1327. if socket is None:
  1328. self._socket = None
  1329. # Don't set up any gc for these, SSL_free will take care of them.
  1330. self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
  1331. _openssl_assert(self._into_ssl != _ffi.NULL)
  1332. self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
  1333. _openssl_assert(self._from_ssl != _ffi.NULL)
  1334. _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
  1335. else:
  1336. self._into_ssl = None
  1337. self._from_ssl = None
  1338. self._socket = socket
  1339. set_result = _lib.SSL_set_fd(
  1340. self._ssl, _asFileDescriptor(self._socket))
  1341. _openssl_assert(set_result == 1)
  1342. def __getattr__(self, name):
  1343. """
  1344. Look up attributes on the wrapped socket object if they are not found
  1345. on the Connection object.
  1346. """
  1347. if self._socket is None:
  1348. raise AttributeError("'%s' object has no attribute '%s'" % (
  1349. self.__class__.__name__, name
  1350. ))
  1351. else:
  1352. return getattr(self._socket, name)
  1353. def _raise_ssl_error(self, ssl, result):
  1354. if self._context._verify_helper is not None:
  1355. self._context._verify_helper.raise_if_problem()
  1356. if self._context._npn_advertise_helper is not None:
  1357. self._context._npn_advertise_helper.raise_if_problem()
  1358. if self._context._npn_select_helper is not None:
  1359. self._context._npn_select_helper.raise_if_problem()
  1360. if self._context._alpn_select_helper is not None:
  1361. self._context._alpn_select_helper.raise_if_problem()
  1362. if self._context._ocsp_helper is not None:
  1363. self._context._ocsp_helper.raise_if_problem()
  1364. error = _lib.SSL_get_error(ssl, result)
  1365. if error == _lib.SSL_ERROR_WANT_READ:
  1366. raise WantReadError()
  1367. elif error == _lib.SSL_ERROR_WANT_WRITE:
  1368. raise WantWriteError()
  1369. elif error == _lib.SSL_ERROR_ZERO_RETURN:
  1370. raise ZeroReturnError()
  1371. elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
  1372. # TODO: This is untested.
  1373. raise WantX509LookupError()
  1374. elif error == _lib.SSL_ERROR_SYSCALL:
  1375. if _lib.ERR_peek_error() == 0:
  1376. if result < 0:
  1377. if platform == "win32":
  1378. errno = _ffi.getwinerror()[0]
  1379. else:
  1380. errno = _ffi.errno
  1381. if errno != 0:
  1382. raise SysCallError(errno, errorcode.get(errno))
  1383. raise SysCallError(-1, "Unexpected EOF")
  1384. else:
  1385. # TODO: This is untested.
  1386. _raise_current_error()
  1387. elif error == _lib.SSL_ERROR_NONE:
  1388. pass
  1389. else:
  1390. _raise_current_error()
  1391. def get_context(self):
  1392. """
  1393. Retrieve the :class:`Context` object associated with this
  1394. :class:`Connection`.
  1395. """
  1396. return self._context
  1397. def set_context(self, context):
  1398. """
  1399. Switch this connection to a new session context.
  1400. :param context: A :class:`Context` instance giving the new session
  1401. context to use.
  1402. """
  1403. if not isinstance(context, Context):
  1404. raise TypeError("context must be a Context instance")
  1405. _lib.SSL_set_SSL_CTX(self._ssl, context._context)
  1406. self._context = context
  1407. def get_servername(self):
  1408. """
  1409. Retrieve the servername extension value if provided in the client hello
  1410. message, or None if there wasn't one.
  1411. :return: A byte string giving the server name or :data:`None`.
  1412. .. versionadded:: 0.13
  1413. """
  1414. name = _lib.SSL_get_servername(
  1415. self._ssl, _lib.TLSEXT_NAMETYPE_host_name
  1416. )
  1417. if name == _ffi.NULL:
  1418. return None
  1419. return _ffi.string(name)
  1420. def set_tlsext_host_name(self, name):
  1421. """
  1422. Set the value of the servername extension to send in the client hello.
  1423. :param name: A byte string giving the name.
  1424. .. versionadded:: 0.13
  1425. """
  1426. if not isinstance(name, bytes):
  1427. raise TypeError("name must be a byte string")
  1428. elif b"\0" in name:
  1429. raise TypeError("name must not contain NUL byte")
  1430. # XXX I guess this can fail sometimes?
  1431. _lib.SSL_set_tlsext_host_name(self._ssl, name)
  1432. def pending(self):
  1433. """
  1434. Get the number of bytes that can be safely read from the SSL buffer
  1435. (**not** the underlying transport buffer).
  1436. :return: The number of bytes available in the receive buffer.
  1437. """
  1438. return _lib.SSL_pending(self._ssl)
  1439. def send(self, buf, flags=0):
  1440. """
  1441. Send data on the connection. NOTE: If you get one of the WantRead,
  1442. WantWrite or WantX509Lookup exceptions on this, you have to call the
  1443. method again with the SAME buffer.
  1444. :param buf: The string, buffer or memoryview to send
  1445. :param flags: (optional) Included for compatibility with the socket
  1446. API, the value is ignored
  1447. :return: The number of bytes written
  1448. """
  1449. # Backward compatibility
  1450. buf = _text_to_bytes_and_warn("buf", buf)
  1451. with _from_buffer(buf) as data:
  1452. # check len(buf) instead of len(data) for testability
  1453. if len(buf) > 2147483647:
  1454. raise ValueError(
  1455. "Cannot send more than 2**31-1 bytes at once."
  1456. )
  1457. result = _lib.SSL_write(self._ssl, data, len(data))
  1458. self._raise_ssl_error(self._ssl, result)
  1459. return result
  1460. write = send
  1461. def sendall(self, buf, flags=0):
  1462. """
  1463. Send "all" data on the connection. This calls send() repeatedly until
  1464. all data is sent. If an error occurs, it's impossible to tell how much
  1465. data has been sent.
  1466. :param buf: The string, buffer or memoryview to send
  1467. :param flags: (optional) Included for compatibility with the socket
  1468. API, the value is ignored
  1469. :return: The number of bytes written
  1470. """
  1471. buf = _text_to_bytes_and_warn("buf", buf)
  1472. with _from_buffer(buf) as data:
  1473. left_to_send = len(buf)
  1474. total_sent = 0
  1475. while left_to_send:
  1476. # SSL_write's num arg is an int,
  1477. # so we cannot send more than 2**31-1 bytes at once.
  1478. result = _lib.SSL_write(
  1479. self._ssl,
  1480. data + total_sent,
  1481. min(left_to_send, 2147483647)
  1482. )
  1483. self._raise_ssl_error(self._ssl, result)
  1484. total_sent += result
  1485. left_to_send -= result
  1486. return total_sent
  1487. def recv(self, bufsiz, flags=None):
  1488. """
  1489. Receive data on the connection.
  1490. :param bufsiz: The maximum number of bytes to read
  1491. :param flags: (optional) The only supported flag is ``MSG_PEEK``,
  1492. all other flags are ignored.
  1493. :return: The string read from the Connection
  1494. """
  1495. buf = _no_zero_allocator("char[]", bufsiz)
  1496. if flags is not None and flags & socket.MSG_PEEK:
  1497. result = _lib.SSL_peek(self._ssl, buf, bufsiz)
  1498. else:
  1499. result = _lib.SSL_read(self._ssl, buf, bufsiz)
  1500. self._raise_ssl_error(self._ssl, result)
  1501. return _ffi.buffer(buf, result)[:]
  1502. read = recv
  1503. def recv_into(self, buffer, nbytes=None, flags=None):
  1504. """
  1505. Receive data on the connection and copy it directly into the provided
  1506. buffer, rather than creating a new string.
  1507. :param buffer: The buffer to copy into.
  1508. :param nbytes: (optional) The maximum number of bytes to read into the
  1509. buffer. If not present, defaults to the size of the buffer. If
  1510. larger than the size of the buffer, is reduced to the size of the
  1511. buffer.
  1512. :param flags: (optional) The only supported flag is ``MSG_PEEK``,
  1513. all other flags are ignored.
  1514. :return: The number of bytes read into the buffer.
  1515. """
  1516. if nbytes is None:
  1517. nbytes = len(buffer)
  1518. else:
  1519. nbytes = min(nbytes, len(buffer))
  1520. # We need to create a temporary buffer. This is annoying, it would be
  1521. # better if we could pass memoryviews straight into the SSL_read call,
  1522. # but right now we can't. Revisit this if CFFI gets that ability.
  1523. buf = _no_zero_allocator("char[]", nbytes)
  1524. if flags is not None and flags & socket.MSG_PEEK:
  1525. result = _lib.SSL_peek(self._ssl, buf, nbytes)
  1526. else:
  1527. result = _lib.SSL_read(self._ssl, buf, nbytes)
  1528. self._raise_ssl_error(self._ssl, result)
  1529. # This strange line is all to avoid a memory copy. The buffer protocol
  1530. # should allow us to assign a CFFI buffer to the LHS of this line, but
  1531. # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
  1532. # wrap it in a memoryview.
  1533. buffer[:result] = memoryview(_ffi.buffer(buf, result))
  1534. return result
  1535. def _handle_bio_errors(self, bio, result):
  1536. if _lib.BIO_should_retry(bio):
  1537. if _lib.BIO_should_read(bio):
  1538. raise WantReadError()
  1539. elif _lib.BIO_should_write(bio):
  1540. # TODO: This is untested.
  1541. raise WantWriteError()
  1542. elif _lib.BIO_should_io_special(bio):
  1543. # TODO: This is untested. I think io_special means the socket
  1544. # BIO has a not-yet connected socket.
  1545. raise ValueError("BIO_should_io_special")
  1546. else:
  1547. # TODO: This is untested.
  1548. raise ValueError("unknown bio failure")
  1549. else:
  1550. # TODO: This is untested.
  1551. _raise_current_error()
  1552. def bio_read(self, bufsiz):
  1553. """
  1554. If the Connection was created with a memory BIO, this method can be
  1555. used to read bytes from the write end of that memory BIO. Many
  1556. Connection methods will add bytes which must be read in this manner or
  1557. the buffer will eventually fill up and the Connection will be able to
  1558. take no further actions.
  1559. :param bufsiz: The maximum number of bytes to read
  1560. :return: The string read.
  1561. """
  1562. if self._from_ssl is None:
  1563. raise TypeError("Connection sock was not None")
  1564. if not isinstance(bufsiz, integer_types):
  1565. raise TypeError("bufsiz must be an integer")
  1566. buf = _no_zero_allocator("char[]", bufsiz)
  1567. result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
  1568. if result <= 0:
  1569. self._handle_bio_errors(self._from_ssl, result)
  1570. return _ffi.buffer(buf, result)[:]
  1571. def bio_write(self, buf):
  1572. """
  1573. If the Connection was created with a memory BIO, this method can be
  1574. used to add bytes to the read end of that memory BIO. The Connection
  1575. can then read the bytes (for example, in response to a call to
  1576. :meth:`recv`).
  1577. :param buf: The string to put into the memory BIO.
  1578. :return: The number of bytes written
  1579. """
  1580. buf = _text_to_bytes_and_warn("buf", buf)
  1581. if self._into_ssl is None:
  1582. raise TypeError("Connection sock was not None")
  1583. with _from_buffer(buf) as data:
  1584. result = _lib.BIO_write(self._into_ssl, data, len(data))
  1585. if result <= 0:
  1586. self._handle_bio_errors(self._into_ssl, result)
  1587. return result
  1588. def renegotiate(self):
  1589. """
  1590. Renegotiate the session.
  1591. :return: True if the renegotiation can be started, False otherwise
  1592. :rtype: bool
  1593. """
  1594. if not self.renegotiate_pending():
  1595. _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
  1596. return True
  1597. return False
  1598. def do_handshake(self):
  1599. """
  1600. Perform an SSL handshake (usually called after :meth:`renegotiate` or
  1601. one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
  1602. raise the same exceptions as :meth:`send` and :meth:`recv`.
  1603. :return: None.
  1604. """
  1605. result = _lib.SSL_do_handshake(self._ssl)
  1606. self._raise_ssl_error(self._ssl, result)
  1607. def renegotiate_pending(self):
  1608. """
  1609. Check if there's a renegotiation in progress, it will return False once
  1610. a renegotiation is finished.
  1611. :return: Whether there's a renegotiation in progress
  1612. :rtype: bool
  1613. """
  1614. return _lib.SSL_renegotiate_pending(self._ssl) == 1
  1615. def total_renegotiations(self):
  1616. """
  1617. Find out the total number of renegotiations.
  1618. :return: The number of renegotiations.
  1619. :rtype: int
  1620. """
  1621. return _lib.SSL_total_renegotiations(self._ssl)
  1622. def connect(self, addr):
  1623. """
  1624. Call the :meth:`connect` method of the underlying socket and set up SSL
  1625. on the socket, using the :class:`Context` object supplied to this
  1626. :class:`Connection` object at creation.
  1627. :param addr: A remote address
  1628. :return: What the socket's connect method returns
  1629. """
  1630. _lib.SSL_set_connect_state(self._ssl)
  1631. return self._socket.connect(addr)
  1632. def connect_ex(self, addr):
  1633. """
  1634. Call the :meth:`connect_ex` method of the underlying socket and set up
  1635. SSL on the socket, using the Context object supplied to this Connection
  1636. object at creation. Note that if the :meth:`connect_ex` method of the
  1637. socket doesn't return 0, SSL won't be initialized.
  1638. :param addr: A remove address
  1639. :return: What the socket's connect_ex method returns
  1640. """
  1641. connect_ex = self._socket.connect_ex
  1642. self.set_connect_state()
  1643. return connect_ex(addr)
  1644. def accept(self):
  1645. """
  1646. Call the :meth:`accept` method of the underlying socket and set up SSL
  1647. on the returned socket, using the Context object supplied to this
  1648. :class:`Connection` object at creation.
  1649. :return: A *(conn, addr)* pair where *conn* is the new
  1650. :class:`Connection` object created, and *address* is as returned by
  1651. the socket's :meth:`accept`.
  1652. """
  1653. client, addr = self._socket.accept()
  1654. conn = Connection(self._context, client)
  1655. conn.set_accept_state()
  1656. return (conn, addr)
  1657. def bio_shutdown(self):
  1658. """
  1659. If the Connection was created with a memory BIO, this method can be
  1660. used to indicate that *end of file* has been reached on the read end of
  1661. that memory BIO.
  1662. :return: None
  1663. """
  1664. if self._from_ssl is None:
  1665. raise TypeError("Connection sock was not None")
  1666. _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
  1667. def shutdown(self):
  1668. """
  1669. Send the shutdown message to the Connection.
  1670. :return: True if the shutdown completed successfully (i.e. both sides
  1671. have sent closure alerts), False otherwise (in which case you
  1672. call :meth:`recv` or :meth:`send` when the connection becomes
  1673. readable/writeable).
  1674. """
  1675. result = _lib.SSL_shutdown(self._ssl)
  1676. if result < 0:
  1677. self._raise_ssl_error(self._ssl, result)
  1678. elif result > 0:
  1679. return True
  1680. else:
  1681. return False
  1682. def get_cipher_list(self):
  1683. """
  1684. Retrieve the list of ciphers used by the Connection object.
  1685. :return: A list of native cipher strings.
  1686. """
  1687. ciphers = []
  1688. for i in count():
  1689. result = _lib.SSL_get_cipher_list(self._ssl, i)
  1690. if result == _ffi.NULL:
  1691. break
  1692. ciphers.append(_native(_ffi.string(result)))
  1693. return ciphers
  1694. def get_client_ca_list(self):
  1695. """
  1696. Get CAs whose certificates are suggested for client authentication.
  1697. :return: If this is a server connection, the list of certificate
  1698. authorities that will be sent or has been sent to the client, as
  1699. controlled by this :class:`Connection`'s :class:`Context`.
  1700. If this is a client connection, the list will be empty until the
  1701. connection with the server is established.
  1702. .. versionadded:: 0.10
  1703. """
  1704. ca_names = _lib.SSL_get_client_CA_list(self._ssl)
  1705. if ca_names == _ffi.NULL:
  1706. # TODO: This is untested.
  1707. return []
  1708. result = []
  1709. for i in range(_lib.sk_X509_NAME_num(ca_names)):
  1710. name = _lib.sk_X509_NAME_value(ca_names, i)
  1711. copy = _lib.X509_NAME_dup(name)
  1712. _openssl_assert(copy != _ffi.NULL)
  1713. pyname = X509Name.__new__(X509Name)
  1714. pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
  1715. result.append(pyname)
  1716. return result
  1717. def makefile(self, *args, **kwargs):
  1718. """
  1719. The makefile() method is not implemented, since there is no dup
  1720. semantics for SSL connections
  1721. :raise: NotImplementedError
  1722. """
  1723. raise NotImplementedError(
  1724. "Cannot make file object of OpenSSL.SSL.Connection")
  1725. def get_app_data(self):
  1726. """
  1727. Retrieve application data as set by :meth:`set_app_data`.
  1728. :return: The application data
  1729. """
  1730. return self._app_data
  1731. def set_app_data(self, data):
  1732. """
  1733. Set application data
  1734. :param data: The application data
  1735. :return: None
  1736. """
  1737. self._app_data = data
  1738. def get_shutdown(self):
  1739. """
  1740. Get the shutdown state of the Connection.
  1741. :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
  1742. RECEIVED_SHUTDOWN.
  1743. """
  1744. return _lib.SSL_get_shutdown(self._ssl)
  1745. def set_shutdown(self, state):
  1746. """
  1747. Set the shutdown state of the Connection.
  1748. :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
  1749. :return: None
  1750. """
  1751. if not isinstance(state, integer_types):
  1752. raise TypeError("state must be an integer")
  1753. _lib.SSL_set_shutdown(self._ssl, state)
  1754. def get_state_string(self):
  1755. """
  1756. Retrieve a verbose string detailing the state of the Connection.
  1757. :return: A string representing the state
  1758. :rtype: bytes
  1759. """
  1760. return _ffi.string(_lib.SSL_state_string_long(self._ssl))
  1761. def server_random(self):
  1762. """
  1763. Retrieve the random value used with the server hello message.
  1764. :return: A string representing the state
  1765. """
  1766. session = _lib.SSL_get_session(self._ssl)
  1767. if session == _ffi.NULL:
  1768. return None
  1769. length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
  1770. assert length > 0
  1771. outp = _no_zero_allocator("unsigned char[]", length)
  1772. _lib.SSL_get_server_random(self._ssl, outp, length)
  1773. return _ffi.buffer(outp, length)[:]
  1774. def client_random(self):
  1775. """
  1776. Retrieve the random value used with the client hello message.
  1777. :return: A string representing the state
  1778. """
  1779. session = _lib.SSL_get_session(self._ssl)
  1780. if session == _ffi.NULL:
  1781. return None
  1782. length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
  1783. assert length > 0
  1784. outp = _no_zero_allocator("unsigned char[]", length)
  1785. _lib.SSL_get_client_random(self._ssl, outp, length)
  1786. return _ffi.buffer(outp, length)[:]
  1787. def master_key(self):
  1788. """
  1789. Retrieve the value of the master key for this session.
  1790. :return: A string representing the state
  1791. """
  1792. session = _lib.SSL_get_session(self._ssl)
  1793. if session == _ffi.NULL:
  1794. return None
  1795. length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
  1796. assert length > 0
  1797. outp = _no_zero_allocator("unsigned char[]", length)
  1798. _lib.SSL_SESSION_get_master_key(session, outp, length)
  1799. return _ffi.buffer(outp, length)[:]
  1800. def export_keying_material(self, label, olen, context=None):
  1801. """
  1802. Obtain keying material for application use.
  1803. :param: label - a disambiguating label string as described in RFC 5705
  1804. :param: olen - the length of the exported key material in bytes
  1805. :param: context - a per-association context value
  1806. :return: the exported key material bytes or None
  1807. """
  1808. outp = _no_zero_allocator("unsigned char[]", olen)
  1809. context_buf = _ffi.NULL
  1810. context_len = 0
  1811. use_context = 0
  1812. if context is not None:
  1813. context_buf = context
  1814. context_len = len(context)
  1815. use_context = 1
  1816. success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
  1817. label, len(label),
  1818. context_buf, context_len,
  1819. use_context)
  1820. _openssl_assert(success == 1)
  1821. return _ffi.buffer(outp, olen)[:]
  1822. def sock_shutdown(self, *args, **kwargs):
  1823. """
  1824. Call the :meth:`shutdown` method of the underlying socket.
  1825. See :manpage:`shutdown(2)`.
  1826. :return: What the socket's shutdown() method returns
  1827. """
  1828. return self._socket.shutdown(*args, **kwargs)
  1829. def get_certificate(self):
  1830. """
  1831. Retrieve the local certificate (if any)
  1832. :return: The local certificate
  1833. """
  1834. cert = _lib.SSL_get_certificate(self._ssl)
  1835. if cert != _ffi.NULL:
  1836. _lib.X509_up_ref(cert)
  1837. return X509._from_raw_x509_ptr(cert)
  1838. return None
  1839. def get_peer_certificate(self):
  1840. """
  1841. Retrieve the other side's certificate (if any)
  1842. :return: The peer's certificate
  1843. """
  1844. cert = _lib.SSL_get_peer_certificate(self._ssl)
  1845. if cert != _ffi.NULL:
  1846. return X509._from_raw_x509_ptr(cert)
  1847. return None
  1848. def get_peer_cert_chain(self):
  1849. """
  1850. Retrieve the other side's certificate (if any)
  1851. :return: A list of X509 instances giving the peer's certificate chain,
  1852. or None if it does not have one.
  1853. """
  1854. cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
  1855. if cert_stack == _ffi.NULL:
  1856. return None
  1857. result = []
  1858. for i in range(_lib.sk_X509_num(cert_stack)):
  1859. # TODO could incref instead of dup here
  1860. cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
  1861. pycert = X509._from_raw_x509_ptr(cert)
  1862. result.append(pycert)
  1863. return result
  1864. def want_read(self):
  1865. """
  1866. Checks if more data has to be read from the transport layer to complete
  1867. an operation.
  1868. :return: True iff more data has to be read
  1869. """
  1870. return _lib.SSL_want_read(self._ssl)
  1871. def want_write(self):
  1872. """
  1873. Checks if there is data to write to the transport layer to complete an
  1874. operation.
  1875. :return: True iff there is data to write
  1876. """
  1877. return _lib.SSL_want_write(self._ssl)
  1878. def set_accept_state(self):
  1879. """
  1880. Set the connection to work in server mode. The handshake will be
  1881. handled automatically by read/write.
  1882. :return: None
  1883. """
  1884. _lib.SSL_set_accept_state(self._ssl)
  1885. def set_connect_state(self):
  1886. """
  1887. Set the connection to work in client mode. The handshake will be
  1888. handled automatically by read/write.
  1889. :return: None
  1890. """
  1891. _lib.SSL_set_connect_state(self._ssl)
  1892. def get_session(self):
  1893. """
  1894. Returns the Session currently used.
  1895. :return: An instance of :class:`OpenSSL.SSL.Session` or
  1896. :obj:`None` if no session exists.
  1897. .. versionadded:: 0.14
  1898. """
  1899. session = _lib.SSL_get1_session(self._ssl)
  1900. if session == _ffi.NULL:
  1901. return None
  1902. pysession = Session.__new__(Session)
  1903. pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
  1904. return pysession
  1905. def set_session(self, session):
  1906. """
  1907. Set the session to be used when the TLS/SSL connection is established.
  1908. :param session: A Session instance representing the session to use.
  1909. :returns: None
  1910. .. versionadded:: 0.14
  1911. """
  1912. if not isinstance(session, Session):
  1913. raise TypeError("session must be a Session instance")
  1914. result = _lib.SSL_set_session(self._ssl, session._session)
  1915. if not result:
  1916. _raise_current_error()
  1917. def _get_finished_message(self, function):
  1918. """
  1919. Helper to implement :meth:`get_finished` and
  1920. :meth:`get_peer_finished`.
  1921. :param function: Either :data:`SSL_get_finished`: or
  1922. :data:`SSL_get_peer_finished`.
  1923. :return: :data:`None` if the desired message has not yet been
  1924. received, otherwise the contents of the message.
  1925. :rtype: :class:`bytes` or :class:`NoneType`
  1926. """
  1927. # The OpenSSL documentation says nothing about what might happen if the
  1928. # count argument given is zero. Specifically, it doesn't say whether
  1929. # the output buffer may be NULL in that case or not. Inspection of the
  1930. # implementation reveals that it calls memcpy() unconditionally.
  1931. # Section 7.1.4, paragraph 1 of the C standard suggests that
  1932. # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
  1933. # alone desirable) behavior (though it probably does on just about
  1934. # every implementation...)
  1935. #
  1936. # Allocate a tiny buffer to pass in (instead of just passing NULL as
  1937. # one might expect) for the initial call so as to be safe against this
  1938. # potentially undefined behavior.
  1939. empty = _ffi.new("char[]", 0)
  1940. size = function(self._ssl, empty, 0)
  1941. if size == 0:
  1942. # No Finished message so far.
  1943. return None
  1944. buf = _no_zero_allocator("char[]", size)
  1945. function(self._ssl, buf, size)
  1946. return _ffi.buffer(buf, size)[:]
  1947. def get_finished(self):
  1948. """
  1949. Obtain the latest TLS Finished message that we sent.
  1950. :return: The contents of the message or :obj:`None` if the TLS
  1951. handshake has not yet completed.
  1952. :rtype: :class:`bytes` or :class:`NoneType`
  1953. .. versionadded:: 0.15
  1954. """
  1955. return self._get_finished_message(_lib.SSL_get_finished)
  1956. def get_peer_finished(self):
  1957. """
  1958. Obtain the latest TLS Finished message that we received from the peer.
  1959. :return: The contents of the message or :obj:`None` if the TLS
  1960. handshake has not yet completed.
  1961. :rtype: :class:`bytes` or :class:`NoneType`
  1962. .. versionadded:: 0.15
  1963. """
  1964. return self._get_finished_message(_lib.SSL_get_peer_finished)
  1965. def get_cipher_name(self):
  1966. """
  1967. Obtain the name of the currently used cipher.
  1968. :returns: The name of the currently used cipher or :obj:`None`
  1969. if no connection has been established.
  1970. :rtype: :class:`unicode` or :class:`NoneType`
  1971. .. versionadded:: 0.15
  1972. """
  1973. cipher = _lib.SSL_get_current_cipher(self._ssl)
  1974. if cipher == _ffi.NULL:
  1975. return None
  1976. else:
  1977. name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
  1978. return name.decode("utf-8")
  1979. def get_cipher_bits(self):
  1980. """
  1981. Obtain the number of secret bits of the currently used cipher.
  1982. :returns: The number of secret bits of the currently used cipher
  1983. or :obj:`None` if no connection has been established.
  1984. :rtype: :class:`int` or :class:`NoneType`
  1985. .. versionadded:: 0.15
  1986. """
  1987. cipher = _lib.SSL_get_current_cipher(self._ssl)
  1988. if cipher == _ffi.NULL:
  1989. return None
  1990. else:
  1991. return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
  1992. def get_cipher_version(self):
  1993. """
  1994. Obtain the protocol version of the currently used cipher.
  1995. :returns: The protocol name of the currently used cipher
  1996. or :obj:`None` if no connection has been established.
  1997. :rtype: :class:`unicode` or :class:`NoneType`
  1998. .. versionadded:: 0.15
  1999. """
  2000. cipher = _lib.SSL_get_current_cipher(self._ssl)
  2001. if cipher == _ffi.NULL:
  2002. return None
  2003. else:
  2004. version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
  2005. return version.decode("utf-8")
  2006. def get_protocol_version_name(self):
  2007. """
  2008. Retrieve the protocol version of the current connection.
  2009. :returns: The TLS version of the current connection, for example
  2010. the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
  2011. for connections that were not successfully established.
  2012. :rtype: :class:`unicode`
  2013. """
  2014. version = _ffi.string(_lib.SSL_get_version(self._ssl))
  2015. return version.decode("utf-8")
  2016. def get_protocol_version(self):
  2017. """
  2018. Retrieve the SSL or TLS protocol version of the current connection.
  2019. :returns: The TLS version of the current connection. For example,
  2020. it will return ``0x769`` for connections made over TLS version 1.
  2021. :rtype: :class:`int`
  2022. """
  2023. version = _lib.SSL_version(self._ssl)
  2024. return version
  2025. @_requires_npn
  2026. def get_next_proto_negotiated(self):
  2027. """
  2028. Get the protocol that was negotiated by NPN.
  2029. :returns: A bytestring of the protocol name. If no protocol has been
  2030. negotiated yet, returns an empty string.
  2031. .. versionadded:: 0.15
  2032. """
  2033. _warn_npn()
  2034. data = _ffi.new("unsigned char **")
  2035. data_len = _ffi.new("unsigned int *")
  2036. _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
  2037. return _ffi.buffer(data[0], data_len[0])[:]
  2038. @_requires_alpn
  2039. def set_alpn_protos(self, protos):
  2040. """
  2041. Specify the client's ALPN protocol list.
  2042. These protocols are offered to the server during protocol negotiation.
  2043. :param protos: A list of the protocols to be offered to the server.
  2044. This list should be a Python list of bytestrings representing the
  2045. protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
  2046. """
  2047. # Take the list of protocols and join them together, prefixing them
  2048. # with their lengths.
  2049. protostr = b''.join(
  2050. chain.from_iterable((int2byte(len(p)), p) for p in protos)
  2051. )
  2052. # Build a C string from the list. We don't need to save this off
  2053. # because OpenSSL immediately copies the data out.
  2054. input_str = _ffi.new("unsigned char[]", protostr)
  2055. _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
  2056. @_requires_alpn
  2057. def get_alpn_proto_negotiated(self):
  2058. """
  2059. Get the protocol that was negotiated by ALPN.
  2060. :returns: A bytestring of the protocol name. If no protocol has been
  2061. negotiated yet, returns an empty string.
  2062. """
  2063. data = _ffi.new("unsigned char **")
  2064. data_len = _ffi.new("unsigned int *")
  2065. _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
  2066. if not data_len:
  2067. return b''
  2068. return _ffi.buffer(data[0], data_len[0])[:]
  2069. def request_ocsp(self):
  2070. """
  2071. Called to request that the server sends stapled OCSP data, if
  2072. available. If this is not called on the client side then the server
  2073. will not send OCSP data. Should be used in conjunction with
  2074. :meth:`Context.set_ocsp_client_callback`.
  2075. """
  2076. rc = _lib.SSL_set_tlsext_status_type(
  2077. self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
  2078. )
  2079. _openssl_assert(rc == 1)
  2080. # This is similar to the initialization calls at the end of OpenSSL/crypto.py
  2081. # but is exercised mostly by the Context initializer.
  2082. _lib.SSL_library_init()