SSL.py 90 KB

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