SSL.py 93 KB

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