blob: adcfd8fab6126e1c92dde2e08d47b2f4405fded0 [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 Gaynor336d8022017-06-29 21:46:42 -070010from six import (
11 binary_type as _binary_type, integer_types as integer_types, int2byte,
12 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050013
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010015 UNSPECIFIED as _UNSPECIFIED,
16 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 ffi as _ffi,
Daniel Holth079c9632019-11-17 22:45:52 -050018 from_buffer as _from_buffer,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050019 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Nicolas Karolak736c6212017-11-26 14:40:28 +010030__all__ = [
31 'OPENSSL_VERSION_NUMBER',
32 'SSLEAY_VERSION',
33 'SSLEAY_CFLAGS',
34 'SSLEAY_PLATFORM',
35 'SSLEAY_DIR',
36 'SSLEAY_BUILT_ON',
37 'SENT_SHUTDOWN',
38 'RECEIVED_SHUTDOWN',
39 'SSLv2_METHOD',
40 'SSLv3_METHOD',
41 'SSLv23_METHOD',
42 'TLSv1_METHOD',
43 'TLSv1_1_METHOD',
44 'TLSv1_2_METHOD',
45 'OP_NO_SSLv2',
46 'OP_NO_SSLv3',
47 'OP_NO_TLSv1',
48 'OP_NO_TLSv1_1',
49 'OP_NO_TLSv1_2',
Nathaniel J. Smitha1813732019-08-01 21:32:13 -070050 'OP_NO_TLSv1_3',
Nicolas Karolak736c6212017-11-26 14:40:28 +010051 'MODE_RELEASE_BUFFERS',
52 'OP_SINGLE_DH_USE',
53 'OP_SINGLE_ECDH_USE',
54 'OP_EPHEMERAL_RSA',
55 'OP_MICROSOFT_SESS_ID_BUG',
56 'OP_NETSCAPE_CHALLENGE_BUG',
57 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
58 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
59 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
60 'OP_MSIE_SSLV2_RSA_PADDING',
61 'OP_SSLEAY_080_CLIENT_DH_BUG',
62 'OP_TLS_D5_BUG',
63 'OP_TLS_BLOCK_PADDING_BUG',
64 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
65 'OP_CIPHER_SERVER_PREFERENCE',
66 'OP_TLS_ROLLBACK_BUG',
67 'OP_PKCS1_CHECK_1',
68 'OP_PKCS1_CHECK_2',
69 'OP_NETSCAPE_CA_DN_BUG',
70 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
71 'OP_NO_COMPRESSION',
72 'OP_NO_QUERY_MTU',
73 'OP_COOKIE_EXCHANGE',
74 'OP_NO_TICKET',
75 'OP_ALL',
76 'VERIFY_PEER',
77 'VERIFY_FAIL_IF_NO_PEER_CERT',
78 'VERIFY_CLIENT_ONCE',
79 'VERIFY_NONE',
80 'SESS_CACHE_OFF',
81 'SESS_CACHE_CLIENT',
82 'SESS_CACHE_SERVER',
83 'SESS_CACHE_BOTH',
84 'SESS_CACHE_NO_AUTO_CLEAR',
85 'SESS_CACHE_NO_INTERNAL_LOOKUP',
86 'SESS_CACHE_NO_INTERNAL_STORE',
87 'SESS_CACHE_NO_INTERNAL',
88 'SSL_ST_CONNECT',
89 'SSL_ST_ACCEPT',
90 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010091 'SSL_CB_LOOP',
92 'SSL_CB_EXIT',
93 'SSL_CB_READ',
94 'SSL_CB_WRITE',
95 'SSL_CB_ALERT',
96 'SSL_CB_READ_ALERT',
97 'SSL_CB_WRITE_ALERT',
98 'SSL_CB_ACCEPT_LOOP',
99 'SSL_CB_ACCEPT_EXIT',
100 'SSL_CB_CONNECT_LOOP',
101 'SSL_CB_CONNECT_EXIT',
102 'SSL_CB_HANDSHAKE_START',
103 'SSL_CB_HANDSHAKE_DONE',
104 'Error',
105 'WantReadError',
106 'WantWriteError',
107 'WantX509LookupError',
108 'ZeroReturnError',
109 'SysCallError',
110 'SSLeay_version',
111 'Session',
112 'Context',
113 'Connection'
114]
115
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500116try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200117 _buffer = buffer
118except NameError:
119 class _buffer(object):
120 pass
121
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500122OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
123SSLEAY_VERSION = _lib.SSLEAY_VERSION
124SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
125SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
126SSLEAY_DIR = _lib.SSLEAY_DIR
127SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500129SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
130RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800131
132SSLv2_METHOD = 1
133SSLv3_METHOD = 2
134SSLv23_METHOD = 3
135TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500136TLSv1_1_METHOD = 5
137TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800138
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500139OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
140OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
141OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700142OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
143OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700144try:
145 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
146except AttributeError:
147 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800148
Alex Gaynorbf012872016-06-04 13:18:39 -0700149MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800150
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500151OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900152OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500153OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
154OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
155OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400156OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
157 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
158)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500159OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
160OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400161OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500162OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
163OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
164OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
165OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
166OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
167OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
168OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
169OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
170OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400171OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
172 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
173)
Alex Gaynorbf012872016-06-04 13:18:39 -0700174OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800175
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500176OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
177OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400178OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800179
Alex Gaynorc4889812015-09-04 08:43:17 -0400180OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800181
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500182VERIFY_PEER = _lib.SSL_VERIFY_PEER
183VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
184VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
185VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
188SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
189SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
190SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
191SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
192SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
193SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
194SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800195
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500196SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
197SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
198SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400199if _lib.Cryptography_HAS_SSL_ST:
200 SSL_ST_INIT = _lib.SSL_ST_INIT
201 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
202 SSL_ST_OK = _lib.SSL_ST_OK
203 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100204 __all__.extend([
205 'SSL_ST_INIT',
206 'SSL_ST_BEFORE',
207 'SSL_ST_OK',
208 'SSL_ST_RENEGOTIATE',
209 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800210
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500211SSL_CB_LOOP = _lib.SSL_CB_LOOP
212SSL_CB_EXIT = _lib.SSL_CB_EXIT
213SSL_CB_READ = _lib.SSL_CB_READ
214SSL_CB_WRITE = _lib.SSL_CB_WRITE
215SSL_CB_ALERT = _lib.SSL_CB_ALERT
216SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
217SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
218SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
219SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
220SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
221SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
222SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
223SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800224
Paul Kehrer55fb3412017-06-29 18:44:08 -0500225# Taken from https://golang.org/src/crypto/x509/root_linux.go
226_CERTIFICATE_FILE_LOCATIONS = [
227 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
228 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
229 "/etc/ssl/ca-bundle.pem", # OpenSUSE
230 "/etc/pki/tls/cacert.pem", # OpenELEC
231 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
232]
233
234_CERTIFICATE_PATH_LOCATIONS = [
235 "/etc/ssl/certs", # SLES10/SLES11
236]
237
Paul Kehrera92a1a72017-07-19 15:53:23 +0200238# These values are compared to output from cffi's ffi.string so they must be
239# byte strings.
240_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
241_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500242
Alex Gaynor83284952015-09-05 10:43:30 -0400243
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500244class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500245 """
246 An error occurred in an `OpenSSL.SSL` API.
247 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500248
249
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500250_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100251_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500252
253
254class WantReadError(Error):
255 pass
256
257
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500258class WantWriteError(Error):
259 pass
260
261
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500262class WantX509LookupError(Error):
263 pass
264
265
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500266class ZeroReturnError(Error):
267 pass
268
269
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500270class SysCallError(Error):
271 pass
272
273
Cory Benfield0ea76e72015-03-22 09:05:28 +0000274class _CallbackExceptionHelper(object):
275 """
276 A base class for wrapper classes that allow for intelligent exception
277 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500278
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400279 :ivar list _problems: Any exceptions that occurred while executing in a
280 context where they could not be raised in the normal way. Typically
281 this is because OpenSSL has called into some Python code and requires a
282 return value. The exceptions are saved to be raised later when it is
283 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000284 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400285
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400286 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800287 self._problems = []
288
Cory Benfield0ea76e72015-03-22 09:05:28 +0000289 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400290 """
291 Raise an exception from the OpenSSL error queue or that was previously
292 captured whe running a callback.
293 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000294 if self._problems:
295 try:
296 _raise_current_error()
297 except Error:
298 pass
299 raise self._problems.pop(0)
300
301
302class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400303 """
304 Wrap a callback such that it can be used as a certificate verification
305 callback.
306 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400307
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800308 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400309 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800310
311 @wraps(callback)
312 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800313 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
314 _lib.X509_up_ref(x509)
315 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500316 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
317 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800318
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400319 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
320 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
321 connection = Connection._reverse_mapping[ssl]
322
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800323 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400324 result = callback(
325 connection, cert, error_number, error_depth, ok
326 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800327 except Exception as e:
328 self._problems.append(e)
329 return 0
330 else:
331 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500332 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800333 return 1
334 else:
335 return 0
336
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500337 self.callback = _ffi.callback(
338 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800339
340
Cory Benfield0ea76e72015-03-22 09:05:28 +0000341class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400342 """
343 Wrap a callback such that it can be used as an NPN advertisement callback.
344 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400345
Cory Benfield0ea76e72015-03-22 09:05:28 +0000346 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400347 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800348
Cory Benfield0ea76e72015-03-22 09:05:28 +0000349 @wraps(callback)
350 def wrapper(ssl, out, outlen, arg):
351 try:
352 conn = Connection._reverse_mapping[ssl]
353 protos = callback(conn)
354
355 # Join the protocols into a Python bytestring, length-prefixing
356 # each element.
357 protostr = b''.join(
358 chain.from_iterable((int2byte(len(p)), p) for p in protos)
359 )
360
361 # Save our callback arguments on the connection object. This is
362 # done to make sure that they don't get freed before OpenSSL
363 # uses them. Then, return them appropriately in the output
364 # parameters.
365 conn._npn_advertise_callback_args = [
366 _ffi.new("unsigned int *", len(protostr)),
367 _ffi.new("unsigned char[]", protostr),
368 ]
369 outlen[0] = conn._npn_advertise_callback_args[0][0]
370 out[0] = conn._npn_advertise_callback_args[1]
371 return 0
372 except Exception as e:
373 self._problems.append(e)
374 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
375
376 self.callback = _ffi.callback(
377 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
378 wrapper
379 )
380
381
382class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400383 """
384 Wrap a callback such that it can be used as an NPN selection callback.
385 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400386
Cory Benfield0ea76e72015-03-22 09:05:28 +0000387 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400388 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000389
390 @wraps(callback)
391 def wrapper(ssl, out, outlen, in_, inlen, arg):
392 try:
393 conn = Connection._reverse_mapping[ssl]
394
395 # The string passed to us is actually made up of multiple
396 # length-prefixed bytestrings. We need to split that into a
397 # list.
398 instr = _ffi.buffer(in_, inlen)[:]
399 protolist = []
400 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500401 length = indexbytes(instr, 0)
402 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000403 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500404 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000405
406 # Call the callback
407 outstr = callback(conn, protolist)
408
409 # Save our callback arguments on the connection object. This is
410 # done to make sure that they don't get freed before OpenSSL
411 # uses them. Then, return them appropriately in the output
412 # parameters.
413 conn._npn_select_callback_args = [
414 _ffi.new("unsigned char *", len(outstr)),
415 _ffi.new("unsigned char[]", outstr),
416 ]
417 outlen[0] = conn._npn_select_callback_args[0][0]
418 out[0] = conn._npn_select_callback_args[1]
419 return 0
420 except Exception as e:
421 self._problems.append(e)
422 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
423
424 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400425 ("int (*)(SSL *, unsigned char **, unsigned char *, "
426 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000427 wrapper
428 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800429
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800430
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400431class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400432 """
433 Wrap a callback such that it can be used as an ALPN selection callback.
434 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400435
Cory Benfieldf1177e72015-04-12 09:11:49 -0400436 def __init__(self, callback):
437 _CallbackExceptionHelper.__init__(self)
438
439 @wraps(callback)
440 def wrapper(ssl, out, outlen, in_, inlen, arg):
441 try:
442 conn = Connection._reverse_mapping[ssl]
443
444 # The string passed to us is made up of multiple
445 # length-prefixed bytestrings. We need to split that into a
446 # list.
447 instr = _ffi.buffer(in_, inlen)[:]
448 protolist = []
449 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400450 encoded_len = indexbytes(instr, 0)
451 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400452 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400453 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400454
455 # Call the callback
456 outstr = callback(conn, protolist)
457
458 if not isinstance(outstr, _binary_type):
459 raise TypeError("ALPN callback must return a bytestring.")
460
461 # Save our callback arguments on the connection object to make
462 # sure that they don't get freed before OpenSSL can use them.
463 # Then, return them in the appropriate output parameters.
464 conn._alpn_select_callback_args = [
465 _ffi.new("unsigned char *", len(outstr)),
466 _ffi.new("unsigned char[]", outstr),
467 ]
468 outlen[0] = conn._alpn_select_callback_args[0][0]
469 out[0] = conn._alpn_select_callback_args[1]
470 return 0
471 except Exception as e:
472 self._problems.append(e)
473 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
474
475 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400476 ("int (*)(SSL *, unsigned char **, unsigned char *, "
477 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400478 wrapper
479 )
480
481
Cory Benfield496652a2017-01-24 11:42:56 +0000482class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
483 """
484 Wrap a callback such that it can be used as an OCSP callback for the server
485 side.
486
487 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
488 ways. For servers, that callback is expected to retrieve some OCSP data and
489 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
490 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
491 is expected to check the OCSP data, and returns a negative value on error,
492 0 if the response is not acceptable, or positive if it is. These are
493 mutually exclusive return code behaviours, and they mean that we need two
494 helpers so that we always return an appropriate error code if the user's
495 code throws an exception.
496
497 Given that we have to have two helpers anyway, these helpers are a bit more
498 helpery than most: specifically, they hide a few more of the OpenSSL
499 functions so that the user has an easier time writing these callbacks.
500
501 This helper implements the server side.
502 """
503
504 def __init__(self, callback):
505 _CallbackExceptionHelper.__init__(self)
506
507 @wraps(callback)
508 def wrapper(ssl, cdata):
509 try:
510 conn = Connection._reverse_mapping[ssl]
511
512 # Extract the data if any was provided.
513 if cdata != _ffi.NULL:
514 data = _ffi.from_handle(cdata)
515 else:
516 data = None
517
518 # Call the callback.
519 ocsp_data = callback(conn, data)
520
521 if not isinstance(ocsp_data, _binary_type):
522 raise TypeError("OCSP callback must return a bytestring.")
523
524 # If the OCSP data was provided, we will pass it to OpenSSL.
525 # However, we have an early exit here: if no OCSP data was
526 # provided we will just exit out and tell OpenSSL that there
527 # is nothing to do.
528 if not ocsp_data:
529 return 3 # SSL_TLSEXT_ERR_NOACK
530
David Benjamin7ac5f272018-05-21 21:24:04 -0400531 # OpenSSL takes ownership of this data and expects it to have
532 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000533 ocsp_data_length = len(ocsp_data)
534 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
535 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
536
537 _lib.SSL_set_tlsext_status_ocsp_resp(
538 ssl, data_ptr, ocsp_data_length
539 )
540
541 return 0
542 except Exception as e:
543 self._problems.append(e)
544 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
545
546 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
547
548
549class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
550 """
551 Wrap a callback such that it can be used as an OCSP callback for the client
552 side.
553
554 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
555 ways. For servers, that callback is expected to retrieve some OCSP data and
556 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
557 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
558 is expected to check the OCSP data, and returns a negative value on error,
559 0 if the response is not acceptable, or positive if it is. These are
560 mutually exclusive return code behaviours, and they mean that we need two
561 helpers so that we always return an appropriate error code if the user's
562 code throws an exception.
563
564 Given that we have to have two helpers anyway, these helpers are a bit more
565 helpery than most: specifically, they hide a few more of the OpenSSL
566 functions so that the user has an easier time writing these callbacks.
567
568 This helper implements the client side.
569 """
570
571 def __init__(self, callback):
572 _CallbackExceptionHelper.__init__(self)
573
574 @wraps(callback)
575 def wrapper(ssl, cdata):
576 try:
577 conn = Connection._reverse_mapping[ssl]
578
579 # Extract the data if any was provided.
580 if cdata != _ffi.NULL:
581 data = _ffi.from_handle(cdata)
582 else:
583 data = None
584
585 # Get the OCSP data.
586 ocsp_ptr = _ffi.new("unsigned char **")
587 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
588 if ocsp_len < 0:
589 # No OCSP data.
590 ocsp_data = b''
591 else:
592 # Copy the OCSP data, then pass it to the callback.
593 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
594
595 valid = callback(conn, ocsp_data, data)
596
597 # Return 1 on success or 0 on error.
598 return int(bool(valid))
599
600 except Exception as e:
601 self._problems.append(e)
602 # Return negative value if an exception is hit.
603 return -1
604
605 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
606
607
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800608def _asFileDescriptor(obj):
609 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800610 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800611 meth = getattr(obj, "fileno", None)
612 if meth is not None:
613 obj = meth()
614
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800615 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800616 fd = obj
617
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800618 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619 raise TypeError("argument must be an int, or have a fileno() method.")
620 elif fd < 0:
621 raise ValueError(
622 "file descriptor cannot be a negative integer (%i)" % (fd,))
623
624 return fd
625
626
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800627def SSLeay_version(type):
628 """
629 Return a string describing the version of OpenSSL in use.
630
Alex Chand072cae2018-02-15 09:57:59 +0000631 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800632 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500633 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800634
635
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500636def _warn_npn():
637 warnings.warn("NPN is deprecated. Protocols should switch to using ALPN.",
638 DeprecationWarning, stacklevel=3)
639
640
Cory Benfieldef404df2016-03-29 15:32:48 +0100641def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400642 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100643 Builds a decorator that ensures that functions that rely on OpenSSL
644 functions that are not present in this build raise NotImplementedError,
645 rather than AttributeError coming out of cryptography.
646
647 :param flag: A cryptography flag that guards the functions, e.g.
648 ``Cryptography_HAS_NEXTPROTONEG``.
649 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400650 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100651 def _requires_decorator(func):
652 if not flag:
653 @wraps(func)
654 def explode(*args, **kwargs):
655 raise NotImplementedError(error)
656 return explode
657 else:
658 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400659
Cory Benfieldef404df2016-03-29 15:32:48 +0100660 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400661
662
Cory Benfieldef404df2016-03-29 15:32:48 +0100663_requires_npn = _make_requires(
664 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
665)
Cory Benfield7907e332015-04-13 17:18:25 -0400666
667
Cory Benfieldef404df2016-03-29 15:32:48 +0100668_requires_alpn = _make_requires(
669 _lib.Cryptography_HAS_ALPN, "ALPN not available"
670)
Cory Benfielde6f35882016-03-29 11:21:04 +0100671
Cory Benfielde6f35882016-03-29 11:21:04 +0100672
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800673class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000674 """
675 A class representing an SSL session. A session defines certain connection
676 parameters which may be re-used to speed up the setup of subsequent
677 connections.
678
679 .. versionadded:: 0.14
680 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800681 pass
682
683
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684class Context(object):
685 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100686 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400687 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000688
689 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
690 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691 """
692 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800693 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500694 SSLv3_METHOD: "SSLv3_method",
695 SSLv23_METHOD: "SSLv23_method",
696 TLSv1_METHOD: "TLSv1_method",
697 TLSv1_1_METHOD: "TLSv1_1_method",
698 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400699 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500700 _methods = dict(
701 (identifier, getattr(_lib, name))
702 for (identifier, name) in _methods.items()
703 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704
705 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500706 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707 raise TypeError("method must be an integer")
708
709 try:
710 method_func = self._methods[method]
711 except KeyError:
712 raise ValueError("No such protocol")
713
714 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700715 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700718 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500719 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800720
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600721 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
722 # will be auto-selected. This function was added in 1.0.2 and made a
723 # noop in 1.1.0+ (where it is set automatically).
724 try:
725 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
726 _openssl_assert(res == 1)
727 except AttributeError:
728 pass
729
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800731 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800732 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800733 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800734 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 self._verify_callback = None
736 self._info_callback = None
737 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000739 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100740 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000741 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100742 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400743 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100744 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000745 self._ocsp_helper = None
746 self._ocsp_callback = None
747 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500749 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800751 def load_verify_locations(self, cafile, capath=None):
752 """
753 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000754 chain. Note that the certificates have to be in PEM format.
755
756 If capath is passed, it must be a directory prepared using the
757 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
758 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800759
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400760 :param cafile: In which file we can find the certificates (``bytes`` or
761 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800762 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400763 (``bytes`` or ``unicode``).
764
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800765 :return: None
766 """
767 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500768 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400769 else:
770 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800771
772 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500773 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400774 else:
775 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776
Alex Gaynor62da94d2015-09-05 14:37:34 -0400777 load_result = _lib.SSL_CTX_load_verify_locations(
778 self._context, cafile, capath
779 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500781 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def _wrap_callback(self, callback):
784 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800785 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 return callback(size, verify, self._passphrase_userdata)
787 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800788 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790 def set_passwd_cb(self, callback, userdata=None):
791 """
Alex Chand072cae2018-02-15 09:57:59 +0000792 Set the passphrase callback. This function will be called
793 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794
Alex Chand072cae2018-02-15 09:57:59 +0000795 :param callback: The Python callback to use. This must accept three
796 positional arguments. First, an integer giving the maximum length
797 of the passphrase it may return. If the returned passphrase is
798 longer than this, it will be truncated. Second, a boolean value
799 which will be true if the user should be prompted for the
800 passphrase twice and the callback should verify that the two values
801 supplied are equal. Third, the value given as the *userdata*
802 parameter to :meth:`set_passwd_cb`. The *callback* must return
803 a byte string. If an error occurs, *callback* should return a false
804 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800805 :param userdata: (optional) A Python object which will be given as
806 argument to the callback
807 :return: None
808 """
809 if not callable(callback):
810 raise TypeError("callback must be callable")
811
812 self._passphrase_helper = self._wrap_callback(callback)
813 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500814 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815 self._context, self._passphrase_callback)
816 self._passphrase_userdata = userdata
817
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 def set_default_verify_paths(self):
819 """
Alex Chand072cae2018-02-15 09:57:59 +0000820 Specify that the platform provided CA certificates are to be used for
821 verification purposes. This method has some caveats related to the
822 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
823
824 * macOS will only load certificates using this method if the user has
825 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
826 in the default location.
827 * Windows will not work.
828 * manylinux1 cryptography wheels will work on most common Linux
829 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
830 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800831
832 :return: None
833 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500834 # SSL_CTX_set_default_verify_paths will attempt to load certs from
835 # both a cafile and capath that are set at compile time. However,
836 # it will first check environment variables and, if present, load
837 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500838 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400839 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500840 # After attempting to set default_verify_paths we need to know whether
841 # to go down the fallback path.
842 # First we'll check to see if any env vars have been set. If so,
843 # we won't try to do anything else because the user has set the path
844 # themselves.
845 dir_env_var = _ffi.string(
846 _lib.X509_get_default_cert_dir_env()
847 ).decode("ascii")
848 file_env_var = _ffi.string(
849 _lib.X509_get_default_cert_file_env()
850 ).decode("ascii")
851 if not self._check_env_vars_set(dir_env_var, file_env_var):
852 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
853 default_file = _ffi.string(_lib.X509_get_default_cert_file())
854 # Now we check to see if the default_dir and default_file are set
855 # to the exact values we use in our manylinux1 builds. If they are
856 # then we know to load the fallbacks
857 if (
858 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
859 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
860 ):
861 # This is manylinux1, let's load our fallback paths
862 self._fallback_default_verify_paths(
863 _CERTIFICATE_FILE_LOCATIONS,
864 _CERTIFICATE_PATH_LOCATIONS
865 )
866
867 def _check_env_vars_set(self, dir_env_var, file_env_var):
868 """
869 Check to see if the default cert dir/file environment vars are present.
870
871 :return: bool
872 """
873 return (
874 os.environ.get(file_env_var) is not None or
875 os.environ.get(dir_env_var) is not None
876 )
877
878 def _fallback_default_verify_paths(self, file_path, dir_path):
879 """
880 Default verify paths are based on the compiled version of OpenSSL.
881 However, when pyca/cryptography is compiled as a manylinux1 wheel
882 that compiled location can potentially be wrong. So, like Go, we
883 will try a predefined set of paths and attempt to load roots
884 from there.
885
886 :return: None
887 """
888 for cafile in file_path:
889 if os.path.isfile(cafile):
890 self.load_verify_locations(cafile)
891 break
892
893 for capath in dir_path:
894 if os.path.isdir(capath):
895 self.load_verify_locations(None, capath)
896 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800897
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 def use_certificate_chain_file(self, certfile):
899 """
Alex Chand072cae2018-02-15 09:57:59 +0000900 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800901
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400902 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000903 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400904
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905 :return: None
906 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400907 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800908
Alex Gaynor62da94d2015-09-05 14:37:34 -0400909 result = _lib.SSL_CTX_use_certificate_chain_file(
910 self._context, certfile
911 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800912 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500913 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800914
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800915 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800916 """
917 Load a certificate from a file
918
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400919 :param certfile: The name of the certificate file (``bytes`` or
920 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000921 :param filetype: (optional) The encoding of the file, which is either
922 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
923 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400924
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925 :return: None
926 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400927 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500928 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800929 raise TypeError("filetype must be an integer")
930
Alex Gaynor62da94d2015-09-05 14:37:34 -0400931 use_result = _lib.SSL_CTX_use_certificate_file(
932 self._context, certfile, filetype
933 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800934 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500935 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800936
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800937 def use_certificate(self, cert):
938 """
939 Load a certificate from a X509 object
940
941 :param cert: The X509 object
942 :return: None
943 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800944 if not isinstance(cert, X509):
945 raise TypeError("cert must be an X509 instance")
946
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500947 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800948 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500949 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800950
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951 def add_extra_chain_cert(self, certobj):
952 """
953 Add certificate to chain
954
955 :param certobj: The X509 certificate object to add to the chain
956 :return: None
957 """
958 if not isinstance(certobj, X509):
959 raise TypeError("certobj must be an X509 instance")
960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 copy = _lib.X509_dup(certobj._x509)
962 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800963 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500964 # TODO: This is untested.
965 _lib.X509_free(copy)
966 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800968 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500969 if self._passphrase_helper is not None:
970 self._passphrase_helper.raise_if_problem(Error)
971
972 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800973
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400974 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975 """
976 Load a private key from a file
977
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400978 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000979 :param filetype: (optional) The encoding of the file, which is either
980 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
981 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400982
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983 :return: None
984 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400985 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400987 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800988 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500989 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990 raise TypeError("filetype must be an integer")
991
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500992 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800993 self._context, keyfile, filetype)
994 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800995 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997 def use_privatekey(self, pkey):
998 """
999 Load a private key from a PKey object
1000
1001 :param pkey: The PKey object
1002 :return: None
1003 """
1004 if not isinstance(pkey, PKey):
1005 raise TypeError("pkey must be a PKey instance")
1006
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001007 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001008 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001009 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011 def check_privatekey(self):
1012 """
Alex Chand072cae2018-02-15 09:57:59 +00001013 Check if the private key (loaded with :meth:`use_privatekey`) matches
1014 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015
Alex Chand072cae2018-02-15 09:57:59 +00001016 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001018 if not _lib.SSL_CTX_check_private_key(self._context):
1019 _raise_current_error()
1020
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021 def load_client_ca(self, cafile):
1022 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001023 Load the trusted certificates that will be sent to the client. Does
1024 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001025 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001027 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028 :return: None
1029 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001030 ca_list = _lib.SSL_load_client_CA_file(
1031 _text_to_bytes_and_warn("cafile", cafile)
1032 )
1033 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001034 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035
1036 def set_session_id(self, buf):
1037 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001038 Set the session id to *buf* within which a session can be reused for
1039 this Context object. This is needed when doing session resumption,
1040 because there is no way for a stored session to know which Context
1041 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001043 :param bytes buf: The session id.
1044
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045 :returns: None
1046 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001047 buf = _text_to_bytes_and_warn("buf", buf)
1048 _openssl_assert(
1049 _lib.SSL_CTX_set_session_id_context(
1050 self._context,
1051 buf,
1052 len(buf),
1053 ) == 1
1054 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
1056 def set_session_cache_mode(self, mode):
1057 """
Alex Chand072cae2018-02-15 09:57:59 +00001058 Set the behavior of the session cache used by all connections using
1059 this Context. The previously set mode is returned. See
1060 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
1062 :param mode: One or more of the SESS_CACHE_* flags (combine using
1063 bitwise or)
1064 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001065
1066 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001068 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001069 raise TypeError("mode must be an integer")
1070
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001071 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 def get_session_cache_mode(self):
1074 """
Alex Chand072cae2018-02-15 09:57:59 +00001075 Get the current session cache mode.
1076
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001077 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001078
1079 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083 def set_verify(self, mode, callback):
1084 """
Alex Chand072cae2018-02-15 09:57:59 +00001085 et the verification flags for this Context object to *mode* and specify
1086 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
Alex Chand072cae2018-02-15 09:57:59 +00001088 :param mode: The verify mode, this should be one of
1089 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1090 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1091 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1092 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1093 :param callback: The Python callback to use. This should take five
1094 arguments: A Connection object, an X509 object, and three integer
1095 variables, which are in turn potential error number, error depth
1096 and return code. *callback* should return True if verification
1097 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098 :return: None
1099
1100 See SSL_CTX_set_verify(3SSL) for further details.
1101 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001102 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001103 raise TypeError("mode must be an integer")
1104
1105 if not callable(callback):
1106 raise TypeError("callback must be callable")
1107
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001108 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001109 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001110 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001112 def set_verify_depth(self, depth):
1113 """
Alex Chand072cae2018-02-15 09:57:59 +00001114 Set the maximum depth for the certificate chain verification that shall
1115 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001116
1117 :param depth: An integer specifying the verify depth
1118 :return: None
1119 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001120 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001121 raise TypeError("depth must be an integer")
1122
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001123 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001125 def get_verify_mode(self):
1126 """
Alex Chand072cae2018-02-15 09:57:59 +00001127 Retrieve the Context object's verify mode, as set by
1128 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001129
1130 :return: The verify mode
1131 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001132 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001133
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001134 def get_verify_depth(self):
1135 """
Alex Chand072cae2018-02-15 09:57:59 +00001136 Retrieve the Context object's verify depth, as set by
1137 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138
1139 :return: The verify depth
1140 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143 def load_tmp_dh(self, dhfile):
1144 """
1145 Load parameters for Ephemeral Diffie-Hellman
1146
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001147 :param dhfile: The file to load EDH parameters from (``bytes`` or
1148 ``unicode``).
1149
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001150 :return: None
1151 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001152 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001153
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001154 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001156 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001158
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1160 dh = _ffi.gc(dh, _lib.DH_free)
1161 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001162
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001163 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001164 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001165 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001166
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001167 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001168 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1169 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001170
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001171 :return: None
1172 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001173 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001174
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001175 def set_cipher_list(self, cipher_list):
1176 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001177 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001178
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001179 See the OpenSSL manual for more information (e.g.
1180 :manpage:`ciphers(1)`).
1181
1182 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183 :return: None
1184 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001185 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001186
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001187 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001188 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001189
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001190 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001191 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001192 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001193 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1194 # ciphers even if you pass an invalid cipher. Applications (like
1195 # Twisted) have tests that depend on an error being raised if an
1196 # invalid cipher string is passed, but without the following check
1197 # for the TLS 1.3 specific cipher suites it would never error.
1198 tmpconn = Connection(self, None)
Mark Williamsdf2480d2019-02-14 19:30:07 -08001199 if (
1200 tmpconn.get_cipher_list() == [
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001201 'TLS_AES_256_GCM_SHA384',
1202 'TLS_CHACHA20_POLY1305_SHA256',
1203 'TLS_AES_128_GCM_SHA256'
1204 ]
Mark Williamsdf2480d2019-02-14 19:30:07 -08001205 ):
1206 raise Error(
1207 [
1208 (
1209 'SSL routines',
1210 'SSL_CTX_set_cipher_list',
1211 'no cipher match',
1212 ),
1213 ],
1214 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001215
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001216 def set_client_ca_list(self, certificate_authorities):
1217 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001218 Set the list of preferred client certificate signers for this server
1219 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001220
Alex Gaynor62da94d2015-09-05 14:37:34 -04001221 This list of certificate authorities will be sent to the client when
1222 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001223
1224 :param certificate_authorities: a sequence of X509Names.
1225 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001226
1227 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001228 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001229 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001230 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001231
1232 try:
1233 for ca_name in certificate_authorities:
1234 if not isinstance(ca_name, X509Name):
1235 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001236 "client CAs must be X509Name objects, not %s "
1237 "objects" % (
1238 type(ca_name).__name__,
1239 )
1240 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001241 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001242 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001244 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001245 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001246 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001247 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001248 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001249 raise
1250
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001251 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001252
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001253 def add_client_ca(self, certificate_authority):
1254 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001255 Add the CA certificate to the list of preferred signers for this
1256 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001257
1258 The list of certificate authorities will be sent to the client when the
1259 server requests a client certificate.
1260
1261 :param certificate_authority: certificate authority's X509 certificate.
1262 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001263
1264 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001265 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001266 if not isinstance(certificate_authority, X509):
1267 raise TypeError("certificate_authority must be an X509 instance")
1268
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001269 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001270 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001271 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001272
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273 def set_timeout(self, timeout):
1274 """
Alex Chand072cae2018-02-15 09:57:59 +00001275 Set the timeout for newly created sessions for this Context object to
1276 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1277 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001278
Alex Chand072cae2018-02-15 09:57:59 +00001279 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001280 :return: The previous session timeout
1281 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001282 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001283 raise TypeError("timeout must be an integer")
1284
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001285 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001286
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287 def get_timeout(self):
1288 """
Alex Chand072cae2018-02-15 09:57:59 +00001289 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1290 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001291
1292 :return: The session timeout
1293 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001294 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001295
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296 def set_info_callback(self, callback):
1297 """
Alex Chand072cae2018-02-15 09:57:59 +00001298 Set the information callback to *callback*. This function will be
1299 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001300
Alex Chand072cae2018-02-15 09:57:59 +00001301 :param callback: The Python callback to use. This should take three
1302 arguments: a Connection object and two integers. The first integer
1303 specifies where in the SSL handshake the function was called, and
1304 the other the return code from a (possibly failed) internal
1305 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001306 :return: None
1307 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001308 @wraps(callback)
1309 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001310 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001311 self._info_callback = _ffi.callback(
1312 "void (*)(const SSL *, int, int)", wrapper)
1313 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001314
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001315 def get_app_data(self):
1316 """
Alex Chand072cae2018-02-15 09:57:59 +00001317 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001318
1319 :return: The application data
1320 """
1321 return self._app_data
1322
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001323 def set_app_data(self, data):
1324 """
1325 Set the application data (will be returned from get_app_data())
1326
1327 :param data: Any Python object
1328 :return: None
1329 """
1330 self._app_data = data
1331
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001332 def get_cert_store(self):
1333 """
Alex Chand072cae2018-02-15 09:57:59 +00001334 Get the certificate store for the context. This can be used to add
1335 "trusted" certificates without using the
1336 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001337
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001338 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001339 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001340 store = _lib.SSL_CTX_get_cert_store(self._context)
1341 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001342 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001343 return None
1344
1345 pystore = X509Store.__new__(X509Store)
1346 pystore._store = store
1347 return pystore
1348
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001349 def set_options(self, options):
1350 """
1351 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001352 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001353
1354 :param options: The options to add.
1355 :return: The new option bitmask.
1356 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001357 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358 raise TypeError("options must be an integer")
1359
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001360 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001361
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001362 def set_mode(self, mode):
1363 """
Alex Chand072cae2018-02-15 09:57:59 +00001364 Add modes via bitmask. Modes set before are not cleared! This method
1365 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001366
1367 :param mode: The mode to add.
1368 :return: The new mode bitmask.
1369 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001370 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001371 raise TypeError("mode must be an integer")
1372
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001373 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001374
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001375 def set_tlsext_servername_callback(self, callback):
1376 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001377 Specify a callback function to be called when clients specify a server
1378 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001379
1380 :param callback: The callback function. It will be invoked with one
1381 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001382
1383 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001384 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 @wraps(callback)
1386 def wrapper(ssl, alert, arg):
1387 callback(Connection._reverse_mapping[ssl])
1388 return 0
1389
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001390 self._tlsext_servername_callback = _ffi.callback(
David Benjamince5c3842018-05-21 21:14:46 -04001391 "int (*)(SSL *, int *, void *)", wrapper)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001392 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001393 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001394
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001395 def set_tlsext_use_srtp(self, profiles):
1396 """
1397 Enable support for negotiating SRTP keying material.
1398
1399 :param bytes profiles: A colon delimited list of protection profile
1400 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1401 :return: None
1402 """
1403 if not isinstance(profiles, bytes):
1404 raise TypeError("profiles must be a byte string.")
1405
1406 _openssl_assert(
1407 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1408 )
1409
Cory Benfield10b277f2015-04-13 17:12:42 -04001410 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001411 def set_npn_advertise_callback(self, callback):
1412 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001413 Specify a callback function that will be called when offering `Next
1414 Protocol Negotiation
1415 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001416
1417 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001418 argument, the :class:`Connection` instance. It should return a
1419 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001420 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001421
1422 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001423 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001424 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001425 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1426 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001427 _lib.SSL_CTX_set_next_protos_advertised_cb(
1428 self._context, self._npn_advertise_callback, _ffi.NULL)
1429
Cory Benfield10b277f2015-04-13 17:12:42 -04001430 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001431 def set_npn_select_callback(self, callback):
1432 """
1433 Specify a callback function that will be called when a server offers
1434 Next Protocol Negotiation options.
1435
1436 :param callback: The callback function. It will be invoked with two
1437 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001438 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1439 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001440
1441 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001442 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001443 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001444 self._npn_select_helper = _NpnSelectHelper(callback)
1445 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001446 _lib.SSL_CTX_set_next_proto_select_cb(
1447 self._context, self._npn_select_callback, _ffi.NULL)
1448
Cory Benfield7907e332015-04-13 17:18:25 -04001449 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001450 def set_alpn_protos(self, protos):
1451 """
Alex Chand072cae2018-02-15 09:57:59 +00001452 Specify the protocols that the client is prepared to speak after the
1453 TLS connection has been negotiated using Application Layer Protocol
1454 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001455
1456 :param protos: A list of the protocols to be offered to the server.
1457 This list should be a Python list of bytestrings representing the
1458 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1459 """
1460 # Take the list of protocols and join them together, prefixing them
1461 # with their lengths.
1462 protostr = b''.join(
1463 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1464 )
1465
1466 # Build a C string from the list. We don't need to save this off
1467 # because OpenSSL immediately copies the data out.
1468 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001469 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001470
Cory Benfield7907e332015-04-13 17:18:25 -04001471 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001472 def set_alpn_select_callback(self, callback):
1473 """
Alex Chand072cae2018-02-15 09:57:59 +00001474 Specify a callback function that will be called on the server when a
1475 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001476
1477 :param callback: The callback function. It will be invoked with two
1478 arguments: the Connection, and a list of offered protocols as
1479 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001480 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001481 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001482 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001483 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001484 _lib.SSL_CTX_set_alpn_select_cb(
1485 self._context, self._alpn_select_callback, _ffi.NULL)
1486
Cory Benfield496652a2017-01-24 11:42:56 +00001487 def _set_ocsp_callback(self, helper, data):
1488 """
1489 This internal helper does the common work for
1490 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1491 almost all of it.
1492 """
1493 self._ocsp_helper = helper
1494 self._ocsp_callback = helper.callback
1495 if data is None:
1496 self._ocsp_data = _ffi.NULL
1497 else:
1498 self._ocsp_data = _ffi.new_handle(data)
1499
1500 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1501 self._context, self._ocsp_callback
1502 )
1503 _openssl_assert(rc == 1)
1504 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1505 _openssl_assert(rc == 1)
1506
1507 def set_ocsp_server_callback(self, callback, data=None):
1508 """
1509 Set a callback to provide OCSP data to be stapled to the TLS handshake
1510 on the server side.
1511
1512 :param callback: The callback function. It will be invoked with two
1513 arguments: the Connection, and the optional arbitrary data you have
1514 provided. The callback must return a bytestring that contains the
1515 OCSP data to staple to the handshake. If no OCSP data is available
1516 for this connection, return the empty bytestring.
1517 :param data: Some opaque data that will be passed into the callback
1518 function when called. This can be used to avoid needing to do
1519 complex data lookups or to keep track of what context is being
1520 used. This parameter is optional.
1521 """
1522 helper = _OCSPServerCallbackHelper(callback)
1523 self._set_ocsp_callback(helper, data)
1524
1525 def set_ocsp_client_callback(self, callback, data=None):
1526 """
1527 Set a callback to validate OCSP data stapled to the TLS handshake on
1528 the client side.
1529
1530 :param callback: The callback function. It will be invoked with three
1531 arguments: the Connection, a bytestring containing the stapled OCSP
1532 assertion, and the optional arbitrary data you have provided. The
1533 callback must return a boolean that indicates the result of
1534 validating the OCSP data: ``True`` if the OCSP data is valid and
1535 the certificate can be trusted, or ``False`` if either the OCSP
1536 data is invalid or the certificate has been revoked.
1537 :param data: Some opaque data that will be passed into the callback
1538 function when called. This can be used to avoid needing to do
1539 complex data lookups or to keep track of what context is being
1540 used. This parameter is optional.
1541 """
1542 helper = _OCSPClientCallbackHelper(callback)
1543 self._set_ocsp_callback(helper, data)
1544
Alex Chanc6077062016-11-18 13:53:39 +00001545
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001546class Connection(object):
1547 """
1548 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001549 _reverse_mapping = WeakValueDictionary()
1550
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001551 def __init__(self, context, socket=None):
1552 """
1553 Create a new Connection object, using the given OpenSSL.SSL.Context
1554 instance and socket.
1555
1556 :param context: An SSL Context to use for this connection
1557 :param socket: The socket to use for transport layer
1558 """
1559 if not isinstance(context, Context):
1560 raise TypeError("context must be a Context instance")
1561
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001562 ssl = _lib.SSL_new(context._context)
1563 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001564 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1565 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1566 # even though there is still data on the underlying transport.
1567 # See https://github.com/openssl/openssl/issues/6234 for more details.
1568 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001569 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001570 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001572 # References to strings used for Next Protocol Negotiation. OpenSSL's
1573 # header files suggest that these might get copied at some point, but
1574 # doesn't specify when, so we store them here to make sure they don't
1575 # get freed before OpenSSL uses them.
1576 self._npn_advertise_callback_args = None
1577 self._npn_select_callback_args = None
1578
Cory Benfield12eae892014-06-07 15:42:56 +01001579 # References to strings used for Application Layer Protocol
1580 # Negotiation. These strings get copied at some point but it's well
1581 # after the callback returns, so we have to hang them somewhere to
1582 # avoid them getting freed.
1583 self._alpn_select_callback_args = None
1584
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001585 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001586
1587 if socket is None:
1588 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001589 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001590 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001591 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001592
Alex Gaynora829e902016-06-04 18:16:01 -07001593 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1594 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001595
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001596 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001598 self._into_ssl = None
1599 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001600 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001601 set_result = _lib.SSL_set_fd(
1602 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001603 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001604
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001605 def __getattr__(self, name):
1606 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001607 Look up attributes on the wrapped socket object if they are not found
1608 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001609 """
kjav0b66fa12015-09-02 11:51:26 +01001610 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001611 raise AttributeError("'%s' object has no attribute '%s'" % (
1612 self.__class__.__name__, name
1613 ))
kjav0b66fa12015-09-02 11:51:26 +01001614 else:
1615 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001616
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001618 if self._context._verify_helper is not None:
1619 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001620 if self._context._npn_advertise_helper is not None:
1621 self._context._npn_advertise_helper.raise_if_problem()
1622 if self._context._npn_select_helper is not None:
1623 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001624 if self._context._alpn_select_helper is not None:
1625 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001626 if self._context._ocsp_helper is not None:
1627 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001628
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001629 error = _lib.SSL_get_error(ssl, result)
1630 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001632 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001633 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001634 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001636 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001637 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001638 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001639 elif error == _lib.SSL_ERROR_SYSCALL:
1640 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001641 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001642 if platform == "win32":
1643 errno = _ffi.getwinerror()[0]
1644 else:
1645 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001646
1647 if errno != 0:
1648 raise SysCallError(errno, errorcode.get(errno))
1649 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001650 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001651 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001652 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001653 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001654 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001656 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001657
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001658 def get_context(self):
1659 """
Alex Chand072cae2018-02-15 09:57:59 +00001660 Retrieve the :class:`Context` object associated with this
1661 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001663 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001664
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001665 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001666 """
Alex Chand072cae2018-02-15 09:57:59 +00001667 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001668
Alex Chand072cae2018-02-15 09:57:59 +00001669 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672 if not isinstance(context, Context):
1673 raise TypeError("context must be a Context instance")
1674
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001675 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001676 self._context = context
1677
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001678 def get_servername(self):
1679 """
1680 Retrieve the servername extension value if provided in the client hello
1681 message, or None if there wasn't one.
1682
Alex Chand072cae2018-02-15 09:57:59 +00001683 :return: A byte string giving the server name or :data:`None`.
1684
1685 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001687 name = _lib.SSL_get_servername(
1688 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1689 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001690 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001691 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001692
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001694
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001695 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 """
1697 Set the value of the servername extension to send in the client hello.
1698
1699 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001700
1701 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001703 if not isinstance(name, bytes):
1704 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001705 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001706 raise TypeError("name must not contain NUL byte")
1707
1708 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001710
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 def pending(self):
1712 """
Alex Chand072cae2018-02-15 09:57:59 +00001713 Get the number of bytes that can be safely read from the SSL buffer
1714 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715
1716 :return: The number of bytes available in the receive buffer.
1717 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721 """
1722 Send data on the connection. NOTE: If you get one of the WantRead,
1723 WantWrite or WantX509Lookup exceptions on this, you have to call the
1724 method again with the SAME buffer.
1725
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001726 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001727 :param flags: (optional) Included for compatibility with the socket
1728 API, the value is ignored
1729 :return: The number of bytes written
1730 """
Abraham Martine82326c2015-02-04 10:18:10 +00001731 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001732 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001733
Daniel Holth079c9632019-11-17 22:45:52 -05001734 with _from_buffer(buf) as data:
1735 # check len(buf) instead of len(data) for testability
1736 if len(buf) > 2147483647:
1737 raise ValueError(
1738 "Cannot send more than 2**31-1 bytes at once."
1739 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001740
Daniel Holth079c9632019-11-17 22:45:52 -05001741 result = _lib.SSL_write(self._ssl, data, len(data))
1742 self._raise_ssl_error(self._ssl, result)
1743
1744 return result
1745
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001746 write = send
1747
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001748 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001750 Send "all" data on the connection. This calls send() repeatedly until
1751 all data is sent. If an error occurs, it's impossible to tell how much
1752 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001753
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001754 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001755 :param flags: (optional) Included for compatibility with the socket
1756 API, the value is ignored
1757 :return: The number of bytes written
1758 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001759 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001760
Daniel Holth079c9632019-11-17 22:45:52 -05001761 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001762
Daniel Holth079c9632019-11-17 22:45:52 -05001763 left_to_send = len(buf)
1764 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001765
Daniel Holth079c9632019-11-17 22:45:52 -05001766 while left_to_send:
1767 # SSL_write's num arg is an int,
1768 # so we cannot send more than 2**31-1 bytes at once.
1769 result = _lib.SSL_write(
1770 self._ssl,
1771 data + total_sent,
1772 min(left_to_send, 2147483647)
1773 )
1774 self._raise_ssl_error(self._ssl, result)
1775 total_sent += result
1776 left_to_send -= result
1777
1778 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001779
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001780 def recv(self, bufsiz, flags=None):
1781 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001782 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001783
1784 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001785 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1786 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001787 :return: The string read from the Connection
1788 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001789 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001790 if flags is not None and flags & socket.MSG_PEEK:
1791 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1792 else:
1793 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001794 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001795 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001796 read = recv
1797
Cory Benfield62d10332014-06-15 10:03:41 +01001798 def recv_into(self, buffer, nbytes=None, flags=None):
1799 """
Alex Chand072cae2018-02-15 09:57:59 +00001800 Receive data on the connection and copy it directly into the provided
1801 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001802
1803 :param buffer: The buffer to copy into.
1804 :param nbytes: (optional) The maximum number of bytes to read into the
1805 buffer. If not present, defaults to the size of the buffer. If
1806 larger than the size of the buffer, is reduced to the size of the
1807 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001808 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1809 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001810 :return: The number of bytes read into the buffer.
1811 """
1812 if nbytes is None:
1813 nbytes = len(buffer)
1814 else:
1815 nbytes = min(nbytes, len(buffer))
1816
1817 # We need to create a temporary buffer. This is annoying, it would be
1818 # better if we could pass memoryviews straight into the SSL_read call,
1819 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001820 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001821 if flags is not None and flags & socket.MSG_PEEK:
1822 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1823 else:
1824 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001825 self._raise_ssl_error(self._ssl, result)
1826
1827 # This strange line is all to avoid a memory copy. The buffer protocol
1828 # should allow us to assign a CFFI buffer to the LHS of this line, but
1829 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001830 # wrap it in a memoryview.
1831 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001832
1833 return result
1834
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001835 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001836 if _lib.BIO_should_retry(bio):
1837 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001838 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001839 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001840 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001841 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001842 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001843 # TODO: This is untested. I think io_special means the socket
1844 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001845 raise ValueError("BIO_should_io_special")
1846 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001847 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001848 raise ValueError("unknown bio failure")
1849 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001850 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001851 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001852
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001853 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001854 """
Alex Chand072cae2018-02-15 09:57:59 +00001855 If the Connection was created with a memory BIO, this method can be
1856 used to read bytes from the write end of that memory BIO. Many
1857 Connection methods will add bytes which must be read in this manner or
1858 the buffer will eventually fill up and the Connection will be able to
1859 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860
1861 :param bufsiz: The maximum number of bytes to read
1862 :return: The string read.
1863 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001864 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001865 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001867 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001868 raise TypeError("bufsiz must be an integer")
1869
Cory Benfielde62840e2016-11-28 12:17:08 +00001870 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001871 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001872 if result <= 0:
1873 self._handle_bio_errors(self._from_ssl, result)
1874
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001875 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001876
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001877 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001878 """
Alex Chand072cae2018-02-15 09:57:59 +00001879 If the Connection was created with a memory BIO, this method can be
1880 used to add bytes to the read end of that memory BIO. The Connection
1881 can then read the bytes (for example, in response to a call to
1882 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001883
1884 :param buf: The string to put into the memory BIO.
1885 :return: The number of bytes written
1886 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001887 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001888
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001889 if self._into_ssl is None:
1890 raise TypeError("Connection sock was not None")
1891
Daniel Holth079c9632019-11-17 22:45:52 -05001892 with _from_buffer(buf) as data:
1893 result = _lib.BIO_write(self._into_ssl, data, len(data))
1894 if result <= 0:
1895 self._handle_bio_errors(self._into_ssl, result)
1896 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001897
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898 def renegotiate(self):
1899 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001900 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001901
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001902 :return: True if the renegotiation can be started, False otherwise
1903 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001905 if not self.renegotiate_pending():
1906 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1907 return True
1908 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001909
1910 def do_handshake(self):
1911 """
Alex Chand072cae2018-02-15 09:57:59 +00001912 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001913 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001914 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915
1916 :return: None.
1917 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001918 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001919 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001920
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 def renegotiate_pending(self):
1922 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001923 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001924 a renegotiation is finished.
1925
1926 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001927 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001928 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001929 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930
1931 def total_renegotiations(self):
1932 """
1933 Find out the total number of renegotiations.
1934
1935 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001936 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001937 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001938 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001940 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941 """
Alex Chand072cae2018-02-15 09:57:59 +00001942 Call the :meth:`connect` method of the underlying socket and set up SSL
1943 on the socket, using the :class:`Context` object supplied to this
1944 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001945
1946 :param addr: A remote address
1947 :return: What the socket's connect method returns
1948 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001949 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001951
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001952 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001953 """
Alex Chand072cae2018-02-15 09:57:59 +00001954 Call the :meth:`connect_ex` method of the underlying socket and set up
1955 SSL on the socket, using the Context object supplied to this Connection
1956 object at creation. Note that if the :meth:`connect_ex` method of the
1957 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
1959 :param addr: A remove address
1960 :return: What the socket's connect_ex method returns
1961 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001962 connect_ex = self._socket.connect_ex
1963 self.set_connect_state()
1964 return connect_ex(addr)
1965
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966 def accept(self):
1967 """
Alex Chand072cae2018-02-15 09:57:59 +00001968 Call the :meth:`accept` method of the underlying socket and set up SSL
1969 on the returned socket, using the Context object supplied to this
1970 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001971
Alex Chand072cae2018-02-15 09:57:59 +00001972 :return: A *(conn, addr)* pair where *conn* is the new
1973 :class:`Connection` object created, and *address* is as returned by
1974 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001975 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001976 client, addr = self._socket.accept()
1977 conn = Connection(self._context, client)
1978 conn.set_accept_state()
1979 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001981 def bio_shutdown(self):
1982 """
Alex Chand072cae2018-02-15 09:57:59 +00001983 If the Connection was created with a memory BIO, this method can be
1984 used to indicate that *end of file* has been reached on the read end of
1985 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001986
1987 :return: None
1988 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 if self._from_ssl is None:
1990 raise TypeError("Connection sock was not None")
1991
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001992 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001993
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994 def shutdown(self):
1995 """
Alex Chand072cae2018-02-15 09:57:59 +00001996 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997
1998 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001999 have sent closure alerts), False otherwise (in which case you
2000 call :meth:`recv` or :meth:`send` when the connection becomes
2001 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002002 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002003 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002005 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002006 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002007 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008 else:
2009 return False
2010
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011 def get_cipher_list(self):
2012 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002013 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002014
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002015 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016 """
2017 ciphers = []
2018 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002019 result = _lib.SSL_get_cipher_list(self._ssl, i)
2020 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002022 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002023 return ciphers
2024
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025 def get_client_ca_list(self):
2026 """
2027 Get CAs whose certificates are suggested for client authentication.
2028
Alex Chand072cae2018-02-15 09:57:59 +00002029 :return: If this is a server connection, the list of certificate
2030 authorities that will be sent or has been sent to the client, as
2031 controlled by this :class:`Connection`'s :class:`Context`.
2032
2033 If this is a client connection, the list will be empty until the
2034 connection with the server is established.
2035
2036 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002037 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002038 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2039 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002040 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002041 return []
2042
2043 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002044 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2045 name = _lib.sk_X509_NAME_value(ca_names, i)
2046 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002047 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002048
2049 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002050 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051 result.append(pyname)
2052 return result
2053
Aykee7f33452018-05-16 19:18:16 +02002054 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002056 The makefile() method is not implemented, since there is no dup
2057 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002058
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002059 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002060 """
Alex Gaynor83284952015-09-05 10:43:30 -04002061 raise NotImplementedError(
2062 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002063
2064 def get_app_data(self):
2065 """
Alex Chand072cae2018-02-15 09:57:59 +00002066 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002067
2068 :return: The application data
2069 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002070 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002072 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073 """
2074 Set application data
2075
Alex Chand072cae2018-02-15 09:57:59 +00002076 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002077 :return: None
2078 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002079 self._app_data = data
2080
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002081 def get_shutdown(self):
2082 """
Alex Chand072cae2018-02-15 09:57:59 +00002083 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002084
Alex Gaynor62da94d2015-09-05 14:37:34 -04002085 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2086 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002087 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002088 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002089
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002090 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002091 """
Alex Chand072cae2018-02-15 09:57:59 +00002092 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002093
Alex Chand072cae2018-02-15 09:57:59 +00002094 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002095 :return: None
2096 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002097 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002098 raise TypeError("state must be an integer")
2099
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002100 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002101
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002102 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002103 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002104 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002105
2106 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002107 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002108 """
kjavc704a2e2015-09-07 12:12:27 +01002109 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110
2111 def server_random(self):
2112 """
Alex Chand072cae2018-02-15 09:57:59 +00002113 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002114
2115 :return: A string representing the state
2116 """
Alex Gaynor93603062016-06-01 20:13:09 -07002117 session = _lib.SSL_get_session(self._ssl)
2118 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002119 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002120 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2121 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002122 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002123 _lib.SSL_get_server_random(self._ssl, outp, length)
2124 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002125
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002126 def client_random(self):
2127 """
Alex Chand072cae2018-02-15 09:57:59 +00002128 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002129
2130 :return: A string representing the state
2131 """
Alex Gaynor93603062016-06-01 20:13:09 -07002132 session = _lib.SSL_get_session(self._ssl)
2133 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002134 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002135
2136 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2137 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002138 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002139 _lib.SSL_get_client_random(self._ssl, outp, length)
2140 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002141
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002142 def master_key(self):
2143 """
Alex Chand072cae2018-02-15 09:57:59 +00002144 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002145
2146 :return: A string representing the state
2147 """
Alex Gaynor93603062016-06-01 20:13:09 -07002148 session = _lib.SSL_get_session(self._ssl)
2149 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002150 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002151
2152 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2153 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002154 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002155 _lib.SSL_SESSION_get_master_key(session, outp, length)
2156 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002157
Paul Kehrerbdb76392017-12-01 04:54:32 +08002158 def export_keying_material(self, label, olen, context=None):
2159 """
2160 Obtain keying material for application use.
2161
Alex Chand072cae2018-02-15 09:57:59 +00002162 :param: label - a disambiguating label string as described in RFC 5705
2163 :param: olen - the length of the exported key material in bytes
2164 :param: context - a per-association context value
2165 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002166 """
2167 outp = _no_zero_allocator("unsigned char[]", olen)
2168 context_buf = _ffi.NULL
2169 context_len = 0
2170 use_context = 0
2171 if context is not None:
2172 context_buf = context
2173 context_len = len(context)
2174 use_context = 1
2175 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2176 label, len(label),
2177 context_buf, context_len,
2178 use_context)
2179 _openssl_assert(success == 1)
2180 return _ffi.buffer(outp, olen)[:]
2181
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002182 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002183 """
Alex Chand072cae2018-02-15 09:57:59 +00002184 Call the :meth:`shutdown` method of the underlying socket.
2185 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002186
2187 :return: What the socket's shutdown() method returns
2188 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002189 return self._socket.shutdown(*args, **kwargs)
2190
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002191 def get_certificate(self):
2192 """
2193 Retrieve the local certificate (if any)
2194
2195 :return: The local certificate
2196 """
2197 cert = _lib.SSL_get_certificate(self._ssl)
2198 if cert != _ffi.NULL:
2199 _lib.X509_up_ref(cert)
2200 return X509._from_raw_x509_ptr(cert)
2201 return None
2202
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002203 def get_peer_certificate(self):
2204 """
2205 Retrieve the other side's certificate (if any)
2206
2207 :return: The peer's certificate
2208 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002209 cert = _lib.SSL_get_peer_certificate(self._ssl)
2210 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002211 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002212 return None
2213
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002214 def get_peer_cert_chain(self):
2215 """
2216 Retrieve the other side's certificate (if any)
2217
2218 :return: A list of X509 instances giving the peer's certificate chain,
2219 or None if it does not have one.
2220 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002221 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2222 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002223 return None
2224
2225 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002226 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002227 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002228 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002229 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002230 result.append(pycert)
2231 return result
2232
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002233 def want_read(self):
2234 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002235 Checks if more data has to be read from the transport layer to complete
2236 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002237
2238 :return: True iff more data has to be read
2239 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002240 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002241
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002242 def want_write(self):
2243 """
2244 Checks if there is data to write to the transport layer to complete an
2245 operation.
2246
2247 :return: True iff there is data to write
2248 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002249 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002250
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002251 def set_accept_state(self):
2252 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002253 Set the connection to work in server mode. The handshake will be
2254 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002255
2256 :return: None
2257 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002258 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002259
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002260 def set_connect_state(self):
2261 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002262 Set the connection to work in client mode. The handshake will be
2263 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002264
2265 :return: None
2266 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002267 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002268
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002269 def get_session(self):
2270 """
2271 Returns the Session currently used.
2272
Alex Chand072cae2018-02-15 09:57:59 +00002273 :return: An instance of :class:`OpenSSL.SSL.Session` or
2274 :obj:`None` if no session exists.
2275
2276 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002277 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002278 session = _lib.SSL_get1_session(self._ssl)
2279 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002280 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002281
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002282 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002283 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002284 return pysession
2285
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002286 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002287 """
2288 Set the session to be used when the TLS/SSL connection is established.
2289
2290 :param session: A Session instance representing the session to use.
2291 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002292
2293 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002294 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002295 if not isinstance(session, Session):
2296 raise TypeError("session must be a Session instance")
2297
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002298 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002299 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002300 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002301
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002302 def _get_finished_message(self, function):
2303 """
Alex Chand072cae2018-02-15 09:57:59 +00002304 Helper to implement :meth:`get_finished` and
2305 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002306
Alex Chand072cae2018-02-15 09:57:59 +00002307 :param function: Either :data:`SSL_get_finished`: or
2308 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002309
Alex Chand072cae2018-02-15 09:57:59 +00002310 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002311 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002312 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002313 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002314 # The OpenSSL documentation says nothing about what might happen if the
2315 # count argument given is zero. Specifically, it doesn't say whether
2316 # the output buffer may be NULL in that case or not. Inspection of the
2317 # implementation reveals that it calls memcpy() unconditionally.
2318 # Section 7.1.4, paragraph 1 of the C standard suggests that
2319 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2320 # alone desirable) behavior (though it probably does on just about
2321 # every implementation...)
2322 #
2323 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2324 # one might expect) for the initial call so as to be safe against this
2325 # potentially undefined behavior.
2326 empty = _ffi.new("char[]", 0)
2327 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002328 if size == 0:
2329 # No Finished message so far.
2330 return None
2331
Cory Benfielde62840e2016-11-28 12:17:08 +00002332 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002333 function(self._ssl, buf, size)
2334 return _ffi.buffer(buf, size)[:]
2335
Fedor Brunner5747b932014-03-05 14:22:34 +01002336 def get_finished(self):
2337 """
Alex Chand072cae2018-02-15 09:57:59 +00002338 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002339
Alex Chand072cae2018-02-15 09:57:59 +00002340 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002341 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002342 :rtype: :class:`bytes` or :class:`NoneType`
2343
2344 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002345 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002346 return self._get_finished_message(_lib.SSL_get_finished)
2347
Fedor Brunner5747b932014-03-05 14:22:34 +01002348 def get_peer_finished(self):
2349 """
Alex Chand072cae2018-02-15 09:57:59 +00002350 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002351
Alex Chand072cae2018-02-15 09:57:59 +00002352 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002353 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002354 :rtype: :class:`bytes` or :class:`NoneType`
2355
2356 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002357 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002358 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002359
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002360 def get_cipher_name(self):
2361 """
2362 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002363
Alex Chand072cae2018-02-15 09:57:59 +00002364 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002365 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002366 :rtype: :class:`unicode` or :class:`NoneType`
2367
2368 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002369 """
2370 cipher = _lib.SSL_get_current_cipher(self._ssl)
2371 if cipher == _ffi.NULL:
2372 return None
2373 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002374 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2375 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002376
2377 def get_cipher_bits(self):
2378 """
2379 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002380
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002381 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002382 or :obj:`None` if no connection has been established.
2383 :rtype: :class:`int` or :class:`NoneType`
2384
2385 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002386 """
2387 cipher = _lib.SSL_get_current_cipher(self._ssl)
2388 if cipher == _ffi.NULL:
2389 return None
2390 else:
2391 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2392
2393 def get_cipher_version(self):
2394 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002395 Obtain the protocol version of the currently used cipher.
2396
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002397 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002398 or :obj:`None` if no connection has been established.
2399 :rtype: :class:`unicode` or :class:`NoneType`
2400
2401 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002402 """
2403 cipher = _lib.SSL_get_current_cipher(self._ssl)
2404 if cipher == _ffi.NULL:
2405 return None
2406 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002407 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002408 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002409
Jim Shaverabff1882015-05-27 09:15:55 -04002410 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002411 """
Alex Chand072cae2018-02-15 09:57:59 +00002412 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002413
2414 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002415 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002416 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002417 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002418 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002419 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002420 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002421
Jim Shaver208438c2015-05-28 09:52:38 -04002422 def get_protocol_version(self):
2423 """
Alex Chand072cae2018-02-15 09:57:59 +00002424 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002425
Alex Chand072cae2018-02-15 09:57:59 +00002426 :returns: The TLS version of the current connection. For example,
2427 it will return ``0x769`` for connections made over TLS version 1.
2428 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002429 """
2430 version = _lib.SSL_version(self._ssl)
2431 return version
2432
Cory Benfield10b277f2015-04-13 17:12:42 -04002433 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002434 def get_next_proto_negotiated(self):
2435 """
2436 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002437
2438 :returns: A bytestring of the protocol name. If no protocol has been
2439 negotiated yet, returns an empty string.
2440
2441 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002442 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002443 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002444 data = _ffi.new("unsigned char **")
2445 data_len = _ffi.new("unsigned int *")
2446
2447 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2448
Cory Benfieldcd010f62014-05-15 19:00:27 +01002449 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002450
Cory Benfield7907e332015-04-13 17:18:25 -04002451 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002452 def set_alpn_protos(self, protos):
2453 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002454 Specify the client's ALPN protocol list.
2455
2456 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002457
2458 :param protos: A list of the protocols to be offered to the server.
2459 This list should be a Python list of bytestrings representing the
2460 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2461 """
2462 # Take the list of protocols and join them together, prefixing them
2463 # with their lengths.
2464 protostr = b''.join(
2465 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2466 )
2467
2468 # Build a C string from the list. We don't need to save this off
2469 # because OpenSSL immediately copies the data out.
2470 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002471 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002472
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002473 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002474 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002475 """
2476 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002477
2478 :returns: A bytestring of the protocol name. If no protocol has been
2479 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002480 """
Cory Benfield12eae892014-06-07 15:42:56 +01002481 data = _ffi.new("unsigned char **")
2482 data_len = _ffi.new("unsigned int *")
2483
2484 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2485
Cory Benfielde8e9c382015-04-11 17:33:48 -04002486 if not data_len:
2487 return b''
2488
Cory Benfield12eae892014-06-07 15:42:56 +01002489 return _ffi.buffer(data[0], data_len[0])[:]
2490
Cory Benfield496652a2017-01-24 11:42:56 +00002491 def request_ocsp(self):
2492 """
2493 Called to request that the server sends stapled OCSP data, if
2494 available. If this is not called on the client side then the server
2495 will not send OCSP data. Should be used in conjunction with
2496 :meth:`Context.set_ocsp_client_callback`.
2497 """
2498 rc = _lib.SSL_set_tlsext_status_type(
2499 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2500 )
2501 _openssl_assert(rc == 1)
2502
Cory Benfield12eae892014-06-07 15:42:56 +01002503
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002504# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2505# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002506_lib.SSL_library_init()