SSL.py 86 KB

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