blob: 03f145552c6f9addcba7d6a5ea236af27ef28e31 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Alex Gaynorbe2bd542019-02-21 21:41:22 -05003import warnings
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02004from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05005from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01006from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08007from weakref import WeakValueDictionary
8from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08009
Alex Gaynor12576002019-11-18 00:18:50 -050010from six import integer_types, int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
Daniel Holth079c9632019-11-17 22:45:52 -050016 from_buffer as _from_buffer,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010018 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010019 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040020 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000022 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040023)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080024
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050026 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027
Nicolas Karolak736c6212017-11-26 14:40:28 +010028__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 'OP_NO_SSLv2',
44 'OP_NO_SSLv3',
45 'OP_NO_TLSv1',
46 'OP_NO_TLSv1_1',
47 'OP_NO_TLSv1_2',
Nathaniel J. Smitha1813732019-08-01 21:32:13 -070048 'OP_NO_TLSv1_3',
Nicolas Karolak736c6212017-11-26 14:40:28 +010049 'MODE_RELEASE_BUFFERS',
50 'OP_SINGLE_DH_USE',
51 'OP_SINGLE_ECDH_USE',
52 'OP_EPHEMERAL_RSA',
53 'OP_MICROSOFT_SESS_ID_BUG',
54 'OP_NETSCAPE_CHALLENGE_BUG',
55 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
56 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
57 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
58 'OP_MSIE_SSLV2_RSA_PADDING',
59 'OP_SSLEAY_080_CLIENT_DH_BUG',
60 'OP_TLS_D5_BUG',
61 'OP_TLS_BLOCK_PADDING_BUG',
62 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
63 'OP_CIPHER_SERVER_PREFERENCE',
64 'OP_TLS_ROLLBACK_BUG',
65 'OP_PKCS1_CHECK_1',
66 'OP_PKCS1_CHECK_2',
67 'OP_NETSCAPE_CA_DN_BUG',
68 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
69 'OP_NO_COMPRESSION',
70 'OP_NO_QUERY_MTU',
71 'OP_COOKIE_EXCHANGE',
72 'OP_NO_TICKET',
73 'OP_ALL',
74 'VERIFY_PEER',
75 'VERIFY_FAIL_IF_NO_PEER_CERT',
76 'VERIFY_CLIENT_ONCE',
77 'VERIFY_NONE',
78 'SESS_CACHE_OFF',
79 'SESS_CACHE_CLIENT',
80 'SESS_CACHE_SERVER',
81 'SESS_CACHE_BOTH',
82 'SESS_CACHE_NO_AUTO_CLEAR',
83 'SESS_CACHE_NO_INTERNAL_LOOKUP',
84 'SESS_CACHE_NO_INTERNAL_STORE',
85 'SESS_CACHE_NO_INTERNAL',
86 'SSL_ST_CONNECT',
87 'SSL_ST_ACCEPT',
88 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010089 'SSL_CB_LOOP',
90 'SSL_CB_EXIT',
91 'SSL_CB_READ',
92 'SSL_CB_WRITE',
93 'SSL_CB_ALERT',
94 'SSL_CB_READ_ALERT',
95 'SSL_CB_WRITE_ALERT',
96 'SSL_CB_ACCEPT_LOOP',
97 'SSL_CB_ACCEPT_EXIT',
98 'SSL_CB_CONNECT_LOOP',
99 'SSL_CB_CONNECT_EXIT',
100 'SSL_CB_HANDSHAKE_START',
101 'SSL_CB_HANDSHAKE_DONE',
102 'Error',
103 'WantReadError',
104 'WantWriteError',
105 'WantX509LookupError',
106 'ZeroReturnError',
107 'SysCallError',
108 'SSLeay_version',
109 'Session',
110 'Context',
111 'Connection'
112]
113
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500114try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200115 _buffer = buffer
116except NameError:
117 class _buffer(object):
118 pass
119
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500120OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
121SSLEAY_VERSION = _lib.SSLEAY_VERSION
122SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
123SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
124SSLEAY_DIR = _lib.SSLEAY_DIR
125SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500127SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
128RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800129
130SSLv2_METHOD = 1
131SSLv3_METHOD = 2
132SSLv23_METHOD = 3
133TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500134TLSv1_1_METHOD = 5
135TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800136
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500137OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
138OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
139OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700140OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
141OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700142try:
143 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
144except AttributeError:
145 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800146
Alex Gaynorbf012872016-06-04 13:18:39 -0700147MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500149OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900150OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500151OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
152OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
153OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400154OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
155 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
156)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500157OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
158OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400159OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500160OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
161OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
162OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
163OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
164OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
165OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
166OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
167OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
168OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400169OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
170 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
171)
Alex Gaynorbf012872016-06-04 13:18:39 -0700172OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800173
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500174OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
175OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400176OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800177
Alex Gaynorc4889812015-09-04 08:43:17 -0400178OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800179
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180VERIFY_PEER = _lib.SSL_VERIFY_PEER
181VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
182VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
183VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800184
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500185SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
186SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
187SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
188SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
189SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
190SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
191SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
192SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800193
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500194SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
195SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
196SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400197if _lib.Cryptography_HAS_SSL_ST:
198 SSL_ST_INIT = _lib.SSL_ST_INIT
199 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
200 SSL_ST_OK = _lib.SSL_ST_OK
201 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100202 __all__.extend([
203 'SSL_ST_INIT',
204 'SSL_ST_BEFORE',
205 'SSL_ST_OK',
206 'SSL_ST_RENEGOTIATE',
207 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800208
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500209SSL_CB_LOOP = _lib.SSL_CB_LOOP
210SSL_CB_EXIT = _lib.SSL_CB_EXIT
211SSL_CB_READ = _lib.SSL_CB_READ
212SSL_CB_WRITE = _lib.SSL_CB_WRITE
213SSL_CB_ALERT = _lib.SSL_CB_ALERT
214SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
215SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
216SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
217SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
218SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
219SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
220SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
221SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800222
Paul Kehrer55fb3412017-06-29 18:44:08 -0500223# Taken from https://golang.org/src/crypto/x509/root_linux.go
224_CERTIFICATE_FILE_LOCATIONS = [
225 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
226 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
227 "/etc/ssl/ca-bundle.pem", # OpenSUSE
228 "/etc/pki/tls/cacert.pem", # OpenELEC
229 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
230]
231
232_CERTIFICATE_PATH_LOCATIONS = [
233 "/etc/ssl/certs", # SLES10/SLES11
234]
235
Paul Kehrera92a1a72017-07-19 15:53:23 +0200236# These values are compared to output from cffi's ffi.string so they must be
237# byte strings.
238_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
239_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500240
Alex Gaynor83284952015-09-05 10:43:30 -0400241
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500242class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500243 """
244 An error occurred in an `OpenSSL.SSL` API.
245 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500246
247
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500248_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100249_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500250
251
252class WantReadError(Error):
253 pass
254
255
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500256class WantWriteError(Error):
257 pass
258
259
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500260class WantX509LookupError(Error):
261 pass
262
263
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500264class ZeroReturnError(Error):
265 pass
266
267
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500268class SysCallError(Error):
269 pass
270
271
Cory Benfield0ea76e72015-03-22 09:05:28 +0000272class _CallbackExceptionHelper(object):
273 """
274 A base class for wrapper classes that allow for intelligent exception
275 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500276
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400277 :ivar list _problems: Any exceptions that occurred while executing in a
278 context where they could not be raised in the normal way. Typically
279 this is because OpenSSL has called into some Python code and requires a
280 return value. The exceptions are saved to be raised later when it is
281 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000282 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400283
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400284 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800285 self._problems = []
286
Cory Benfield0ea76e72015-03-22 09:05:28 +0000287 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400288 """
289 Raise an exception from the OpenSSL error queue or that was previously
290 captured whe running a callback.
291 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292 if self._problems:
293 try:
294 _raise_current_error()
295 except Error:
296 pass
297 raise self._problems.pop(0)
298
299
300class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400301 """
302 Wrap a callback such that it can be used as a certificate verification
303 callback.
304 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400305
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800306 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400307 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800308
309 @wraps(callback)
310 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800311 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
312 _lib.X509_up_ref(x509)
313 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500314 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
315 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800316
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400317 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
318 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
319 connection = Connection._reverse_mapping[ssl]
320
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800321 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400322 result = callback(
323 connection, cert, error_number, error_depth, ok
324 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325 except Exception as e:
326 self._problems.append(e)
327 return 0
328 else:
329 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500330 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800331 return 1
332 else:
333 return 0
334
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500335 self.callback = _ffi.callback(
336 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800337
338
Cory Benfield0ea76e72015-03-22 09:05:28 +0000339class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400340 """
341 Wrap a callback such that it can be used as an NPN advertisement callback.
342 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400343
Cory Benfield0ea76e72015-03-22 09:05:28 +0000344 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400345 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800346
Cory Benfield0ea76e72015-03-22 09:05:28 +0000347 @wraps(callback)
348 def wrapper(ssl, out, outlen, arg):
349 try:
350 conn = Connection._reverse_mapping[ssl]
351 protos = callback(conn)
352
353 # Join the protocols into a Python bytestring, length-prefixing
354 # each element.
355 protostr = b''.join(
356 chain.from_iterable((int2byte(len(p)), p) for p in protos)
357 )
358
359 # Save our callback arguments on the connection object. This is
360 # done to make sure that they don't get freed before OpenSSL
361 # uses them. Then, return them appropriately in the output
362 # parameters.
363 conn._npn_advertise_callback_args = [
364 _ffi.new("unsigned int *", len(protostr)),
365 _ffi.new("unsigned char[]", protostr),
366 ]
367 outlen[0] = conn._npn_advertise_callback_args[0][0]
368 out[0] = conn._npn_advertise_callback_args[1]
369 return 0
370 except Exception as e:
371 self._problems.append(e)
372 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
373
374 self.callback = _ffi.callback(
375 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
376 wrapper
377 )
378
379
380class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400381 """
382 Wrap a callback such that it can be used as an NPN selection callback.
383 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400384
Cory Benfield0ea76e72015-03-22 09:05:28 +0000385 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400386 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000387
388 @wraps(callback)
389 def wrapper(ssl, out, outlen, in_, inlen, arg):
390 try:
391 conn = Connection._reverse_mapping[ssl]
392
393 # The string passed to us is actually made up of multiple
394 # length-prefixed bytestrings. We need to split that into a
395 # list.
396 instr = _ffi.buffer(in_, inlen)[:]
397 protolist = []
398 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500399 length = indexbytes(instr, 0)
400 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000401 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500402 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000403
404 # Call the callback
405 outstr = callback(conn, protolist)
406
407 # Save our callback arguments on the connection object. This is
408 # done to make sure that they don't get freed before OpenSSL
409 # uses them. Then, return them appropriately in the output
410 # parameters.
411 conn._npn_select_callback_args = [
412 _ffi.new("unsigned char *", len(outstr)),
413 _ffi.new("unsigned char[]", outstr),
414 ]
415 outlen[0] = conn._npn_select_callback_args[0][0]
416 out[0] = conn._npn_select_callback_args[1]
417 return 0
418 except Exception as e:
419 self._problems.append(e)
420 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
421
422 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400423 ("int (*)(SSL *, unsigned char **, unsigned char *, "
424 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000425 wrapper
426 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800427
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800428
Mark Williams5d890a02019-11-17 19:56:26 -0800429NO_OVERLAPPING_PROTOCOLS = object()
430
431
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400432class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400433 """
434 Wrap a callback such that it can be used as an ALPN selection callback.
435 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400436
Cory Benfieldf1177e72015-04-12 09:11:49 -0400437 def __init__(self, callback):
438 _CallbackExceptionHelper.__init__(self)
439
440 @wraps(callback)
441 def wrapper(ssl, out, outlen, in_, inlen, arg):
442 try:
443 conn = Connection._reverse_mapping[ssl]
444
445 # The string passed to us is made up of multiple
446 # length-prefixed bytestrings. We need to split that into a
447 # list.
448 instr = _ffi.buffer(in_, inlen)[:]
449 protolist = []
450 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400451 encoded_len = indexbytes(instr, 0)
452 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400453 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400454 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400455
456 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800457 outbytes = callback(conn, protolist)
458 any_accepted = True
459 if outbytes is NO_OVERLAPPING_PROTOCOLS:
460 outbytes = b''
461 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500462 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800463 raise TypeError(
464 "ALPN callback must return a bytestring or the "
465 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
466 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400467
468 # Save our callback arguments on the connection object to make
469 # sure that they don't get freed before OpenSSL can use them.
470 # Then, return them in the appropriate output parameters.
471 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800472 _ffi.new("unsigned char *", len(outbytes)),
473 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400474 ]
475 outlen[0] = conn._alpn_select_callback_args[0][0]
476 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800477 if not any_accepted:
478 return _lib.SSL_TLSEXT_ERR_NOACK
479 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400480 except Exception as e:
481 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800482 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400483
484 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400485 ("int (*)(SSL *, unsigned char **, unsigned char *, "
486 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400487 wrapper
488 )
489
490
Cory Benfield496652a2017-01-24 11:42:56 +0000491class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
492 """
493 Wrap a callback such that it can be used as an OCSP callback for the server
494 side.
495
496 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
497 ways. For servers, that callback is expected to retrieve some OCSP data and
498 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
499 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
500 is expected to check the OCSP data, and returns a negative value on error,
501 0 if the response is not acceptable, or positive if it is. These are
502 mutually exclusive return code behaviours, and they mean that we need two
503 helpers so that we always return an appropriate error code if the user's
504 code throws an exception.
505
506 Given that we have to have two helpers anyway, these helpers are a bit more
507 helpery than most: specifically, they hide a few more of the OpenSSL
508 functions so that the user has an easier time writing these callbacks.
509
510 This helper implements the server side.
511 """
512
513 def __init__(self, callback):
514 _CallbackExceptionHelper.__init__(self)
515
516 @wraps(callback)
517 def wrapper(ssl, cdata):
518 try:
519 conn = Connection._reverse_mapping[ssl]
520
521 # Extract the data if any was provided.
522 if cdata != _ffi.NULL:
523 data = _ffi.from_handle(cdata)
524 else:
525 data = None
526
527 # Call the callback.
528 ocsp_data = callback(conn, data)
529
Alex Gaynor12576002019-11-18 00:18:50 -0500530 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000531 raise TypeError("OCSP callback must return a bytestring.")
532
533 # If the OCSP data was provided, we will pass it to OpenSSL.
534 # However, we have an early exit here: if no OCSP data was
535 # provided we will just exit out and tell OpenSSL that there
536 # is nothing to do.
537 if not ocsp_data:
538 return 3 # SSL_TLSEXT_ERR_NOACK
539
David Benjamin7ac5f272018-05-21 21:24:04 -0400540 # OpenSSL takes ownership of this data and expects it to have
541 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000542 ocsp_data_length = len(ocsp_data)
543 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
544 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
545
546 _lib.SSL_set_tlsext_status_ocsp_resp(
547 ssl, data_ptr, ocsp_data_length
548 )
549
550 return 0
551 except Exception as e:
552 self._problems.append(e)
553 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
554
555 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
556
557
558class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
559 """
560 Wrap a callback such that it can be used as an OCSP callback for the client
561 side.
562
563 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
564 ways. For servers, that callback is expected to retrieve some OCSP data and
565 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
566 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
567 is expected to check the OCSP data, and returns a negative value on error,
568 0 if the response is not acceptable, or positive if it is. These are
569 mutually exclusive return code behaviours, and they mean that we need two
570 helpers so that we always return an appropriate error code if the user's
571 code throws an exception.
572
573 Given that we have to have two helpers anyway, these helpers are a bit more
574 helpery than most: specifically, they hide a few more of the OpenSSL
575 functions so that the user has an easier time writing these callbacks.
576
577 This helper implements the client side.
578 """
579
580 def __init__(self, callback):
581 _CallbackExceptionHelper.__init__(self)
582
583 @wraps(callback)
584 def wrapper(ssl, cdata):
585 try:
586 conn = Connection._reverse_mapping[ssl]
587
588 # Extract the data if any was provided.
589 if cdata != _ffi.NULL:
590 data = _ffi.from_handle(cdata)
591 else:
592 data = None
593
594 # Get the OCSP data.
595 ocsp_ptr = _ffi.new("unsigned char **")
596 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
597 if ocsp_len < 0:
598 # No OCSP data.
599 ocsp_data = b''
600 else:
601 # Copy the OCSP data, then pass it to the callback.
602 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
603
604 valid = callback(conn, ocsp_data, data)
605
606 # Return 1 on success or 0 on error.
607 return int(bool(valid))
608
609 except Exception as e:
610 self._problems.append(e)
611 # Return negative value if an exception is hit.
612 return -1
613
614 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
615
616
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800617def _asFileDescriptor(obj):
618 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800619 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800620 meth = getattr(obj, "fileno", None)
621 if meth is not None:
622 obj = meth()
623
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800624 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800625 fd = obj
626
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800627 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800628 raise TypeError("argument must be an int, or have a fileno() method.")
629 elif fd < 0:
630 raise ValueError(
631 "file descriptor cannot be a negative integer (%i)" % (fd,))
632
633 return fd
634
635
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800636def SSLeay_version(type):
637 """
638 Return a string describing the version of OpenSSL in use.
639
Alex Chand072cae2018-02-15 09:57:59 +0000640 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800641 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500642 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800643
644
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500645def _warn_npn():
646 warnings.warn("NPN is deprecated. Protocols should switch to using ALPN.",
647 DeprecationWarning, stacklevel=3)
648
649
Cory Benfieldef404df2016-03-29 15:32:48 +0100650def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400651 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100652 Builds a decorator that ensures that functions that rely on OpenSSL
653 functions that are not present in this build raise NotImplementedError,
654 rather than AttributeError coming out of cryptography.
655
656 :param flag: A cryptography flag that guards the functions, e.g.
657 ``Cryptography_HAS_NEXTPROTONEG``.
658 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400659 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100660 def _requires_decorator(func):
661 if not flag:
662 @wraps(func)
663 def explode(*args, **kwargs):
664 raise NotImplementedError(error)
665 return explode
666 else:
667 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400668
Cory Benfieldef404df2016-03-29 15:32:48 +0100669 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400670
671
Cory Benfieldef404df2016-03-29 15:32:48 +0100672_requires_npn = _make_requires(
673 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
674)
Cory Benfield7907e332015-04-13 17:18:25 -0400675
676
Cory Benfieldef404df2016-03-29 15:32:48 +0100677_requires_alpn = _make_requires(
678 _lib.Cryptography_HAS_ALPN, "ALPN not available"
679)
Cory Benfielde6f35882016-03-29 11:21:04 +0100680
Cory Benfielde6f35882016-03-29 11:21:04 +0100681
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800682class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000683 """
684 A class representing an SSL session. A session defines certain connection
685 parameters which may be re-used to speed up the setup of subsequent
686 connections.
687
688 .. versionadded:: 0.14
689 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800690 pass
691
692
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693class Context(object):
694 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100695 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400696 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000697
698 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
699 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800700 """
701 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800702 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500703 SSLv3_METHOD: "SSLv3_method",
704 SSLv23_METHOD: "SSLv23_method",
705 TLSv1_METHOD: "TLSv1_method",
706 TLSv1_1_METHOD: "TLSv1_1_method",
707 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400708 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500709 _methods = dict(
710 (identifier, getattr(_lib, name))
711 for (identifier, name) in _methods.items()
712 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713
714 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500715 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716 raise TypeError("method must be an integer")
717
718 try:
719 method_func = self._methods[method]
720 except KeyError:
721 raise ValueError("No such protocol")
722
723 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700724 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800725
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700727 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500728 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600730 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
731 # will be auto-selected. This function was added in 1.0.2 and made a
732 # noop in 1.1.0+ (where it is set automatically).
733 try:
734 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
735 _openssl_assert(res == 1)
736 except AttributeError:
737 pass
738
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800739 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800740 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800742 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800743 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744 self._verify_callback = None
745 self._info_callback = None
746 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800747 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000748 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100749 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000750 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100751 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400752 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100753 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000754 self._ocsp_helper = None
755 self._ocsp_callback = None
756 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500758 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800759
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800760 def load_verify_locations(self, cafile, capath=None):
761 """
762 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000763 chain. Note that the certificates have to be in PEM format.
764
765 If capath is passed, it must be a directory prepared using the
766 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
767 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800768
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400769 :param cafile: In which file we can find the certificates (``bytes`` or
770 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800771 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400772 (``bytes`` or ``unicode``).
773
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800774 :return: None
775 """
776 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500777 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400778 else:
779 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780
781 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500782 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400783 else:
784 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785
Alex Gaynor62da94d2015-09-05 14:37:34 -0400786 load_result = _lib.SSL_CTX_load_verify_locations(
787 self._context, cafile, capath
788 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500790 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792 def _wrap_callback(self, callback):
793 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800794 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800795 return callback(size, verify, self._passphrase_userdata)
796 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800797 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800799 def set_passwd_cb(self, callback, userdata=None):
800 """
Alex Chand072cae2018-02-15 09:57:59 +0000801 Set the passphrase callback. This function will be called
802 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800803
Alex Chand072cae2018-02-15 09:57:59 +0000804 :param callback: The Python callback to use. This must accept three
805 positional arguments. First, an integer giving the maximum length
806 of the passphrase it may return. If the returned passphrase is
807 longer than this, it will be truncated. Second, a boolean value
808 which will be true if the user should be prompted for the
809 passphrase twice and the callback should verify that the two values
810 supplied are equal. Third, the value given as the *userdata*
811 parameter to :meth:`set_passwd_cb`. The *callback* must return
812 a byte string. If an error occurs, *callback* should return a false
813 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814 :param userdata: (optional) A Python object which will be given as
815 argument to the callback
816 :return: None
817 """
818 if not callable(callback):
819 raise TypeError("callback must be callable")
820
821 self._passphrase_helper = self._wrap_callback(callback)
822 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500823 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800824 self._context, self._passphrase_callback)
825 self._passphrase_userdata = userdata
826
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800827 def set_default_verify_paths(self):
828 """
Alex Chand072cae2018-02-15 09:57:59 +0000829 Specify that the platform provided CA certificates are to be used for
830 verification purposes. This method has some caveats related to the
831 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
832
833 * macOS will only load certificates using this method if the user has
834 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
835 in the default location.
836 * Windows will not work.
837 * manylinux1 cryptography wheels will work on most common Linux
838 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
839 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800840
841 :return: None
842 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500843 # SSL_CTX_set_default_verify_paths will attempt to load certs from
844 # both a cafile and capath that are set at compile time. However,
845 # it will first check environment variables and, if present, load
846 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500847 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400848 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500849 # After attempting to set default_verify_paths we need to know whether
850 # to go down the fallback path.
851 # First we'll check to see if any env vars have been set. If so,
852 # we won't try to do anything else because the user has set the path
853 # themselves.
854 dir_env_var = _ffi.string(
855 _lib.X509_get_default_cert_dir_env()
856 ).decode("ascii")
857 file_env_var = _ffi.string(
858 _lib.X509_get_default_cert_file_env()
859 ).decode("ascii")
860 if not self._check_env_vars_set(dir_env_var, file_env_var):
861 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
862 default_file = _ffi.string(_lib.X509_get_default_cert_file())
863 # Now we check to see if the default_dir and default_file are set
864 # to the exact values we use in our manylinux1 builds. If they are
865 # then we know to load the fallbacks
866 if (
867 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
868 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
869 ):
870 # This is manylinux1, let's load our fallback paths
871 self._fallback_default_verify_paths(
872 _CERTIFICATE_FILE_LOCATIONS,
873 _CERTIFICATE_PATH_LOCATIONS
874 )
875
876 def _check_env_vars_set(self, dir_env_var, file_env_var):
877 """
878 Check to see if the default cert dir/file environment vars are present.
879
880 :return: bool
881 """
882 return (
883 os.environ.get(file_env_var) is not None or
884 os.environ.get(dir_env_var) is not None
885 )
886
887 def _fallback_default_verify_paths(self, file_path, dir_path):
888 """
889 Default verify paths are based on the compiled version of OpenSSL.
890 However, when pyca/cryptography is compiled as a manylinux1 wheel
891 that compiled location can potentially be wrong. So, like Go, we
892 will try a predefined set of paths and attempt to load roots
893 from there.
894
895 :return: None
896 """
897 for cafile in file_path:
898 if os.path.isfile(cafile):
899 self.load_verify_locations(cafile)
900 break
901
902 for capath in dir_path:
903 if os.path.isdir(capath):
904 self.load_verify_locations(None, capath)
905 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800906
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 def use_certificate_chain_file(self, certfile):
908 """
Alex Chand072cae2018-02-15 09:57:59 +0000909 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400911 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000912 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400913
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800914 :return: None
915 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400916 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800917
Alex Gaynor62da94d2015-09-05 14:37:34 -0400918 result = _lib.SSL_CTX_use_certificate_chain_file(
919 self._context, certfile
920 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800921 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500922 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800923
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800924 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925 """
926 Load a certificate from a file
927
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400928 :param certfile: The name of the certificate file (``bytes`` or
929 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000930 :param filetype: (optional) The encoding of the file, which is either
931 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
932 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400933
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934 :return: None
935 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400936 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500937 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800938 raise TypeError("filetype must be an integer")
939
Alex Gaynor62da94d2015-09-05 14:37:34 -0400940 use_result = _lib.SSL_CTX_use_certificate_file(
941 self._context, certfile, filetype
942 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800943 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500944 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800945
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946 def use_certificate(self, cert):
947 """
948 Load a certificate from a X509 object
949
950 :param cert: The X509 object
951 :return: None
952 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800953 if not isinstance(cert, X509):
954 raise TypeError("cert must be an X509 instance")
955
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500956 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800957 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500958 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800959
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960 def add_extra_chain_cert(self, certobj):
961 """
962 Add certificate to chain
963
964 :param certobj: The X509 certificate object to add to the chain
965 :return: None
966 """
967 if not isinstance(certobj, X509):
968 raise TypeError("certobj must be an X509 instance")
969
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500970 copy = _lib.X509_dup(certobj._x509)
971 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800972 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500973 # TODO: This is untested.
974 _lib.X509_free(copy)
975 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800976
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800977 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500978 if self._passphrase_helper is not None:
979 self._passphrase_helper.raise_if_problem(Error)
980
981 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800982
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400983 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984 """
985 Load a private key from a file
986
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400987 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000988 :param filetype: (optional) The encoding of the file, which is either
989 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
990 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400991
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992 :return: None
993 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400994 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400996 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500998 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 raise TypeError("filetype must be an integer")
1000
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001001 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001002 self._context, keyfile, filetype)
1003 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001004 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001005
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006 def use_privatekey(self, pkey):
1007 """
1008 Load a private key from a PKey object
1009
1010 :param pkey: The PKey object
1011 :return: None
1012 """
1013 if not isinstance(pkey, PKey):
1014 raise TypeError("pkey must be a PKey instance")
1015
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001016 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001018 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001019
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020 def check_privatekey(self):
1021 """
Alex Chand072cae2018-02-15 09:57:59 +00001022 Check if the private key (loaded with :meth:`use_privatekey`) matches
1023 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001024
Alex Chand072cae2018-02-15 09:57:59 +00001025 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001027 if not _lib.SSL_CTX_check_private_key(self._context):
1028 _raise_current_error()
1029
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001030 def load_client_ca(self, cafile):
1031 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001032 Load the trusted certificates that will be sent to the client. Does
1033 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001034 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001036 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001037 :return: None
1038 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001039 ca_list = _lib.SSL_load_client_CA_file(
1040 _text_to_bytes_and_warn("cafile", cafile)
1041 )
1042 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001043 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044
1045 def set_session_id(self, buf):
1046 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001047 Set the session id to *buf* within which a session can be reused for
1048 this Context object. This is needed when doing session resumption,
1049 because there is no way for a stored session to know which Context
1050 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001052 :param bytes buf: The session id.
1053
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054 :returns: None
1055 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001056 buf = _text_to_bytes_and_warn("buf", buf)
1057 _openssl_assert(
1058 _lib.SSL_CTX_set_session_id_context(
1059 self._context,
1060 buf,
1061 len(buf),
1062 ) == 1
1063 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064
1065 def set_session_cache_mode(self, mode):
1066 """
Alex Chand072cae2018-02-15 09:57:59 +00001067 Set the behavior of the session cache used by all connections using
1068 this Context. The previously set mode is returned. See
1069 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070
1071 :param mode: One or more of the SESS_CACHE_* flags (combine using
1072 bitwise or)
1073 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001074
1075 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001077 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001078 raise TypeError("mode must be an integer")
1079
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001080 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001081
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082 def get_session_cache_mode(self):
1083 """
Alex Chand072cae2018-02-15 09:57:59 +00001084 Get the current session cache mode.
1085
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001087
1088 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001089 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001092 def set_verify(self, mode, callback):
1093 """
Alex Chand072cae2018-02-15 09:57:59 +00001094 et the verification flags for this Context object to *mode* and specify
1095 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096
Alex Chand072cae2018-02-15 09:57:59 +00001097 :param mode: The verify mode, this should be one of
1098 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1099 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1100 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1101 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1102 :param callback: The Python callback to use. This should take five
1103 arguments: A Connection object, an X509 object, and three integer
1104 variables, which are in turn potential error number, error depth
1105 and return code. *callback* should return True if verification
1106 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107 :return: None
1108
1109 See SSL_CTX_set_verify(3SSL) for further details.
1110 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001111 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001112 raise TypeError("mode must be an integer")
1113
1114 if not callable(callback):
1115 raise TypeError("callback must be callable")
1116
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001117 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001118 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001119 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001120
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001121 def set_verify_depth(self, depth):
1122 """
Alex Chand072cae2018-02-15 09:57:59 +00001123 Set the maximum depth for the certificate chain verification that shall
1124 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001125
1126 :param depth: An integer specifying the verify depth
1127 :return: None
1128 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001129 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001130 raise TypeError("depth must be an integer")
1131
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001132 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001133
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001134 def get_verify_mode(self):
1135 """
Alex Chand072cae2018-02-15 09:57:59 +00001136 Retrieve the Context object's verify mode, as set by
1137 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138
1139 :return: The verify mode
1140 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143 def get_verify_depth(self):
1144 """
Alex Chand072cae2018-02-15 09:57:59 +00001145 Retrieve the Context object's verify depth, as set by
1146 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147
1148 :return: The verify depth
1149 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001150 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001151
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001152 def load_tmp_dh(self, dhfile):
1153 """
1154 Load parameters for Ephemeral Diffie-Hellman
1155
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001156 :param dhfile: The file to load EDH parameters from (``bytes`` or
1157 ``unicode``).
1158
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001159 :return: None
1160 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001161 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001162
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001163 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001164 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001165 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001167
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1169 dh = _ffi.gc(dh, _lib.DH_free)
1170 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001171
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001172 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001173 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001174 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001175
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001176 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001177 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1178 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001179
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001180 :return: None
1181 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001182 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001183
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184 def set_cipher_list(self, cipher_list):
1185 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001186 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001187
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001188 See the OpenSSL manual for more information (e.g.
1189 :manpage:`ciphers(1)`).
1190
1191 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001192 :return: None
1193 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001194 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001195
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001196 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001197 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001198
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001199 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001200 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001201 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001202 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1203 # ciphers even if you pass an invalid cipher. Applications (like
1204 # Twisted) have tests that depend on an error being raised if an
1205 # invalid cipher string is passed, but without the following check
1206 # for the TLS 1.3 specific cipher suites it would never error.
1207 tmpconn = Connection(self, None)
Mark Williamsdf2480d2019-02-14 19:30:07 -08001208 if (
1209 tmpconn.get_cipher_list() == [
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001210 'TLS_AES_256_GCM_SHA384',
1211 'TLS_CHACHA20_POLY1305_SHA256',
1212 'TLS_AES_128_GCM_SHA256'
1213 ]
Mark Williamsdf2480d2019-02-14 19:30:07 -08001214 ):
1215 raise Error(
1216 [
1217 (
1218 'SSL routines',
1219 'SSL_CTX_set_cipher_list',
1220 'no cipher match',
1221 ),
1222 ],
1223 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001224
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001225 def set_client_ca_list(self, certificate_authorities):
1226 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001227 Set the list of preferred client certificate signers for this server
1228 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001229
Alex Gaynor62da94d2015-09-05 14:37:34 -04001230 This list of certificate authorities will be sent to the client when
1231 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001232
1233 :param certificate_authorities: a sequence of X509Names.
1234 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001235
1236 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001237 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001238 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001239 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001240
1241 try:
1242 for ca_name in certificate_authorities:
1243 if not isinstance(ca_name, X509Name):
1244 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001245 "client CAs must be X509Name objects, not %s "
1246 "objects" % (
1247 type(ca_name).__name__,
1248 )
1249 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001250 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001251 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001252 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001253 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001254 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001255 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001256 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001257 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001258 raise
1259
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001260 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001261
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001262 def add_client_ca(self, certificate_authority):
1263 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001264 Add the CA certificate to the list of preferred signers for this
1265 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001266
1267 The list of certificate authorities will be sent to the client when the
1268 server requests a client certificate.
1269
1270 :param certificate_authority: certificate authority's X509 certificate.
1271 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001272
1273 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001274 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001275 if not isinstance(certificate_authority, X509):
1276 raise TypeError("certificate_authority must be an X509 instance")
1277
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001279 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001280 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282 def set_timeout(self, timeout):
1283 """
Alex Chand072cae2018-02-15 09:57:59 +00001284 Set the timeout for newly created sessions for this Context object to
1285 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1286 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287
Alex Chand072cae2018-02-15 09:57:59 +00001288 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001289 :return: The previous session timeout
1290 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001291 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001292 raise TypeError("timeout must be an integer")
1293
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001294 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001295
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296 def get_timeout(self):
1297 """
Alex Chand072cae2018-02-15 09:57:59 +00001298 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1299 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001300
1301 :return: The session timeout
1302 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001304
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001305 def set_info_callback(self, callback):
1306 """
Alex Chand072cae2018-02-15 09:57:59 +00001307 Set the information callback to *callback*. This function will be
1308 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309
Alex Chand072cae2018-02-15 09:57:59 +00001310 :param callback: The Python callback to use. This should take three
1311 arguments: a Connection object and two integers. The first integer
1312 specifies where in the SSL handshake the function was called, and
1313 the other the return code from a (possibly failed) internal
1314 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001315 :return: None
1316 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001317 @wraps(callback)
1318 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001319 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 self._info_callback = _ffi.callback(
1321 "void (*)(const SSL *, int, int)", wrapper)
1322 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001323
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001324 def get_app_data(self):
1325 """
Alex Chand072cae2018-02-15 09:57:59 +00001326 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001327
1328 :return: The application data
1329 """
1330 return self._app_data
1331
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001332 def set_app_data(self, data):
1333 """
1334 Set the application data (will be returned from get_app_data())
1335
1336 :param data: Any Python object
1337 :return: None
1338 """
1339 self._app_data = data
1340
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001341 def get_cert_store(self):
1342 """
Alex Chand072cae2018-02-15 09:57:59 +00001343 Get the certificate store for the context. This can be used to add
1344 "trusted" certificates without using the
1345 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001346
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001347 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001348 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001349 store = _lib.SSL_CTX_get_cert_store(self._context)
1350 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001351 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001352 return None
1353
1354 pystore = X509Store.__new__(X509Store)
1355 pystore._store = store
1356 return pystore
1357
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358 def set_options(self, options):
1359 """
1360 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001361 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001362
1363 :param options: The options to add.
1364 :return: The new option bitmask.
1365 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001366 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001367 raise TypeError("options must be an integer")
1368
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001369 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001370
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001371 def set_mode(self, mode):
1372 """
Alex Chand072cae2018-02-15 09:57:59 +00001373 Add modes via bitmask. Modes set before are not cleared! This method
1374 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001375
1376 :param mode: The mode to add.
1377 :return: The new mode bitmask.
1378 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001379 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001380 raise TypeError("mode must be an integer")
1381
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001382 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001383
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001384 def set_tlsext_servername_callback(self, callback):
1385 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001386 Specify a callback function to be called when clients specify a server
1387 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001388
1389 :param callback: The callback function. It will be invoked with one
1390 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001391
1392 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001393 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001394 @wraps(callback)
1395 def wrapper(ssl, alert, arg):
1396 callback(Connection._reverse_mapping[ssl])
1397 return 0
1398
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001399 self._tlsext_servername_callback = _ffi.callback(
David Benjamince5c3842018-05-21 21:14:46 -04001400 "int (*)(SSL *, int *, void *)", wrapper)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001402 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001403
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001404 def set_tlsext_use_srtp(self, profiles):
1405 """
1406 Enable support for negotiating SRTP keying material.
1407
1408 :param bytes profiles: A colon delimited list of protection profile
1409 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1410 :return: None
1411 """
1412 if not isinstance(profiles, bytes):
1413 raise TypeError("profiles must be a byte string.")
1414
1415 _openssl_assert(
1416 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1417 )
1418
Cory Benfield10b277f2015-04-13 17:12:42 -04001419 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001420 def set_npn_advertise_callback(self, callback):
1421 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001422 Specify a callback function that will be called when offering `Next
1423 Protocol Negotiation
1424 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001425
1426 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001427 argument, the :class:`Connection` instance. It should return a
1428 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001429 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001430
1431 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001432 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001433 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001434 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1435 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001436 _lib.SSL_CTX_set_next_protos_advertised_cb(
1437 self._context, self._npn_advertise_callback, _ffi.NULL)
1438
Cory Benfield10b277f2015-04-13 17:12:42 -04001439 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001440 def set_npn_select_callback(self, callback):
1441 """
1442 Specify a callback function that will be called when a server offers
1443 Next Protocol Negotiation options.
1444
1445 :param callback: The callback function. It will be invoked with two
1446 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001447 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1448 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001449
1450 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001451 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001452 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001453 self._npn_select_helper = _NpnSelectHelper(callback)
1454 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001455 _lib.SSL_CTX_set_next_proto_select_cb(
1456 self._context, self._npn_select_callback, _ffi.NULL)
1457
Cory Benfield7907e332015-04-13 17:18:25 -04001458 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001459 def set_alpn_protos(self, protos):
1460 """
Alex Chand072cae2018-02-15 09:57:59 +00001461 Specify the protocols that the client is prepared to speak after the
1462 TLS connection has been negotiated using Application Layer Protocol
1463 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001464
1465 :param protos: A list of the protocols to be offered to the server.
1466 This list should be a Python list of bytestrings representing the
1467 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1468 """
1469 # Take the list of protocols and join them together, prefixing them
1470 # with their lengths.
1471 protostr = b''.join(
1472 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1473 )
1474
1475 # Build a C string from the list. We don't need to save this off
1476 # because OpenSSL immediately copies the data out.
1477 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001478 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001479
Cory Benfield7907e332015-04-13 17:18:25 -04001480 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001481 def set_alpn_select_callback(self, callback):
1482 """
Alex Chand072cae2018-02-15 09:57:59 +00001483 Specify a callback function that will be called on the server when a
1484 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001485
1486 :param callback: The callback function. It will be invoked with two
1487 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001488 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1489 one of those bytestrings to indicate the chosen protocol, the
1490 empty bytestring to terminate the TLS connection, or the
1491 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1492 protocol was selected, but that the connection should not be
1493 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001494 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001495 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001496 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001497 _lib.SSL_CTX_set_alpn_select_cb(
1498 self._context, self._alpn_select_callback, _ffi.NULL)
1499
Cory Benfield496652a2017-01-24 11:42:56 +00001500 def _set_ocsp_callback(self, helper, data):
1501 """
1502 This internal helper does the common work for
1503 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1504 almost all of it.
1505 """
1506 self._ocsp_helper = helper
1507 self._ocsp_callback = helper.callback
1508 if data is None:
1509 self._ocsp_data = _ffi.NULL
1510 else:
1511 self._ocsp_data = _ffi.new_handle(data)
1512
1513 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1514 self._context, self._ocsp_callback
1515 )
1516 _openssl_assert(rc == 1)
1517 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1518 _openssl_assert(rc == 1)
1519
1520 def set_ocsp_server_callback(self, callback, data=None):
1521 """
1522 Set a callback to provide OCSP data to be stapled to the TLS handshake
1523 on the server side.
1524
1525 :param callback: The callback function. It will be invoked with two
1526 arguments: the Connection, and the optional arbitrary data you have
1527 provided. The callback must return a bytestring that contains the
1528 OCSP data to staple to the handshake. If no OCSP data is available
1529 for this connection, return the empty bytestring.
1530 :param data: Some opaque data that will be passed into the callback
1531 function when called. This can be used to avoid needing to do
1532 complex data lookups or to keep track of what context is being
1533 used. This parameter is optional.
1534 """
1535 helper = _OCSPServerCallbackHelper(callback)
1536 self._set_ocsp_callback(helper, data)
1537
1538 def set_ocsp_client_callback(self, callback, data=None):
1539 """
1540 Set a callback to validate OCSP data stapled to the TLS handshake on
1541 the client side.
1542
1543 :param callback: The callback function. It will be invoked with three
1544 arguments: the Connection, a bytestring containing the stapled OCSP
1545 assertion, and the optional arbitrary data you have provided. The
1546 callback must return a boolean that indicates the result of
1547 validating the OCSP data: ``True`` if the OCSP data is valid and
1548 the certificate can be trusted, or ``False`` if either the OCSP
1549 data is invalid or the certificate has been revoked.
1550 :param data: Some opaque data that will be passed into the callback
1551 function when called. This can be used to avoid needing to do
1552 complex data lookups or to keep track of what context is being
1553 used. This parameter is optional.
1554 """
1555 helper = _OCSPClientCallbackHelper(callback)
1556 self._set_ocsp_callback(helper, data)
1557
Alex Chanc6077062016-11-18 13:53:39 +00001558
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559class Connection(object):
1560 """
1561 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001562 _reverse_mapping = WeakValueDictionary()
1563
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001564 def __init__(self, context, socket=None):
1565 """
1566 Create a new Connection object, using the given OpenSSL.SSL.Context
1567 instance and socket.
1568
1569 :param context: An SSL Context to use for this connection
1570 :param socket: The socket to use for transport layer
1571 """
1572 if not isinstance(context, Context):
1573 raise TypeError("context must be a Context instance")
1574
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001575 ssl = _lib.SSL_new(context._context)
1576 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001577 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1578 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1579 # even though there is still data on the underlying transport.
1580 # See https://github.com/openssl/openssl/issues/6234 for more details.
1581 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001583 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001585 # References to strings used for Next Protocol Negotiation. OpenSSL's
1586 # header files suggest that these might get copied at some point, but
1587 # doesn't specify when, so we store them here to make sure they don't
1588 # get freed before OpenSSL uses them.
1589 self._npn_advertise_callback_args = None
1590 self._npn_select_callback_args = None
1591
Cory Benfield12eae892014-06-07 15:42:56 +01001592 # References to strings used for Application Layer Protocol
1593 # Negotiation. These strings get copied at some point but it's well
1594 # after the callback returns, so we have to hang them somewhere to
1595 # avoid them getting freed.
1596 self._alpn_select_callback_args = None
1597
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001598 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001599
1600 if socket is None:
1601 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001602 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001604 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001605
Alex Gaynora829e902016-06-04 18:16:01 -07001606 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1607 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001609 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001611 self._into_ssl = None
1612 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001613 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001614 set_result = _lib.SSL_set_fd(
1615 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001616 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001617
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001618 def __getattr__(self, name):
1619 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001620 Look up attributes on the wrapped socket object if they are not found
1621 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001622 """
kjav0b66fa12015-09-02 11:51:26 +01001623 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001624 raise AttributeError("'%s' object has no attribute '%s'" % (
1625 self.__class__.__name__, name
1626 ))
kjav0b66fa12015-09-02 11:51:26 +01001627 else:
1628 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001630 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001631 if self._context._verify_helper is not None:
1632 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001633 if self._context._npn_advertise_helper is not None:
1634 self._context._npn_advertise_helper.raise_if_problem()
1635 if self._context._npn_select_helper is not None:
1636 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001637 if self._context._alpn_select_helper is not None:
1638 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001639 if self._context._ocsp_helper is not None:
1640 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001641
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001642 error = _lib.SSL_get_error(ssl, result)
1643 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001644 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001645 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001646 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001647 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001648 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001649 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001650 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001651 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001652 elif error == _lib.SSL_ERROR_SYSCALL:
1653 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001654 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001655 if platform == "win32":
1656 errno = _ffi.getwinerror()[0]
1657 else:
1658 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001659
1660 if errno != 0:
1661 raise SysCallError(errno, errorcode.get(errno))
1662 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001663 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001664 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001665 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001666 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001667 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001668 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001669 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671 def get_context(self):
1672 """
Alex Chand072cae2018-02-15 09:57:59 +00001673 Retrieve the :class:`Context` object associated with this
1674 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001675 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001676 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679 """
Alex Chand072cae2018-02-15 09:57:59 +00001680 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001681
Alex Chand072cae2018-02-15 09:57:59 +00001682 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001683 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001685 if not isinstance(context, Context):
1686 raise TypeError("context must be a Context instance")
1687
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001688 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001689 self._context = context
1690
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001691 def get_servername(self):
1692 """
1693 Retrieve the servername extension value if provided in the client hello
1694 message, or None if there wasn't one.
1695
Alex Chand072cae2018-02-15 09:57:59 +00001696 :return: A byte string giving the server name or :data:`None`.
1697
1698 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001699 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001700 name = _lib.SSL_get_servername(
1701 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1702 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001704 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001706 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001707
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001708 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001709 """
1710 Set the value of the servername extension to send in the client hello.
1711
1712 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001713
1714 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001716 if not isinstance(name, bytes):
1717 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001718 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001719 raise TypeError("name must not contain NUL byte")
1720
1721 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001722 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001723
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724 def pending(self):
1725 """
Alex Chand072cae2018-02-15 09:57:59 +00001726 Get the number of bytes that can be safely read from the SSL buffer
1727 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001728
1729 :return: The number of bytes available in the receive buffer.
1730 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001731 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001733 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001734 """
1735 Send data on the connection. NOTE: If you get one of the WantRead,
1736 WantWrite or WantX509Lookup exceptions on this, you have to call the
1737 method again with the SAME buffer.
1738
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001739 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001740 :param flags: (optional) Included for compatibility with the socket
1741 API, the value is ignored
1742 :return: The number of bytes written
1743 """
Abraham Martine82326c2015-02-04 10:18:10 +00001744 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001745 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001746
Daniel Holth079c9632019-11-17 22:45:52 -05001747 with _from_buffer(buf) as data:
1748 # check len(buf) instead of len(data) for testability
1749 if len(buf) > 2147483647:
1750 raise ValueError(
1751 "Cannot send more than 2**31-1 bytes at once."
1752 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001753
Daniel Holth079c9632019-11-17 22:45:52 -05001754 result = _lib.SSL_write(self._ssl, data, len(data))
1755 self._raise_ssl_error(self._ssl, result)
1756
1757 return result
1758
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001759 write = send
1760
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001762 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001763 Send "all" data on the connection. This calls send() repeatedly until
1764 all data is sent. If an error occurs, it's impossible to tell how much
1765 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001766
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001767 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768 :param flags: (optional) Included for compatibility with the socket
1769 API, the value is ignored
1770 :return: The number of bytes written
1771 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001772 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001773
Daniel Holth079c9632019-11-17 22:45:52 -05001774 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001775
Daniel Holth079c9632019-11-17 22:45:52 -05001776 left_to_send = len(buf)
1777 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001778
Daniel Holth079c9632019-11-17 22:45:52 -05001779 while left_to_send:
1780 # SSL_write's num arg is an int,
1781 # so we cannot send more than 2**31-1 bytes at once.
1782 result = _lib.SSL_write(
1783 self._ssl,
1784 data + total_sent,
1785 min(left_to_send, 2147483647)
1786 )
1787 self._raise_ssl_error(self._ssl, result)
1788 total_sent += result
1789 left_to_send -= result
1790
1791 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001792
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001793 def recv(self, bufsiz, flags=None):
1794 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001795 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001796
1797 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001798 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1799 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001800 :return: The string read from the Connection
1801 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001802 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001803 if flags is not None and flags & socket.MSG_PEEK:
1804 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1805 else:
1806 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001807 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001808 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809 read = recv
1810
Cory Benfield62d10332014-06-15 10:03:41 +01001811 def recv_into(self, buffer, nbytes=None, flags=None):
1812 """
Alex Chand072cae2018-02-15 09:57:59 +00001813 Receive data on the connection and copy it directly into the provided
1814 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001815
1816 :param buffer: The buffer to copy into.
1817 :param nbytes: (optional) The maximum number of bytes to read into the
1818 buffer. If not present, defaults to the size of the buffer. If
1819 larger than the size of the buffer, is reduced to the size of the
1820 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001821 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1822 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001823 :return: The number of bytes read into the buffer.
1824 """
1825 if nbytes is None:
1826 nbytes = len(buffer)
1827 else:
1828 nbytes = min(nbytes, len(buffer))
1829
1830 # We need to create a temporary buffer. This is annoying, it would be
1831 # better if we could pass memoryviews straight into the SSL_read call,
1832 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001833 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001834 if flags is not None and flags & socket.MSG_PEEK:
1835 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1836 else:
1837 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001838 self._raise_ssl_error(self._ssl, result)
1839
1840 # This strange line is all to avoid a memory copy. The buffer protocol
1841 # should allow us to assign a CFFI buffer to the LHS of this line, but
1842 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001843 # wrap it in a memoryview.
1844 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001845
1846 return result
1847
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001848 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001849 if _lib.BIO_should_retry(bio):
1850 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001851 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001852 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001853 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001854 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001855 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001856 # TODO: This is untested. I think io_special means the socket
1857 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001858 raise ValueError("BIO_should_io_special")
1859 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001860 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001861 raise ValueError("unknown bio failure")
1862 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001863 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001864 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001865
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001866 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867 """
Alex Chand072cae2018-02-15 09:57:59 +00001868 If the Connection was created with a memory BIO, this method can be
1869 used to read bytes from the write end of that memory BIO. Many
1870 Connection methods will add bytes which must be read in this manner or
1871 the buffer will eventually fill up and the Connection will be able to
1872 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001873
1874 :param bufsiz: The maximum number of bytes to read
1875 :return: The string read.
1876 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001877 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001878 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001880 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001881 raise TypeError("bufsiz must be an integer")
1882
Cory Benfielde62840e2016-11-28 12:17:08 +00001883 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001884 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001885 if result <= 0:
1886 self._handle_bio_errors(self._from_ssl, result)
1887
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001888 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001889
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001890 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001891 """
Alex Chand072cae2018-02-15 09:57:59 +00001892 If the Connection was created with a memory BIO, this method can be
1893 used to add bytes to the read end of that memory BIO. The Connection
1894 can then read the bytes (for example, in response to a call to
1895 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896
1897 :param buf: The string to put into the memory BIO.
1898 :return: The number of bytes written
1899 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001900 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001901
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001902 if self._into_ssl is None:
1903 raise TypeError("Connection sock was not None")
1904
Daniel Holth079c9632019-11-17 22:45:52 -05001905 with _from_buffer(buf) as data:
1906 result = _lib.BIO_write(self._into_ssl, data, len(data))
1907 if result <= 0:
1908 self._handle_bio_errors(self._into_ssl, result)
1909 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001910
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911 def renegotiate(self):
1912 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001913 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001914
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001915 :return: True if the renegotiation can be started, False otherwise
1916 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001918 if not self.renegotiate_pending():
1919 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1920 return True
1921 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001922
1923 def do_handshake(self):
1924 """
Alex Chand072cae2018-02-15 09:57:59 +00001925 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001926 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001927 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001928
1929 :return: None.
1930 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001931 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001932 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001933
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934 def renegotiate_pending(self):
1935 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001936 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001937 a renegotiation is finished.
1938
1939 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001940 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001942 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943
1944 def total_renegotiations(self):
1945 """
1946 Find out the total number of renegotiations.
1947
1948 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001949 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001950 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001951 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001953 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001954 """
Alex Chand072cae2018-02-15 09:57:59 +00001955 Call the :meth:`connect` method of the underlying socket and set up SSL
1956 on the socket, using the :class:`Context` object supplied to this
1957 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
1959 :param addr: A remote address
1960 :return: What the socket's connect method returns
1961 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001962 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001963 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001965 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966 """
Alex Chand072cae2018-02-15 09:57:59 +00001967 Call the :meth:`connect_ex` method of the underlying socket and set up
1968 SSL on the socket, using the Context object supplied to this Connection
1969 object at creation. Note that if the :meth:`connect_ex` method of the
1970 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001971
1972 :param addr: A remove address
1973 :return: What the socket's connect_ex method returns
1974 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001975 connect_ex = self._socket.connect_ex
1976 self.set_connect_state()
1977 return connect_ex(addr)
1978
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001979 def accept(self):
1980 """
Alex Chand072cae2018-02-15 09:57:59 +00001981 Call the :meth:`accept` method of the underlying socket and set up SSL
1982 on the returned socket, using the Context object supplied to this
1983 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984
Alex Chand072cae2018-02-15 09:57:59 +00001985 :return: A *(conn, addr)* pair where *conn* is the new
1986 :class:`Connection` object created, and *address* is as returned by
1987 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001988 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 client, addr = self._socket.accept()
1990 conn = Connection(self._context, client)
1991 conn.set_accept_state()
1992 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994 def bio_shutdown(self):
1995 """
Alex Chand072cae2018-02-15 09:57:59 +00001996 If the Connection was created with a memory BIO, this method can be
1997 used to indicate that *end of file* has been reached on the read end of
1998 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999
2000 :return: None
2001 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002002 if self._from_ssl is None:
2003 raise TypeError("Connection sock was not None")
2004
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002005 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002007 def shutdown(self):
2008 """
Alex Chand072cae2018-02-15 09:57:59 +00002009 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002010
2011 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00002012 have sent closure alerts), False otherwise (in which case you
2013 call :meth:`recv` or :meth:`send` when the connection becomes
2014 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002016 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002017 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002018 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002020 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021 else:
2022 return False
2023
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024 def get_cipher_list(self):
2025 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002026 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002028 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002029 """
2030 ciphers = []
2031 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002032 result = _lib.SSL_get_cipher_list(self._ssl, i)
2033 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002034 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002035 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036 return ciphers
2037
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002038 def get_client_ca_list(self):
2039 """
2040 Get CAs whose certificates are suggested for client authentication.
2041
Alex Chand072cae2018-02-15 09:57:59 +00002042 :return: If this is a server connection, the list of certificate
2043 authorities that will be sent or has been sent to the client, as
2044 controlled by this :class:`Connection`'s :class:`Context`.
2045
2046 If this is a client connection, the list will be empty until the
2047 connection with the server is established.
2048
2049 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002050 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002051 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2052 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002053 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002054 return []
2055
2056 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002057 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2058 name = _lib.sk_X509_NAME_value(ca_names, i)
2059 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002060 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002061
2062 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002063 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002064 result.append(pyname)
2065 return result
2066
Aykee7f33452018-05-16 19:18:16 +02002067 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002068 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002069 The makefile() method is not implemented, since there is no dup
2070 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002072 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073 """
Alex Gaynor83284952015-09-05 10:43:30 -04002074 raise NotImplementedError(
2075 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002076
2077 def get_app_data(self):
2078 """
Alex Chand072cae2018-02-15 09:57:59 +00002079 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002080
2081 :return: The application data
2082 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002083 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002084
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002085 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086 """
2087 Set application data
2088
Alex Chand072cae2018-02-15 09:57:59 +00002089 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002090 :return: None
2091 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002092 self._app_data = data
2093
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002094 def get_shutdown(self):
2095 """
Alex Chand072cae2018-02-15 09:57:59 +00002096 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002097
Alex Gaynor62da94d2015-09-05 14:37:34 -04002098 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2099 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002100 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002101 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002103 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002104 """
Alex Chand072cae2018-02-15 09:57:59 +00002105 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106
Alex Chand072cae2018-02-15 09:57:59 +00002107 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002108 :return: None
2109 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002110 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002111 raise TypeError("state must be an integer")
2112
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002113 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002114
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002115 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002116 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002117 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002118
2119 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002120 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002121 """
kjavc704a2e2015-09-07 12:12:27 +01002122 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123
2124 def server_random(self):
2125 """
Alex Chand072cae2018-02-15 09:57:59 +00002126 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002127
2128 :return: A string representing the state
2129 """
Alex Gaynor93603062016-06-01 20:13:09 -07002130 session = _lib.SSL_get_session(self._ssl)
2131 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002132 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002133 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002134 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002135 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002136 _lib.SSL_get_server_random(self._ssl, outp, length)
2137 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002138
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002139 def client_random(self):
2140 """
Alex Chand072cae2018-02-15 09:57:59 +00002141 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002142
2143 :return: A string representing the state
2144 """
Alex Gaynor93603062016-06-01 20:13:09 -07002145 session = _lib.SSL_get_session(self._ssl)
2146 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002147 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002148
2149 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002150 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002151 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002152 _lib.SSL_get_client_random(self._ssl, outp, length)
2153 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002154
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002155 def master_key(self):
2156 """
Alex Chand072cae2018-02-15 09:57:59 +00002157 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002158
2159 :return: A string representing the state
2160 """
Alex Gaynor93603062016-06-01 20:13:09 -07002161 session = _lib.SSL_get_session(self._ssl)
2162 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002163 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002164
2165 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002166 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002167 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002168 _lib.SSL_SESSION_get_master_key(session, outp, length)
2169 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002170
Paul Kehrerbdb76392017-12-01 04:54:32 +08002171 def export_keying_material(self, label, olen, context=None):
2172 """
2173 Obtain keying material for application use.
2174
Alex Chand072cae2018-02-15 09:57:59 +00002175 :param: label - a disambiguating label string as described in RFC 5705
2176 :param: olen - the length of the exported key material in bytes
2177 :param: context - a per-association context value
2178 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002179 """
2180 outp = _no_zero_allocator("unsigned char[]", olen)
2181 context_buf = _ffi.NULL
2182 context_len = 0
2183 use_context = 0
2184 if context is not None:
2185 context_buf = context
2186 context_len = len(context)
2187 use_context = 1
2188 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2189 label, len(label),
2190 context_buf, context_len,
2191 use_context)
2192 _openssl_assert(success == 1)
2193 return _ffi.buffer(outp, olen)[:]
2194
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002195 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196 """
Alex Chand072cae2018-02-15 09:57:59 +00002197 Call the :meth:`shutdown` method of the underlying socket.
2198 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002199
2200 :return: What the socket's shutdown() method returns
2201 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002202 return self._socket.shutdown(*args, **kwargs)
2203
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002204 def get_certificate(self):
2205 """
2206 Retrieve the local certificate (if any)
2207
2208 :return: The local certificate
2209 """
2210 cert = _lib.SSL_get_certificate(self._ssl)
2211 if cert != _ffi.NULL:
2212 _lib.X509_up_ref(cert)
2213 return X509._from_raw_x509_ptr(cert)
2214 return None
2215
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002216 def get_peer_certificate(self):
2217 """
2218 Retrieve the other side's certificate (if any)
2219
2220 :return: The peer's certificate
2221 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002222 cert = _lib.SSL_get_peer_certificate(self._ssl)
2223 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002224 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002225 return None
2226
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002227 def get_peer_cert_chain(self):
2228 """
2229 Retrieve the other side's certificate (if any)
2230
2231 :return: A list of X509 instances giving the peer's certificate chain,
2232 or None if it does not have one.
2233 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002234 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2235 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002236 return None
2237
2238 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002239 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002240 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002241 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002242 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002243 result.append(pycert)
2244 return result
2245
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002246 def want_read(self):
2247 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002248 Checks if more data has to be read from the transport layer to complete
2249 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002250
2251 :return: True iff more data has to be read
2252 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002253 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002254
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002255 def want_write(self):
2256 """
2257 Checks if there is data to write to the transport layer to complete an
2258 operation.
2259
2260 :return: True iff there is data to write
2261 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002262 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002263
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002264 def set_accept_state(self):
2265 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002266 Set the connection to work in server mode. The handshake will be
2267 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002268
2269 :return: None
2270 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002271 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002272
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002273 def set_connect_state(self):
2274 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002275 Set the connection to work in client mode. The handshake will be
2276 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002277
2278 :return: None
2279 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002280 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002281
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002282 def get_session(self):
2283 """
2284 Returns the Session currently used.
2285
Alex Chand072cae2018-02-15 09:57:59 +00002286 :return: An instance of :class:`OpenSSL.SSL.Session` or
2287 :obj:`None` if no session exists.
2288
2289 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002290 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002291 session = _lib.SSL_get1_session(self._ssl)
2292 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002293 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002294
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002295 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002296 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002297 return pysession
2298
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002299 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002300 """
2301 Set the session to be used when the TLS/SSL connection is established.
2302
2303 :param session: A Session instance representing the session to use.
2304 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002305
2306 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002307 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002308 if not isinstance(session, Session):
2309 raise TypeError("session must be a Session instance")
2310
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002311 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002312 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002313 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002314
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002315 def _get_finished_message(self, function):
2316 """
Alex Chand072cae2018-02-15 09:57:59 +00002317 Helper to implement :meth:`get_finished` and
2318 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002319
Alex Chand072cae2018-02-15 09:57:59 +00002320 :param function: Either :data:`SSL_get_finished`: or
2321 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002322
Alex Chand072cae2018-02-15 09:57:59 +00002323 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002324 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002325 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002326 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002327 # The OpenSSL documentation says nothing about what might happen if the
2328 # count argument given is zero. Specifically, it doesn't say whether
2329 # the output buffer may be NULL in that case or not. Inspection of the
2330 # implementation reveals that it calls memcpy() unconditionally.
2331 # Section 7.1.4, paragraph 1 of the C standard suggests that
2332 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2333 # alone desirable) behavior (though it probably does on just about
2334 # every implementation...)
2335 #
2336 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2337 # one might expect) for the initial call so as to be safe against this
2338 # potentially undefined behavior.
2339 empty = _ffi.new("char[]", 0)
2340 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002341 if size == 0:
2342 # No Finished message so far.
2343 return None
2344
Cory Benfielde62840e2016-11-28 12:17:08 +00002345 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002346 function(self._ssl, buf, size)
2347 return _ffi.buffer(buf, size)[:]
2348
Fedor Brunner5747b932014-03-05 14:22:34 +01002349 def get_finished(self):
2350 """
Alex Chand072cae2018-02-15 09:57:59 +00002351 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002352
Alex Chand072cae2018-02-15 09:57:59 +00002353 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002354 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002355 :rtype: :class:`bytes` or :class:`NoneType`
2356
2357 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002358 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002359 return self._get_finished_message(_lib.SSL_get_finished)
2360
Fedor Brunner5747b932014-03-05 14:22:34 +01002361 def get_peer_finished(self):
2362 """
Alex Chand072cae2018-02-15 09:57:59 +00002363 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002364
Alex Chand072cae2018-02-15 09:57:59 +00002365 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002366 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002367 :rtype: :class:`bytes` or :class:`NoneType`
2368
2369 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002370 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002371 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002372
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002373 def get_cipher_name(self):
2374 """
2375 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002376
Alex Chand072cae2018-02-15 09:57:59 +00002377 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002378 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002379 :rtype: :class:`unicode` or :class:`NoneType`
2380
2381 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002382 """
2383 cipher = _lib.SSL_get_current_cipher(self._ssl)
2384 if cipher == _ffi.NULL:
2385 return None
2386 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002387 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2388 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002389
2390 def get_cipher_bits(self):
2391 """
2392 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002393
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002394 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002395 or :obj:`None` if no connection has been established.
2396 :rtype: :class:`int` or :class:`NoneType`
2397
2398 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002399 """
2400 cipher = _lib.SSL_get_current_cipher(self._ssl)
2401 if cipher == _ffi.NULL:
2402 return None
2403 else:
2404 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2405
2406 def get_cipher_version(self):
2407 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002408 Obtain the protocol version of the currently used cipher.
2409
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002410 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002411 or :obj:`None` if no connection has been established.
2412 :rtype: :class:`unicode` or :class:`NoneType`
2413
2414 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002415 """
2416 cipher = _lib.SSL_get_current_cipher(self._ssl)
2417 if cipher == _ffi.NULL:
2418 return None
2419 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002420 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002421 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002422
Jim Shaverabff1882015-05-27 09:15:55 -04002423 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002424 """
Alex Chand072cae2018-02-15 09:57:59 +00002425 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002426
2427 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002428 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002429 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002430 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002431 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002432 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002433 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002434
Jim Shaver208438c2015-05-28 09:52:38 -04002435 def get_protocol_version(self):
2436 """
Alex Chand072cae2018-02-15 09:57:59 +00002437 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002438
Alex Chand072cae2018-02-15 09:57:59 +00002439 :returns: The TLS version of the current connection. For example,
2440 it will return ``0x769`` for connections made over TLS version 1.
2441 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002442 """
2443 version = _lib.SSL_version(self._ssl)
2444 return version
2445
Cory Benfield10b277f2015-04-13 17:12:42 -04002446 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002447 def get_next_proto_negotiated(self):
2448 """
2449 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002450
2451 :returns: A bytestring of the protocol name. If no protocol has been
2452 negotiated yet, returns an empty string.
2453
2454 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002455 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002456 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002457 data = _ffi.new("unsigned char **")
2458 data_len = _ffi.new("unsigned int *")
2459
2460 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2461
Cory Benfieldcd010f62014-05-15 19:00:27 +01002462 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002463
Cory Benfield7907e332015-04-13 17:18:25 -04002464 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002465 def set_alpn_protos(self, protos):
2466 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002467 Specify the client's ALPN protocol list.
2468
2469 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002470
2471 :param protos: A list of the protocols to be offered to the server.
2472 This list should be a Python list of bytestrings representing the
2473 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2474 """
2475 # Take the list of protocols and join them together, prefixing them
2476 # with their lengths.
2477 protostr = b''.join(
2478 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2479 )
2480
2481 # Build a C string from the list. We don't need to save this off
2482 # because OpenSSL immediately copies the data out.
2483 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002484 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002485
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002486 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002487 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002488 """
2489 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002490
2491 :returns: A bytestring of the protocol name. If no protocol has been
2492 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002493 """
Cory Benfield12eae892014-06-07 15:42:56 +01002494 data = _ffi.new("unsigned char **")
2495 data_len = _ffi.new("unsigned int *")
2496
2497 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2498
Cory Benfielde8e9c382015-04-11 17:33:48 -04002499 if not data_len:
2500 return b''
2501
Cory Benfield12eae892014-06-07 15:42:56 +01002502 return _ffi.buffer(data[0], data_len[0])[:]
2503
Cory Benfield496652a2017-01-24 11:42:56 +00002504 def request_ocsp(self):
2505 """
2506 Called to request that the server sends stapled OCSP data, if
2507 available. If this is not called on the client side then the server
2508 will not send OCSP data. Should be used in conjunction with
2509 :meth:`Context.set_ocsp_client_callback`.
2510 """
2511 rc = _lib.SSL_set_tlsext_status_type(
2512 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2513 )
2514 _openssl_assert(rc == 1)
2515
Cory Benfield12eae892014-06-07 15:42:56 +01002516
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002517# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2518# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002519_lib.SSL_library_init()