Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SSL.py 99KB

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