You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2499 lines
87 KiB

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