blob: a228b73f8db3ed130399fa3247c55dbb60fa39ee [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
Mark Williams5d890a02019-11-17 19:56:26 -0800431NO_OVERLAPPING_PROTOCOLS = object()
432
433
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400434class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400435 """
436 Wrap a callback such that it can be used as an ALPN selection callback.
437 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400438
Cory Benfieldf1177e72015-04-12 09:11:49 -0400439 def __init__(self, callback):
440 _CallbackExceptionHelper.__init__(self)
441
442 @wraps(callback)
443 def wrapper(ssl, out, outlen, in_, inlen, arg):
444 try:
445 conn = Connection._reverse_mapping[ssl]
446
447 # The string passed to us is made up of multiple
448 # length-prefixed bytestrings. We need to split that into a
449 # list.
450 instr = _ffi.buffer(in_, inlen)[:]
451 protolist = []
452 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400453 encoded_len = indexbytes(instr, 0)
454 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400455 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400456 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400457
458 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800459 outbytes = callback(conn, protolist)
460 any_accepted = True
461 if outbytes is NO_OVERLAPPING_PROTOCOLS:
462 outbytes = b''
463 any_accepted = False
464 elif not isinstance(outbytes, _binary_type):
465 raise TypeError(
466 "ALPN callback must return a bytestring or the "
467 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
468 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400469
470 # Save our callback arguments on the connection object to make
471 # sure that they don't get freed before OpenSSL can use them.
472 # Then, return them in the appropriate output parameters.
473 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800474 _ffi.new("unsigned char *", len(outbytes)),
475 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400476 ]
477 outlen[0] = conn._alpn_select_callback_args[0][0]
478 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800479 if not any_accepted:
480 return _lib.SSL_TLSEXT_ERR_NOACK
481 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400482 except Exception as e:
483 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800484 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400485
486 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400487 ("int (*)(SSL *, unsigned char **, unsigned char *, "
488 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400489 wrapper
490 )
491
492
Cory Benfield496652a2017-01-24 11:42:56 +0000493class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
494 """
495 Wrap a callback such that it can be used as an OCSP callback for the server
496 side.
497
498 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
499 ways. For servers, that callback is expected to retrieve some OCSP data and
500 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
501 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
502 is expected to check the OCSP data, and returns a negative value on error,
503 0 if the response is not acceptable, or positive if it is. These are
504 mutually exclusive return code behaviours, and they mean that we need two
505 helpers so that we always return an appropriate error code if the user's
506 code throws an exception.
507
508 Given that we have to have two helpers anyway, these helpers are a bit more
509 helpery than most: specifically, they hide a few more of the OpenSSL
510 functions so that the user has an easier time writing these callbacks.
511
512 This helper implements the server side.
513 """
514
515 def __init__(self, callback):
516 _CallbackExceptionHelper.__init__(self)
517
518 @wraps(callback)
519 def wrapper(ssl, cdata):
520 try:
521 conn = Connection._reverse_mapping[ssl]
522
523 # Extract the data if any was provided.
524 if cdata != _ffi.NULL:
525 data = _ffi.from_handle(cdata)
526 else:
527 data = None
528
529 # Call the callback.
530 ocsp_data = callback(conn, data)
531
532 if not isinstance(ocsp_data, _binary_type):
533 raise TypeError("OCSP callback must return a bytestring.")
534
535 # If the OCSP data was provided, we will pass it to OpenSSL.
536 # However, we have an early exit here: if no OCSP data was
537 # provided we will just exit out and tell OpenSSL that there
538 # is nothing to do.
539 if not ocsp_data:
540 return 3 # SSL_TLSEXT_ERR_NOACK
541
David Benjamin7ac5f272018-05-21 21:24:04 -0400542 # OpenSSL takes ownership of this data and expects it to have
543 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000544 ocsp_data_length = len(ocsp_data)
545 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
546 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
547
548 _lib.SSL_set_tlsext_status_ocsp_resp(
549 ssl, data_ptr, ocsp_data_length
550 )
551
552 return 0
553 except Exception as e:
554 self._problems.append(e)
555 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
556
557 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
558
559
560class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
561 """
562 Wrap a callback such that it can be used as an OCSP callback for the client
563 side.
564
565 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
566 ways. For servers, that callback is expected to retrieve some OCSP data and
567 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
568 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
569 is expected to check the OCSP data, and returns a negative value on error,
570 0 if the response is not acceptable, or positive if it is. These are
571 mutually exclusive return code behaviours, and they mean that we need two
572 helpers so that we always return an appropriate error code if the user's
573 code throws an exception.
574
575 Given that we have to have two helpers anyway, these helpers are a bit more
576 helpery than most: specifically, they hide a few more of the OpenSSL
577 functions so that the user has an easier time writing these callbacks.
578
579 This helper implements the client side.
580 """
581
582 def __init__(self, callback):
583 _CallbackExceptionHelper.__init__(self)
584
585 @wraps(callback)
586 def wrapper(ssl, cdata):
587 try:
588 conn = Connection._reverse_mapping[ssl]
589
590 # Extract the data if any was provided.
591 if cdata != _ffi.NULL:
592 data = _ffi.from_handle(cdata)
593 else:
594 data = None
595
596 # Get the OCSP data.
597 ocsp_ptr = _ffi.new("unsigned char **")
598 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
599 if ocsp_len < 0:
600 # No OCSP data.
601 ocsp_data = b''
602 else:
603 # Copy the OCSP data, then pass it to the callback.
604 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
605
606 valid = callback(conn, ocsp_data, data)
607
608 # Return 1 on success or 0 on error.
609 return int(bool(valid))
610
611 except Exception as e:
612 self._problems.append(e)
613 # Return negative value if an exception is hit.
614 return -1
615
616 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
617
618
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619def _asFileDescriptor(obj):
620 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800621 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800622 meth = getattr(obj, "fileno", None)
623 if meth is not None:
624 obj = meth()
625
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800626 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800627 fd = obj
628
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800629 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800630 raise TypeError("argument must be an int, or have a fileno() method.")
631 elif fd < 0:
632 raise ValueError(
633 "file descriptor cannot be a negative integer (%i)" % (fd,))
634
635 return fd
636
637
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800638def SSLeay_version(type):
639 """
640 Return a string describing the version of OpenSSL in use.
641
Alex Chand072cae2018-02-15 09:57:59 +0000642 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800643 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500644 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645
646
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500647def _warn_npn():
648 warnings.warn("NPN is deprecated. Protocols should switch to using ALPN.",
649 DeprecationWarning, stacklevel=3)
650
651
Cory Benfieldef404df2016-03-29 15:32:48 +0100652def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400653 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100654 Builds a decorator that ensures that functions that rely on OpenSSL
655 functions that are not present in this build raise NotImplementedError,
656 rather than AttributeError coming out of cryptography.
657
658 :param flag: A cryptography flag that guards the functions, e.g.
659 ``Cryptography_HAS_NEXTPROTONEG``.
660 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400661 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100662 def _requires_decorator(func):
663 if not flag:
664 @wraps(func)
665 def explode(*args, **kwargs):
666 raise NotImplementedError(error)
667 return explode
668 else:
669 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400670
Cory Benfieldef404df2016-03-29 15:32:48 +0100671 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400672
673
Cory Benfieldef404df2016-03-29 15:32:48 +0100674_requires_npn = _make_requires(
675 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
676)
Cory Benfield7907e332015-04-13 17:18:25 -0400677
678
Cory Benfieldef404df2016-03-29 15:32:48 +0100679_requires_alpn = _make_requires(
680 _lib.Cryptography_HAS_ALPN, "ALPN not available"
681)
Cory Benfielde6f35882016-03-29 11:21:04 +0100682
Cory Benfielde6f35882016-03-29 11:21:04 +0100683
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800684class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000685 """
686 A class representing an SSL session. A session defines certain connection
687 parameters which may be re-used to speed up the setup of subsequent
688 connections.
689
690 .. versionadded:: 0.14
691 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800692 pass
693
694
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695class Context(object):
696 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100697 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400698 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000699
700 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
701 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800702 """
703 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800704 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500705 SSLv3_METHOD: "SSLv3_method",
706 SSLv23_METHOD: "SSLv23_method",
707 TLSv1_METHOD: "TLSv1_method",
708 TLSv1_1_METHOD: "TLSv1_1_method",
709 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400710 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500711 _methods = dict(
712 (identifier, getattr(_lib, name))
713 for (identifier, name) in _methods.items()
714 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800715
716 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500717 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718 raise TypeError("method must be an integer")
719
720 try:
721 method_func = self._methods[method]
722 except KeyError:
723 raise ValueError("No such protocol")
724
725 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700726 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800727
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500728 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700729 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500730 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800731
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600732 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
733 # will be auto-selected. This function was added in 1.0.2 and made a
734 # noop in 1.1.0+ (where it is set automatically).
735 try:
736 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
737 _openssl_assert(res == 1)
738 except AttributeError:
739 pass
740
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800742 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800743 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800744 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800745 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800746 self._verify_callback = None
747 self._info_callback = None
748 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800749 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000750 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100751 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000752 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100753 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400754 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100755 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000756 self._ocsp_helper = None
757 self._ocsp_callback = None
758 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800759
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500760 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800762 def load_verify_locations(self, cafile, capath=None):
763 """
764 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000765 chain. Note that the certificates have to be in PEM format.
766
767 If capath is passed, it must be a directory prepared using the
768 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
769 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800770
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400771 :param cafile: In which file we can find the certificates (``bytes`` or
772 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800773 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400774 (``bytes`` or ``unicode``).
775
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776 :return: None
777 """
778 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500779 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400780 else:
781 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
783 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500784 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400785 else:
786 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787
Alex Gaynor62da94d2015-09-05 14:37:34 -0400788 load_result = _lib.SSL_CTX_load_verify_locations(
789 self._context, cafile, capath
790 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500792 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 def _wrap_callback(self, callback):
795 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800796 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800797 return callback(size, verify, self._passphrase_userdata)
798 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800799 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801 def set_passwd_cb(self, callback, userdata=None):
802 """
Alex Chand072cae2018-02-15 09:57:59 +0000803 Set the passphrase callback. This function will be called
804 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800805
Alex Chand072cae2018-02-15 09:57:59 +0000806 :param callback: The Python callback to use. This must accept three
807 positional arguments. First, an integer giving the maximum length
808 of the passphrase it may return. If the returned passphrase is
809 longer than this, it will be truncated. Second, a boolean value
810 which will be true if the user should be prompted for the
811 passphrase twice and the callback should verify that the two values
812 supplied are equal. Third, the value given as the *userdata*
813 parameter to :meth:`set_passwd_cb`. The *callback* must return
814 a byte string. If an error occurs, *callback* should return a false
815 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800816 :param userdata: (optional) A Python object which will be given as
817 argument to the callback
818 :return: None
819 """
820 if not callable(callback):
821 raise TypeError("callback must be callable")
822
823 self._passphrase_helper = self._wrap_callback(callback)
824 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500825 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800826 self._context, self._passphrase_callback)
827 self._passphrase_userdata = userdata
828
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829 def set_default_verify_paths(self):
830 """
Alex Chand072cae2018-02-15 09:57:59 +0000831 Specify that the platform provided CA certificates are to be used for
832 verification purposes. This method has some caveats related to the
833 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
834
835 * macOS will only load certificates using this method if the user has
836 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
837 in the default location.
838 * Windows will not work.
839 * manylinux1 cryptography wheels will work on most common Linux
840 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
841 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800842
843 :return: None
844 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500845 # SSL_CTX_set_default_verify_paths will attempt to load certs from
846 # both a cafile and capath that are set at compile time. However,
847 # it will first check environment variables and, if present, load
848 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500849 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400850 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500851 # After attempting to set default_verify_paths we need to know whether
852 # to go down the fallback path.
853 # First we'll check to see if any env vars have been set. If so,
854 # we won't try to do anything else because the user has set the path
855 # themselves.
856 dir_env_var = _ffi.string(
857 _lib.X509_get_default_cert_dir_env()
858 ).decode("ascii")
859 file_env_var = _ffi.string(
860 _lib.X509_get_default_cert_file_env()
861 ).decode("ascii")
862 if not self._check_env_vars_set(dir_env_var, file_env_var):
863 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
864 default_file = _ffi.string(_lib.X509_get_default_cert_file())
865 # Now we check to see if the default_dir and default_file are set
866 # to the exact values we use in our manylinux1 builds. If they are
867 # then we know to load the fallbacks
868 if (
869 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
870 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
871 ):
872 # This is manylinux1, let's load our fallback paths
873 self._fallback_default_verify_paths(
874 _CERTIFICATE_FILE_LOCATIONS,
875 _CERTIFICATE_PATH_LOCATIONS
876 )
877
878 def _check_env_vars_set(self, dir_env_var, file_env_var):
879 """
880 Check to see if the default cert dir/file environment vars are present.
881
882 :return: bool
883 """
884 return (
885 os.environ.get(file_env_var) is not None or
886 os.environ.get(dir_env_var) is not None
887 )
888
889 def _fallback_default_verify_paths(self, file_path, dir_path):
890 """
891 Default verify paths are based on the compiled version of OpenSSL.
892 However, when pyca/cryptography is compiled as a manylinux1 wheel
893 that compiled location can potentially be wrong. So, like Go, we
894 will try a predefined set of paths and attempt to load roots
895 from there.
896
897 :return: None
898 """
899 for cafile in file_path:
900 if os.path.isfile(cafile):
901 self.load_verify_locations(cafile)
902 break
903
904 for capath in dir_path:
905 if os.path.isdir(capath):
906 self.load_verify_locations(None, capath)
907 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800908
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 def use_certificate_chain_file(self, certfile):
910 """
Alex Chand072cae2018-02-15 09:57:59 +0000911 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400913 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000914 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400915
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800916 :return: None
917 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400918 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800919
Alex Gaynor62da94d2015-09-05 14:37:34 -0400920 result = _lib.SSL_CTX_use_certificate_chain_file(
921 self._context, certfile
922 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800923 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500924 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800925
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800926 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927 """
928 Load a certificate from a file
929
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400930 :param certfile: The name of the certificate file (``bytes`` or
931 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000932 :param filetype: (optional) The encoding of the file, which is either
933 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
934 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 :return: None
937 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400938 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500939 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800940 raise TypeError("filetype must be an integer")
941
Alex Gaynor62da94d2015-09-05 14:37:34 -0400942 use_result = _lib.SSL_CTX_use_certificate_file(
943 self._context, certfile, filetype
944 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800945 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500946 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800947
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800948 def use_certificate(self, cert):
949 """
950 Load a certificate from a X509 object
951
952 :param cert: The X509 object
953 :return: None
954 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800955 if not isinstance(cert, X509):
956 raise TypeError("cert must be an X509 instance")
957
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500958 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800959 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500960 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800961
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 def add_extra_chain_cert(self, certobj):
963 """
964 Add certificate to chain
965
966 :param certobj: The X509 certificate object to add to the chain
967 :return: None
968 """
969 if not isinstance(certobj, X509):
970 raise TypeError("certobj must be an X509 instance")
971
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500972 copy = _lib.X509_dup(certobj._x509)
973 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500975 # TODO: This is untested.
976 _lib.X509_free(copy)
977 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800979 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500980 if self._passphrase_helper is not None:
981 self._passphrase_helper.raise_if_problem(Error)
982
983 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800984
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400985 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986 """
987 Load a private key from a file
988
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400989 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000990 :param filetype: (optional) The encoding of the file, which is either
991 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
992 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400993
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 :return: None
995 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400996 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400998 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001000 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001 raise TypeError("filetype must be an integer")
1002
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001004 self._context, keyfile, filetype)
1005 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001006 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001007
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001008 def use_privatekey(self, pkey):
1009 """
1010 Load a private key from a PKey object
1011
1012 :param pkey: The PKey object
1013 :return: None
1014 """
1015 if not isinstance(pkey, PKey):
1016 raise TypeError("pkey must be a PKey instance")
1017
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001018 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001019 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001020 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001022 def check_privatekey(self):
1023 """
Alex Chand072cae2018-02-15 09:57:59 +00001024 Check if the private key (loaded with :meth:`use_privatekey`) matches
1025 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026
Alex Chand072cae2018-02-15 09:57:59 +00001027 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001029 if not _lib.SSL_CTX_check_private_key(self._context):
1030 _raise_current_error()
1031
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032 def load_client_ca(self, cafile):
1033 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001034 Load the trusted certificates that will be sent to the client. Does
1035 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001036 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001037
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001038 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039 :return: None
1040 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001041 ca_list = _lib.SSL_load_client_CA_file(
1042 _text_to_bytes_and_warn("cafile", cafile)
1043 )
1044 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001045 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046
1047 def set_session_id(self, buf):
1048 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001049 Set the session id to *buf* within which a session can be reused for
1050 this Context object. This is needed when doing session resumption,
1051 because there is no way for a stored session to know which Context
1052 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001053
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001054 :param bytes buf: The session id.
1055
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056 :returns: None
1057 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001058 buf = _text_to_bytes_and_warn("buf", buf)
1059 _openssl_assert(
1060 _lib.SSL_CTX_set_session_id_context(
1061 self._context,
1062 buf,
1063 len(buf),
1064 ) == 1
1065 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066
1067 def set_session_cache_mode(self, mode):
1068 """
Alex Chand072cae2018-02-15 09:57:59 +00001069 Set the behavior of the session cache used by all connections using
1070 this Context. The previously set mode is returned. See
1071 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072
1073 :param mode: One or more of the SESS_CACHE_* flags (combine using
1074 bitwise or)
1075 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001076
1077 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001078 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001079 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080 raise TypeError("mode must be an integer")
1081
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001084 def get_session_cache_mode(self):
1085 """
Alex Chand072cae2018-02-15 09:57:59 +00001086 Get the current session cache mode.
1087
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001088 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001089
1090 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001092 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001094 def set_verify(self, mode, callback):
1095 """
Alex Chand072cae2018-02-15 09:57:59 +00001096 et the verification flags for this Context object to *mode* and specify
1097 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098
Alex Chand072cae2018-02-15 09:57:59 +00001099 :param mode: The verify mode, this should be one of
1100 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1101 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1102 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1103 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1104 :param callback: The Python callback to use. This should take five
1105 arguments: A Connection object, an X509 object, and three integer
1106 variables, which are in turn potential error number, error depth
1107 and return code. *callback* should return True if verification
1108 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 :return: None
1110
1111 See SSL_CTX_set_verify(3SSL) for further details.
1112 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001113 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001114 raise TypeError("mode must be an integer")
1115
1116 if not callable(callback):
1117 raise TypeError("callback must be callable")
1118
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001119 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001120 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001121 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001123 def set_verify_depth(self, depth):
1124 """
Alex Chand072cae2018-02-15 09:57:59 +00001125 Set the maximum depth for the certificate chain verification that shall
1126 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127
1128 :param depth: An integer specifying the verify depth
1129 :return: None
1130 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001131 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001132 raise TypeError("depth must be an integer")
1133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001134 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001135
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001136 def get_verify_mode(self):
1137 """
Alex Chand072cae2018-02-15 09:57:59 +00001138 Retrieve the Context object's verify mode, as set by
1139 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001140
1141 :return: The verify mode
1142 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001143 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001145 def get_verify_depth(self):
1146 """
Alex Chand072cae2018-02-15 09:57:59 +00001147 Retrieve the Context object's verify depth, as set by
1148 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001149
1150 :return: The verify depth
1151 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001153
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001154 def load_tmp_dh(self, dhfile):
1155 """
1156 Load parameters for Ephemeral Diffie-Hellman
1157
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001158 :param dhfile: The file to load EDH parameters from (``bytes`` or
1159 ``unicode``).
1160
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161 :return: None
1162 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001163 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001164
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001165 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001167 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001169
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1171 dh = _ffi.gc(dh, _lib.DH_free)
1172 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001173
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001174 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001175 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001176 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001177
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001178 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001179 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1180 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001181
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001182 :return: None
1183 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001184 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001185
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001186 def set_cipher_list(self, cipher_list):
1187 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001188 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001189
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001190 See the OpenSSL manual for more information (e.g.
1191 :manpage:`ciphers(1)`).
1192
1193 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001194 :return: None
1195 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001196 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001197
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001198 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001199 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001200
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001201 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001202 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001203 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001204 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1205 # ciphers even if you pass an invalid cipher. Applications (like
1206 # Twisted) have tests that depend on an error being raised if an
1207 # invalid cipher string is passed, but without the following check
1208 # for the TLS 1.3 specific cipher suites it would never error.
1209 tmpconn = Connection(self, None)
Mark Williamsdf2480d2019-02-14 19:30:07 -08001210 if (
1211 tmpconn.get_cipher_list() == [
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001212 'TLS_AES_256_GCM_SHA384',
1213 'TLS_CHACHA20_POLY1305_SHA256',
1214 'TLS_AES_128_GCM_SHA256'
1215 ]
Mark Williamsdf2480d2019-02-14 19:30:07 -08001216 ):
1217 raise Error(
1218 [
1219 (
1220 'SSL routines',
1221 'SSL_CTX_set_cipher_list',
1222 'no cipher match',
1223 ),
1224 ],
1225 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001226
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001227 def set_client_ca_list(self, certificate_authorities):
1228 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001229 Set the list of preferred client certificate signers for this server
1230 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001231
Alex Gaynor62da94d2015-09-05 14:37:34 -04001232 This list of certificate authorities will be sent to the client when
1233 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001234
1235 :param certificate_authorities: a sequence of X509Names.
1236 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001237
1238 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001239 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001241 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001242
1243 try:
1244 for ca_name in certificate_authorities:
1245 if not isinstance(ca_name, X509Name):
1246 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001247 "client CAs must be X509Name objects, not %s "
1248 "objects" % (
1249 type(ca_name).__name__,
1250 )
1251 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001252 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001253 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001254 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001255 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001256 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001257 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001258 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001259 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001260 raise
1261
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001262 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001263
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264 def add_client_ca(self, certificate_authority):
1265 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001266 Add the CA certificate to the list of preferred signers for this
1267 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001268
1269 The list of certificate authorities will be sent to the client when the
1270 server requests a client certificate.
1271
1272 :param certificate_authority: certificate authority's X509 certificate.
1273 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001274
1275 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001276 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001277 if not isinstance(certificate_authority, X509):
1278 raise TypeError("certificate_authority must be an X509 instance")
1279
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001280 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001282 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001283
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001284 def set_timeout(self, timeout):
1285 """
Alex Chand072cae2018-02-15 09:57:59 +00001286 Set the timeout for newly created sessions for this Context object to
1287 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1288 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001289
Alex Chand072cae2018-02-15 09:57:59 +00001290 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001291 :return: The previous session timeout
1292 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001293 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001294 raise TypeError("timeout must be an integer")
1295
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001296 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001297
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001298 def get_timeout(self):
1299 """
Alex Chand072cae2018-02-15 09:57:59 +00001300 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1301 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001302
1303 :return: The session timeout
1304 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001305 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001306
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001307 def set_info_callback(self, callback):
1308 """
Alex Chand072cae2018-02-15 09:57:59 +00001309 Set the information callback to *callback*. This function will be
1310 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001311
Alex Chand072cae2018-02-15 09:57:59 +00001312 :param callback: The Python callback to use. This should take three
1313 arguments: a Connection object and two integers. The first integer
1314 specifies where in the SSL handshake the function was called, and
1315 the other the return code from a (possibly failed) internal
1316 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317 :return: None
1318 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001319 @wraps(callback)
1320 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001321 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001322 self._info_callback = _ffi.callback(
1323 "void (*)(const SSL *, int, int)", wrapper)
1324 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001325
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001326 def get_app_data(self):
1327 """
Alex Chand072cae2018-02-15 09:57:59 +00001328 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001329
1330 :return: The application data
1331 """
1332 return self._app_data
1333
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001334 def set_app_data(self, data):
1335 """
1336 Set the application data (will be returned from get_app_data())
1337
1338 :param data: Any Python object
1339 :return: None
1340 """
1341 self._app_data = data
1342
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001343 def get_cert_store(self):
1344 """
Alex Chand072cae2018-02-15 09:57:59 +00001345 Get the certificate store for the context. This can be used to add
1346 "trusted" certificates without using the
1347 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001348
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001349 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001350 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 store = _lib.SSL_CTX_get_cert_store(self._context)
1352 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001353 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001354 return None
1355
1356 pystore = X509Store.__new__(X509Store)
1357 pystore._store = store
1358 return pystore
1359
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001360 def set_options(self, options):
1361 """
1362 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001363 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001364
1365 :param options: The options to add.
1366 :return: The new option bitmask.
1367 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001368 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001369 raise TypeError("options must be an integer")
1370
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001371 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001372
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001373 def set_mode(self, mode):
1374 """
Alex Chand072cae2018-02-15 09:57:59 +00001375 Add modes via bitmask. Modes set before are not cleared! This method
1376 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001377
1378 :param mode: The mode to add.
1379 :return: The new mode bitmask.
1380 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001381 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001382 raise TypeError("mode must be an integer")
1383
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001384 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001385
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001386 def set_tlsext_servername_callback(self, callback):
1387 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001388 Specify a callback function to be called when clients specify a server
1389 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001390
1391 :param callback: The callback function. It will be invoked with one
1392 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001393
1394 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001395 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001396 @wraps(callback)
1397 def wrapper(ssl, alert, arg):
1398 callback(Connection._reverse_mapping[ssl])
1399 return 0
1400
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 self._tlsext_servername_callback = _ffi.callback(
David Benjamince5c3842018-05-21 21:14:46 -04001402 "int (*)(SSL *, int *, void *)", wrapper)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001403 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001404 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001405
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001406 def set_tlsext_use_srtp(self, profiles):
1407 """
1408 Enable support for negotiating SRTP keying material.
1409
1410 :param bytes profiles: A colon delimited list of protection profile
1411 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1412 :return: None
1413 """
1414 if not isinstance(profiles, bytes):
1415 raise TypeError("profiles must be a byte string.")
1416
1417 _openssl_assert(
1418 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1419 )
1420
Cory Benfield10b277f2015-04-13 17:12:42 -04001421 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001422 def set_npn_advertise_callback(self, callback):
1423 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001424 Specify a callback function that will be called when offering `Next
1425 Protocol Negotiation
1426 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001427
1428 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001429 argument, the :class:`Connection` instance. It should return a
1430 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001431 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001432
1433 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001434 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001435 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001436 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1437 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001438 _lib.SSL_CTX_set_next_protos_advertised_cb(
1439 self._context, self._npn_advertise_callback, _ffi.NULL)
1440
Cory Benfield10b277f2015-04-13 17:12:42 -04001441 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001442 def set_npn_select_callback(self, callback):
1443 """
1444 Specify a callback function that will be called when a server offers
1445 Next Protocol Negotiation options.
1446
1447 :param callback: The callback function. It will be invoked with two
1448 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001449 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1450 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001451
1452 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001453 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001454 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001455 self._npn_select_helper = _NpnSelectHelper(callback)
1456 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001457 _lib.SSL_CTX_set_next_proto_select_cb(
1458 self._context, self._npn_select_callback, _ffi.NULL)
1459
Cory Benfield7907e332015-04-13 17:18:25 -04001460 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001461 def set_alpn_protos(self, protos):
1462 """
Alex Chand072cae2018-02-15 09:57:59 +00001463 Specify the protocols that the client is prepared to speak after the
1464 TLS connection has been negotiated using Application Layer Protocol
1465 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001466
1467 :param protos: A list of the protocols to be offered to the server.
1468 This list should be a Python list of bytestrings representing the
1469 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1470 """
1471 # Take the list of protocols and join them together, prefixing them
1472 # with their lengths.
1473 protostr = b''.join(
1474 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1475 )
1476
1477 # Build a C string from the list. We don't need to save this off
1478 # because OpenSSL immediately copies the data out.
1479 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001480 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001481
Cory Benfield7907e332015-04-13 17:18:25 -04001482 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001483 def set_alpn_select_callback(self, callback):
1484 """
Alex Chand072cae2018-02-15 09:57:59 +00001485 Specify a callback function that will be called on the server when a
1486 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001487
1488 :param callback: The callback function. It will be invoked with two
1489 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001490 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1491 one of those bytestrings to indicate the chosen protocol, the
1492 empty bytestring to terminate the TLS connection, or the
1493 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1494 protocol was selected, but that the connection should not be
1495 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001496 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001497 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001498 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001499 _lib.SSL_CTX_set_alpn_select_cb(
1500 self._context, self._alpn_select_callback, _ffi.NULL)
1501
Cory Benfield496652a2017-01-24 11:42:56 +00001502 def _set_ocsp_callback(self, helper, data):
1503 """
1504 This internal helper does the common work for
1505 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1506 almost all of it.
1507 """
1508 self._ocsp_helper = helper
1509 self._ocsp_callback = helper.callback
1510 if data is None:
1511 self._ocsp_data = _ffi.NULL
1512 else:
1513 self._ocsp_data = _ffi.new_handle(data)
1514
1515 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1516 self._context, self._ocsp_callback
1517 )
1518 _openssl_assert(rc == 1)
1519 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1520 _openssl_assert(rc == 1)
1521
1522 def set_ocsp_server_callback(self, callback, data=None):
1523 """
1524 Set a callback to provide OCSP data to be stapled to the TLS handshake
1525 on the server side.
1526
1527 :param callback: The callback function. It will be invoked with two
1528 arguments: the Connection, and the optional arbitrary data you have
1529 provided. The callback must return a bytestring that contains the
1530 OCSP data to staple to the handshake. If no OCSP data is available
1531 for this connection, return the empty bytestring.
1532 :param data: Some opaque data that will be passed into the callback
1533 function when called. This can be used to avoid needing to do
1534 complex data lookups or to keep track of what context is being
1535 used. This parameter is optional.
1536 """
1537 helper = _OCSPServerCallbackHelper(callback)
1538 self._set_ocsp_callback(helper, data)
1539
1540 def set_ocsp_client_callback(self, callback, data=None):
1541 """
1542 Set a callback to validate OCSP data stapled to the TLS handshake on
1543 the client side.
1544
1545 :param callback: The callback function. It will be invoked with three
1546 arguments: the Connection, a bytestring containing the stapled OCSP
1547 assertion, and the optional arbitrary data you have provided. The
1548 callback must return a boolean that indicates the result of
1549 validating the OCSP data: ``True`` if the OCSP data is valid and
1550 the certificate can be trusted, or ``False`` if either the OCSP
1551 data is invalid or the certificate has been revoked.
1552 :param data: Some opaque data that will be passed into the callback
1553 function when called. This can be used to avoid needing to do
1554 complex data lookups or to keep track of what context is being
1555 used. This parameter is optional.
1556 """
1557 helper = _OCSPClientCallbackHelper(callback)
1558 self._set_ocsp_callback(helper, data)
1559
Alex Chanc6077062016-11-18 13:53:39 +00001560
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001561class Connection(object):
1562 """
1563 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001564 _reverse_mapping = WeakValueDictionary()
1565
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001566 def __init__(self, context, socket=None):
1567 """
1568 Create a new Connection object, using the given OpenSSL.SSL.Context
1569 instance and socket.
1570
1571 :param context: An SSL Context to use for this connection
1572 :param socket: The socket to use for transport layer
1573 """
1574 if not isinstance(context, Context):
1575 raise TypeError("context must be a Context instance")
1576
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001577 ssl = _lib.SSL_new(context._context)
1578 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001579 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1580 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1581 # even though there is still data on the underlying transport.
1582 # See https://github.com/openssl/openssl/issues/6234 for more details.
1583 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001585 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001587 # References to strings used for Next Protocol Negotiation. OpenSSL's
1588 # header files suggest that these might get copied at some point, but
1589 # doesn't specify when, so we store them here to make sure they don't
1590 # get freed before OpenSSL uses them.
1591 self._npn_advertise_callback_args = None
1592 self._npn_select_callback_args = None
1593
Cory Benfield12eae892014-06-07 15:42:56 +01001594 # References to strings used for Application Layer Protocol
1595 # Negotiation. These strings get copied at some point but it's well
1596 # after the callback returns, so we have to hang them somewhere to
1597 # avoid them getting freed.
1598 self._alpn_select_callback_args = None
1599
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001600 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001601
1602 if socket is None:
1603 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001604 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001605 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001606 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001607
Alex Gaynora829e902016-06-04 18:16:01 -07001608 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1609 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001611 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 self._into_ssl = None
1614 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001615 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001616 set_result = _lib.SSL_set_fd(
1617 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001618 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001619
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620 def __getattr__(self, name):
1621 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001622 Look up attributes on the wrapped socket object if they are not found
1623 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001624 """
kjav0b66fa12015-09-02 11:51:26 +01001625 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001626 raise AttributeError("'%s' object has no attribute '%s'" % (
1627 self.__class__.__name__, name
1628 ))
kjav0b66fa12015-09-02 11:51:26 +01001629 else:
1630 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001633 if self._context._verify_helper is not None:
1634 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001635 if self._context._npn_advertise_helper is not None:
1636 self._context._npn_advertise_helper.raise_if_problem()
1637 if self._context._npn_select_helper is not None:
1638 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001639 if self._context._alpn_select_helper is not None:
1640 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001641 if self._context._ocsp_helper is not None:
1642 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001643
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001644 error = _lib.SSL_get_error(ssl, result)
1645 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001646 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001647 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001648 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001649 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001650 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001652 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001653 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001654 elif error == _lib.SSL_ERROR_SYSCALL:
1655 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001657 if platform == "win32":
1658 errno = _ffi.getwinerror()[0]
1659 else:
1660 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001661
1662 if errno != 0:
1663 raise SysCallError(errno, errorcode.get(errno))
1664 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001665 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001666 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001667 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001668 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001669 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001671 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001672
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 def get_context(self):
1674 """
Alex Chand072cae2018-02-15 09:57:59 +00001675 Retrieve the :class:`Context` object associated with this
1676 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001680 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001681 """
Alex Chand072cae2018-02-15 09:57:59 +00001682 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001683
Alex Chand072cae2018-02-15 09:57:59 +00001684 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001685 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687 if not isinstance(context, Context):
1688 raise TypeError("context must be a Context instance")
1689
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001690 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001691 self._context = context
1692
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001693 def get_servername(self):
1694 """
1695 Retrieve the servername extension value if provided in the client hello
1696 message, or None if there wasn't one.
1697
Alex Chand072cae2018-02-15 09:57:59 +00001698 :return: A byte string giving the server name or :data:`None`.
1699
1700 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001702 name = _lib.SSL_get_servername(
1703 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1704 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001705 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001706 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001708 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001710 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 """
1712 Set the value of the servername extension to send in the client hello.
1713
1714 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001715
1716 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001717 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001718 if not isinstance(name, bytes):
1719 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001720 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001721 raise TypeError("name must not contain NUL byte")
1722
1723 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001724 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001725
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 def pending(self):
1727 """
Alex Chand072cae2018-02-15 09:57:59 +00001728 Get the number of bytes that can be safely read from the SSL buffer
1729 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001730
1731 :return: The number of bytes available in the receive buffer.
1732 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001733 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001734
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001735 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001736 """
1737 Send data on the connection. NOTE: If you get one of the WantRead,
1738 WantWrite or WantX509Lookup exceptions on this, you have to call the
1739 method again with the SAME buffer.
1740
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001741 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001742 :param flags: (optional) Included for compatibility with the socket
1743 API, the value is ignored
1744 :return: The number of bytes written
1745 """
Abraham Martine82326c2015-02-04 10:18:10 +00001746 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001747 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001748
Daniel Holth079c9632019-11-17 22:45:52 -05001749 with _from_buffer(buf) as data:
1750 # check len(buf) instead of len(data) for testability
1751 if len(buf) > 2147483647:
1752 raise ValueError(
1753 "Cannot send more than 2**31-1 bytes at once."
1754 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755
Daniel Holth079c9632019-11-17 22:45:52 -05001756 result = _lib.SSL_write(self._ssl, data, len(data))
1757 self._raise_ssl_error(self._ssl, result)
1758
1759 return result
1760
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001761 write = send
1762
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001763 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001764 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001765 Send "all" data on the connection. This calls send() repeatedly until
1766 all data is sent. If an error occurs, it's impossible to tell how much
1767 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001769 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001770 :param flags: (optional) Included for compatibility with the socket
1771 API, the value is ignored
1772 :return: The number of bytes written
1773 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001774 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001775
Daniel Holth079c9632019-11-17 22:45:52 -05001776 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001777
Daniel Holth079c9632019-11-17 22:45:52 -05001778 left_to_send = len(buf)
1779 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780
Daniel Holth079c9632019-11-17 22:45:52 -05001781 while left_to_send:
1782 # SSL_write's num arg is an int,
1783 # so we cannot send more than 2**31-1 bytes at once.
1784 result = _lib.SSL_write(
1785 self._ssl,
1786 data + total_sent,
1787 min(left_to_send, 2147483647)
1788 )
1789 self._raise_ssl_error(self._ssl, result)
1790 total_sent += result
1791 left_to_send -= result
1792
1793 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001794
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001795 def recv(self, bufsiz, flags=None):
1796 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001797 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001798
1799 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001800 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1801 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001802 :return: The string read from the Connection
1803 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001804 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001805 if flags is not None and flags & socket.MSG_PEEK:
1806 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1807 else:
1808 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001809 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001810 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001811 read = recv
1812
Cory Benfield62d10332014-06-15 10:03:41 +01001813 def recv_into(self, buffer, nbytes=None, flags=None):
1814 """
Alex Chand072cae2018-02-15 09:57:59 +00001815 Receive data on the connection and copy it directly into the provided
1816 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001817
1818 :param buffer: The buffer to copy into.
1819 :param nbytes: (optional) The maximum number of bytes to read into the
1820 buffer. If not present, defaults to the size of the buffer. If
1821 larger than the size of the buffer, is reduced to the size of the
1822 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001823 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1824 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001825 :return: The number of bytes read into the buffer.
1826 """
1827 if nbytes is None:
1828 nbytes = len(buffer)
1829 else:
1830 nbytes = min(nbytes, len(buffer))
1831
1832 # We need to create a temporary buffer. This is annoying, it would be
1833 # better if we could pass memoryviews straight into the SSL_read call,
1834 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001835 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001836 if flags is not None and flags & socket.MSG_PEEK:
1837 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1838 else:
1839 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001840 self._raise_ssl_error(self._ssl, result)
1841
1842 # This strange line is all to avoid a memory copy. The buffer protocol
1843 # should allow us to assign a CFFI buffer to the LHS of this line, but
1844 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001845 # wrap it in a memoryview.
1846 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001847
1848 return result
1849
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001850 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001851 if _lib.BIO_should_retry(bio):
1852 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001853 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001855 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001856 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001857 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001858 # TODO: This is untested. I think io_special means the socket
1859 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001860 raise ValueError("BIO_should_io_special")
1861 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001862 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001863 raise ValueError("unknown bio failure")
1864 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001865 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001866 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001867
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001868 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001869 """
Alex Chand072cae2018-02-15 09:57:59 +00001870 If the Connection was created with a memory BIO, this method can be
1871 used to read bytes from the write end of that memory BIO. Many
1872 Connection methods will add bytes which must be read in this manner or
1873 the buffer will eventually fill up and the Connection will be able to
1874 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875
1876 :param bufsiz: The maximum number of bytes to read
1877 :return: The string read.
1878 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001879 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001880 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001882 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001883 raise TypeError("bufsiz must be an integer")
1884
Cory Benfielde62840e2016-11-28 12:17:08 +00001885 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001887 if result <= 0:
1888 self._handle_bio_errors(self._from_ssl, result)
1889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001890 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001892 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001893 """
Alex Chand072cae2018-02-15 09:57:59 +00001894 If the Connection was created with a memory BIO, this method can be
1895 used to add bytes to the read end of that memory BIO. The Connection
1896 can then read the bytes (for example, in response to a call to
1897 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898
1899 :param buf: The string to put into the memory BIO.
1900 :return: The number of bytes written
1901 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001902 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001903
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001904 if self._into_ssl is None:
1905 raise TypeError("Connection sock was not None")
1906
Daniel Holth079c9632019-11-17 22:45:52 -05001907 with _from_buffer(buf) as data:
1908 result = _lib.BIO_write(self._into_ssl, data, len(data))
1909 if result <= 0:
1910 self._handle_bio_errors(self._into_ssl, result)
1911 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001912
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913 def renegotiate(self):
1914 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001915 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001917 :return: True if the renegotiation can be started, False otherwise
1918 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001919 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001920 if not self.renegotiate_pending():
1921 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1922 return True
1923 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001924
1925 def do_handshake(self):
1926 """
Alex Chand072cae2018-02-15 09:57:59 +00001927 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001928 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001929 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930
1931 :return: None.
1932 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001933 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001934 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001935
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936 def renegotiate_pending(self):
1937 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001938 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939 a renegotiation is finished.
1940
1941 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001942 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001944 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001945
1946 def total_renegotiations(self):
1947 """
1948 Find out the total number of renegotiations.
1949
1950 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001951 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001954
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001955 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001956 """
Alex Chand072cae2018-02-15 09:57:59 +00001957 Call the :meth:`connect` method of the underlying socket and set up SSL
1958 on the socket, using the :class:`Context` object supplied to this
1959 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001960
1961 :param addr: A remote address
1962 :return: What the socket's connect method returns
1963 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001964 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001965 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001967 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968 """
Alex Chand072cae2018-02-15 09:57:59 +00001969 Call the :meth:`connect_ex` method of the underlying socket and set up
1970 SSL on the socket, using the Context object supplied to this Connection
1971 object at creation. Note that if the :meth:`connect_ex` method of the
1972 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
1974 :param addr: A remove address
1975 :return: What the socket's connect_ex method returns
1976 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001977 connect_ex = self._socket.connect_ex
1978 self.set_connect_state()
1979 return connect_ex(addr)
1980
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001981 def accept(self):
1982 """
Alex Chand072cae2018-02-15 09:57:59 +00001983 Call the :meth:`accept` method of the underlying socket and set up SSL
1984 on the returned socket, using the Context object supplied to this
1985 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001986
Alex Chand072cae2018-02-15 09:57:59 +00001987 :return: A *(conn, addr)* pair where *conn* is the new
1988 :class:`Connection` object created, and *address* is as returned by
1989 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991 client, addr = self._socket.accept()
1992 conn = Connection(self._context, client)
1993 conn.set_accept_state()
1994 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001995
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001996 def bio_shutdown(self):
1997 """
Alex Chand072cae2018-02-15 09:57:59 +00001998 If the Connection was created with a memory BIO, this method can be
1999 used to indicate that *end of file* has been reached on the read end of
2000 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001
2002 :return: None
2003 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002004 if self._from_ssl is None:
2005 raise TypeError("Connection sock was not None")
2006
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002007 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002008
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002009 def shutdown(self):
2010 """
Alex Chand072cae2018-02-15 09:57:59 +00002011 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002012
2013 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00002014 have sent closure alerts), False otherwise (in which case you
2015 call :meth:`recv` or :meth:`send` when the connection becomes
2016 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002017 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002018 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002020 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002022 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002023 else:
2024 return False
2025
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002026 def get_cipher_list(self):
2027 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002028 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002029
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002030 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002031 """
2032 ciphers = []
2033 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002034 result = _lib.SSL_get_cipher_list(self._ssl, i)
2035 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002037 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002038 return ciphers
2039
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002040 def get_client_ca_list(self):
2041 """
2042 Get CAs whose certificates are suggested for client authentication.
2043
Alex Chand072cae2018-02-15 09:57:59 +00002044 :return: If this is a server connection, the list of certificate
2045 authorities that will be sent or has been sent to the client, as
2046 controlled by this :class:`Connection`'s :class:`Context`.
2047
2048 If this is a client connection, the list will be empty until the
2049 connection with the server is established.
2050
2051 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002053 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2054 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002055 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002056 return []
2057
2058 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002059 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2060 name = _lib.sk_X509_NAME_value(ca_names, i)
2061 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002062 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002063
2064 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002065 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002066 result.append(pyname)
2067 return result
2068
Aykee7f33452018-05-16 19:18:16 +02002069 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002070 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002071 The makefile() method is not implemented, since there is no dup
2072 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002074 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002075 """
Alex Gaynor83284952015-09-05 10:43:30 -04002076 raise NotImplementedError(
2077 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002078
2079 def get_app_data(self):
2080 """
Alex Chand072cae2018-02-15 09:57:59 +00002081 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002082
2083 :return: The application data
2084 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002085 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002087 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002088 """
2089 Set application data
2090
Alex Chand072cae2018-02-15 09:57:59 +00002091 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002092 :return: None
2093 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002094 self._app_data = data
2095
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002096 def get_shutdown(self):
2097 """
Alex Chand072cae2018-02-15 09:57:59 +00002098 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002099
Alex Gaynor62da94d2015-09-05 14:37:34 -04002100 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2101 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002103 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002104
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002105 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106 """
Alex Chand072cae2018-02-15 09:57:59 +00002107 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002108
Alex Chand072cae2018-02-15 09:57:59 +00002109 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110 :return: None
2111 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002112 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002113 raise TypeError("state must be an integer")
2114
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002115 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002116
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002117 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002118 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002119 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002120
2121 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002122 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123 """
kjavc704a2e2015-09-07 12:12:27 +01002124 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002125
2126 def server_random(self):
2127 """
Alex Chand072cae2018-02-15 09:57:59 +00002128 Retrieve the random value used with the server 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 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2136 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002137 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002138 _lib.SSL_get_server_random(self._ssl, outp, length)
2139 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002140
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002141 def client_random(self):
2142 """
Alex Chand072cae2018-02-15 09:57:59 +00002143 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002144
2145 :return: A string representing the state
2146 """
Alex Gaynor93603062016-06-01 20:13:09 -07002147 session = _lib.SSL_get_session(self._ssl)
2148 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002149 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002150
2151 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2152 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002153 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002154 _lib.SSL_get_client_random(self._ssl, outp, length)
2155 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002156
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002157 def master_key(self):
2158 """
Alex Chand072cae2018-02-15 09:57:59 +00002159 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002160
2161 :return: A string representing the state
2162 """
Alex Gaynor93603062016-06-01 20:13:09 -07002163 session = _lib.SSL_get_session(self._ssl)
2164 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002165 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002166
2167 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2168 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002169 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002170 _lib.SSL_SESSION_get_master_key(session, outp, length)
2171 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002172
Paul Kehrerbdb76392017-12-01 04:54:32 +08002173 def export_keying_material(self, label, olen, context=None):
2174 """
2175 Obtain keying material for application use.
2176
Alex Chand072cae2018-02-15 09:57:59 +00002177 :param: label - a disambiguating label string as described in RFC 5705
2178 :param: olen - the length of the exported key material in bytes
2179 :param: context - a per-association context value
2180 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002181 """
2182 outp = _no_zero_allocator("unsigned char[]", olen)
2183 context_buf = _ffi.NULL
2184 context_len = 0
2185 use_context = 0
2186 if context is not None:
2187 context_buf = context
2188 context_len = len(context)
2189 use_context = 1
2190 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2191 label, len(label),
2192 context_buf, context_len,
2193 use_context)
2194 _openssl_assert(success == 1)
2195 return _ffi.buffer(outp, olen)[:]
2196
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002197 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002198 """
Alex Chand072cae2018-02-15 09:57:59 +00002199 Call the :meth:`shutdown` method of the underlying socket.
2200 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002201
2202 :return: What the socket's shutdown() method returns
2203 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002204 return self._socket.shutdown(*args, **kwargs)
2205
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002206 def get_certificate(self):
2207 """
2208 Retrieve the local certificate (if any)
2209
2210 :return: The local certificate
2211 """
2212 cert = _lib.SSL_get_certificate(self._ssl)
2213 if cert != _ffi.NULL:
2214 _lib.X509_up_ref(cert)
2215 return X509._from_raw_x509_ptr(cert)
2216 return None
2217
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002218 def get_peer_certificate(self):
2219 """
2220 Retrieve the other side's certificate (if any)
2221
2222 :return: The peer's certificate
2223 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002224 cert = _lib.SSL_get_peer_certificate(self._ssl)
2225 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002226 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002227 return None
2228
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002229 def get_peer_cert_chain(self):
2230 """
2231 Retrieve the other side's certificate (if any)
2232
2233 :return: A list of X509 instances giving the peer's certificate chain,
2234 or None if it does not have one.
2235 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002236 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2237 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002238 return None
2239
2240 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002241 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002242 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002243 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002244 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002245 result.append(pycert)
2246 return result
2247
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002248 def want_read(self):
2249 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002250 Checks if more data has to be read from the transport layer to complete
2251 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002252
2253 :return: True iff more data has to be read
2254 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002255 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002256
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002257 def want_write(self):
2258 """
2259 Checks if there is data to write to the transport layer to complete an
2260 operation.
2261
2262 :return: True iff there is data to write
2263 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002264 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002265
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002266 def set_accept_state(self):
2267 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002268 Set the connection to work in server mode. The handshake will be
2269 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002270
2271 :return: None
2272 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002273 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002274
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002275 def set_connect_state(self):
2276 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002277 Set the connection to work in client mode. The handshake will be
2278 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002279
2280 :return: None
2281 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002282 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002283
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002284 def get_session(self):
2285 """
2286 Returns the Session currently used.
2287
Alex Chand072cae2018-02-15 09:57:59 +00002288 :return: An instance of :class:`OpenSSL.SSL.Session` or
2289 :obj:`None` if no session exists.
2290
2291 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002292 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002293 session = _lib.SSL_get1_session(self._ssl)
2294 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002295 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002296
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002297 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002298 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002299 return pysession
2300
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002301 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002302 """
2303 Set the session to be used when the TLS/SSL connection is established.
2304
2305 :param session: A Session instance representing the session to use.
2306 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002307
2308 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002309 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002310 if not isinstance(session, Session):
2311 raise TypeError("session must be a Session instance")
2312
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002313 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002314 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002315 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002316
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002317 def _get_finished_message(self, function):
2318 """
Alex Chand072cae2018-02-15 09:57:59 +00002319 Helper to implement :meth:`get_finished` and
2320 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002321
Alex Chand072cae2018-02-15 09:57:59 +00002322 :param function: Either :data:`SSL_get_finished`: or
2323 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002324
Alex Chand072cae2018-02-15 09:57:59 +00002325 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002326 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002327 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002328 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002329 # The OpenSSL documentation says nothing about what might happen if the
2330 # count argument given is zero. Specifically, it doesn't say whether
2331 # the output buffer may be NULL in that case or not. Inspection of the
2332 # implementation reveals that it calls memcpy() unconditionally.
2333 # Section 7.1.4, paragraph 1 of the C standard suggests that
2334 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2335 # alone desirable) behavior (though it probably does on just about
2336 # every implementation...)
2337 #
2338 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2339 # one might expect) for the initial call so as to be safe against this
2340 # potentially undefined behavior.
2341 empty = _ffi.new("char[]", 0)
2342 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002343 if size == 0:
2344 # No Finished message so far.
2345 return None
2346
Cory Benfielde62840e2016-11-28 12:17:08 +00002347 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002348 function(self._ssl, buf, size)
2349 return _ffi.buffer(buf, size)[:]
2350
Fedor Brunner5747b932014-03-05 14:22:34 +01002351 def get_finished(self):
2352 """
Alex Chand072cae2018-02-15 09:57:59 +00002353 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002354
Alex Chand072cae2018-02-15 09:57:59 +00002355 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002356 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002357 :rtype: :class:`bytes` or :class:`NoneType`
2358
2359 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002360 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002361 return self._get_finished_message(_lib.SSL_get_finished)
2362
Fedor Brunner5747b932014-03-05 14:22:34 +01002363 def get_peer_finished(self):
2364 """
Alex Chand072cae2018-02-15 09:57:59 +00002365 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002366
Alex Chand072cae2018-02-15 09:57:59 +00002367 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002368 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002369 :rtype: :class:`bytes` or :class:`NoneType`
2370
2371 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002372 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002373 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002374
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002375 def get_cipher_name(self):
2376 """
2377 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002378
Alex Chand072cae2018-02-15 09:57:59 +00002379 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002380 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002381 :rtype: :class:`unicode` or :class:`NoneType`
2382
2383 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002384 """
2385 cipher = _lib.SSL_get_current_cipher(self._ssl)
2386 if cipher == _ffi.NULL:
2387 return None
2388 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002389 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2390 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002391
2392 def get_cipher_bits(self):
2393 """
2394 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002395
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002396 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002397 or :obj:`None` if no connection has been established.
2398 :rtype: :class:`int` or :class:`NoneType`
2399
2400 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002401 """
2402 cipher = _lib.SSL_get_current_cipher(self._ssl)
2403 if cipher == _ffi.NULL:
2404 return None
2405 else:
2406 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2407
2408 def get_cipher_version(self):
2409 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002410 Obtain the protocol version of the currently used cipher.
2411
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002412 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002413 or :obj:`None` if no connection has been established.
2414 :rtype: :class:`unicode` or :class:`NoneType`
2415
2416 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002417 """
2418 cipher = _lib.SSL_get_current_cipher(self._ssl)
2419 if cipher == _ffi.NULL:
2420 return None
2421 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002422 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002423 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002424
Jim Shaverabff1882015-05-27 09:15:55 -04002425 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002426 """
Alex Chand072cae2018-02-15 09:57:59 +00002427 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002428
2429 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002430 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002431 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002432 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002433 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002434 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002435 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002436
Jim Shaver208438c2015-05-28 09:52:38 -04002437 def get_protocol_version(self):
2438 """
Alex Chand072cae2018-02-15 09:57:59 +00002439 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002440
Alex Chand072cae2018-02-15 09:57:59 +00002441 :returns: The TLS version of the current connection. For example,
2442 it will return ``0x769`` for connections made over TLS version 1.
2443 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002444 """
2445 version = _lib.SSL_version(self._ssl)
2446 return version
2447
Cory Benfield10b277f2015-04-13 17:12:42 -04002448 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002449 def get_next_proto_negotiated(self):
2450 """
2451 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002452
2453 :returns: A bytestring of the protocol name. If no protocol has been
2454 negotiated yet, returns an empty string.
2455
2456 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002457 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002458 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002459 data = _ffi.new("unsigned char **")
2460 data_len = _ffi.new("unsigned int *")
2461
2462 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2463
Cory Benfieldcd010f62014-05-15 19:00:27 +01002464 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002465
Cory Benfield7907e332015-04-13 17:18:25 -04002466 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002467 def set_alpn_protos(self, protos):
2468 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002469 Specify the client's ALPN protocol list.
2470
2471 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002472
2473 :param protos: A list of the protocols to be offered to the server.
2474 This list should be a Python list of bytestrings representing the
2475 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2476 """
2477 # Take the list of protocols and join them together, prefixing them
2478 # with their lengths.
2479 protostr = b''.join(
2480 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2481 )
2482
2483 # Build a C string from the list. We don't need to save this off
2484 # because OpenSSL immediately copies the data out.
2485 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002486 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002487
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002488 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002489 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002490 """
2491 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002492
2493 :returns: A bytestring of the protocol name. If no protocol has been
2494 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002495 """
Cory Benfield12eae892014-06-07 15:42:56 +01002496 data = _ffi.new("unsigned char **")
2497 data_len = _ffi.new("unsigned int *")
2498
2499 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2500
Cory Benfielde8e9c382015-04-11 17:33:48 -04002501 if not data_len:
2502 return b''
2503
Cory Benfield12eae892014-06-07 15:42:56 +01002504 return _ffi.buffer(data[0], data_len[0])[:]
2505
Cory Benfield496652a2017-01-24 11:42:56 +00002506 def request_ocsp(self):
2507 """
2508 Called to request that the server sends stapled OCSP data, if
2509 available. If this is not called on the client side then the server
2510 will not send OCSP data. Should be used in conjunction with
2511 :meth:`Context.set_ocsp_client_callback`.
2512 """
2513 rc = _lib.SSL_set_tlsext_status_type(
2514 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2515 )
2516 _openssl_assert(rc == 1)
2517
Cory Benfield12eae892014-06-07 15:42:56 +01002518
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002519# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2520# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002521_lib.SSL_library_init()