blob: e5fea1ec54ca547bbf1946489012612cbd6096d4 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor12576002019-11-18 00:18:50 -05009from six import integer_types, int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050010
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050011from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010012 UNSPECIFIED as _UNSPECIFIED,
13 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014 ffi as _ffi,
Daniel Holth079c9632019-11-17 22:45:52 -050015 from_buffer as _from_buffer,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050016 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000021 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080023
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080024from OpenSSL.crypto import (
Alex Gaynor03737182020-07-23 20:40:46 -040025 FILETYPE_PEM,
26 _PassphraseHelper,
27 PKey,
28 X509Name,
29 X509,
30 X509Store,
31)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080032
Nicolas Karolak736c6212017-11-26 14:40:28 +010033__all__ = [
Alex Gaynor03737182020-07-23 20:40:46 -040034 "OPENSSL_VERSION_NUMBER",
35 "SSLEAY_VERSION",
36 "SSLEAY_CFLAGS",
37 "SSLEAY_PLATFORM",
38 "SSLEAY_DIR",
39 "SSLEAY_BUILT_ON",
40 "SENT_SHUTDOWN",
41 "RECEIVED_SHUTDOWN",
42 "SSLv2_METHOD",
43 "SSLv3_METHOD",
44 "SSLv23_METHOD",
45 "TLSv1_METHOD",
46 "TLSv1_1_METHOD",
47 "TLSv1_2_METHOD",
48 "OP_NO_SSLv2",
49 "OP_NO_SSLv3",
50 "OP_NO_TLSv1",
51 "OP_NO_TLSv1_1",
52 "OP_NO_TLSv1_2",
53 "OP_NO_TLSv1_3",
54 "MODE_RELEASE_BUFFERS",
55 "OP_SINGLE_DH_USE",
56 "OP_SINGLE_ECDH_USE",
57 "OP_EPHEMERAL_RSA",
58 "OP_MICROSOFT_SESS_ID_BUG",
59 "OP_NETSCAPE_CHALLENGE_BUG",
60 "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
61 "OP_SSLREF2_REUSE_CERT_TYPE_BUG",
62 "OP_MICROSOFT_BIG_SSLV3_BUFFER",
63 "OP_MSIE_SSLV2_RSA_PADDING",
64 "OP_SSLEAY_080_CLIENT_DH_BUG",
65 "OP_TLS_D5_BUG",
66 "OP_TLS_BLOCK_PADDING_BUG",
67 "OP_DONT_INSERT_EMPTY_FRAGMENTS",
68 "OP_CIPHER_SERVER_PREFERENCE",
69 "OP_TLS_ROLLBACK_BUG",
70 "OP_PKCS1_CHECK_1",
71 "OP_PKCS1_CHECK_2",
72 "OP_NETSCAPE_CA_DN_BUG",
73 "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
74 "OP_NO_COMPRESSION",
75 "OP_NO_QUERY_MTU",
76 "OP_COOKIE_EXCHANGE",
77 "OP_NO_TICKET",
78 "OP_ALL",
79 "VERIFY_PEER",
80 "VERIFY_FAIL_IF_NO_PEER_CERT",
81 "VERIFY_CLIENT_ONCE",
82 "VERIFY_NONE",
83 "SESS_CACHE_OFF",
84 "SESS_CACHE_CLIENT",
85 "SESS_CACHE_SERVER",
86 "SESS_CACHE_BOTH",
87 "SESS_CACHE_NO_AUTO_CLEAR",
88 "SESS_CACHE_NO_INTERNAL_LOOKUP",
89 "SESS_CACHE_NO_INTERNAL_STORE",
90 "SESS_CACHE_NO_INTERNAL",
91 "SSL_ST_CONNECT",
92 "SSL_ST_ACCEPT",
93 "SSL_ST_MASK",
94 "SSL_CB_LOOP",
95 "SSL_CB_EXIT",
96 "SSL_CB_READ",
97 "SSL_CB_WRITE",
98 "SSL_CB_ALERT",
99 "SSL_CB_READ_ALERT",
100 "SSL_CB_WRITE_ALERT",
101 "SSL_CB_ACCEPT_LOOP",
102 "SSL_CB_ACCEPT_EXIT",
103 "SSL_CB_CONNECT_LOOP",
104 "SSL_CB_CONNECT_EXIT",
105 "SSL_CB_HANDSHAKE_START",
106 "SSL_CB_HANDSHAKE_DONE",
107 "Error",
108 "WantReadError",
109 "WantWriteError",
110 "WantX509LookupError",
111 "ZeroReturnError",
112 "SysCallError",
113 "SSLeay_version",
114 "Session",
115 "Context",
116 "Connection",
Nicolas Karolak736c6212017-11-26 14:40:28 +0100117]
118
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500119try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200120 _buffer = buffer
121except NameError:
Alex Gaynor03737182020-07-23 20:40:46 -0400122
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200123 class _buffer(object):
124 pass
125
Alex Gaynor03737182020-07-23 20:40:46 -0400126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500127OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
128SSLEAY_VERSION = _lib.SSLEAY_VERSION
129SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
130SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
131SSLEAY_DIR = _lib.SSLEAY_DIR
132SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
135RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800136
137SSLv2_METHOD = 1
138SSLv3_METHOD = 2
139SSLv23_METHOD = 3
140TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500141TLSv1_1_METHOD = 5
142TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800143
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500144OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
145OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
146OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700147OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
148OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Alex Gaynorcdbfd822020-12-14 22:57:52 -0500149try:
150 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
151except AttributeError:
152 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800153
Alex Gaynorbf012872016-06-04 13:18:39 -0700154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
Alex Gaynorbf012872016-06-04 13:18:39 -0700179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800184
Alex Gaynorc4889812015-09-04 08:43:17 -0400185OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800204
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500205SSL_CB_LOOP = _lib.SSL_CB_LOOP
206SSL_CB_EXIT = _lib.SSL_CB_EXIT
207SSL_CB_READ = _lib.SSL_CB_READ
208SSL_CB_WRITE = _lib.SSL_CB_WRITE
209SSL_CB_ALERT = _lib.SSL_CB_ALERT
210SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
211SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
212SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
213SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
214SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
215SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
216SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
217SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800218
Paul Kehrer55fb3412017-06-29 18:44:08 -0500219# Taken from https://golang.org/src/crypto/x509/root_linux.go
220_CERTIFICATE_FILE_LOCATIONS = [
221 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
222 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
223 "/etc/ssl/ca-bundle.pem", # OpenSUSE
224 "/etc/pki/tls/cacert.pem", # OpenELEC
225 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
226]
227
228_CERTIFICATE_PATH_LOCATIONS = [
229 "/etc/ssl/certs", # SLES10/SLES11
230]
231
Paul Kehrera92a1a72017-07-19 15:53:23 +0200232# These values are compared to output from cffi's ffi.string so they must be
233# byte strings.
234_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
235_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500236
Alex Gaynor83284952015-09-05 10:43:30 -0400237
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500238class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500239 """
240 An error occurred in an `OpenSSL.SSL` API.
241 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500242
243
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500244_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100245_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500246
247
248class WantReadError(Error):
249 pass
250
251
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500252class WantWriteError(Error):
253 pass
254
255
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500256class WantX509LookupError(Error):
257 pass
258
259
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500260class ZeroReturnError(Error):
261 pass
262
263
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500264class SysCallError(Error):
265 pass
266
267
Cory Benfield0ea76e72015-03-22 09:05:28 +0000268class _CallbackExceptionHelper(object):
269 """
270 A base class for wrapper classes that allow for intelligent exception
271 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500272
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400273 :ivar list _problems: Any exceptions that occurred while executing in a
274 context where they could not be raised in the normal way. Typically
275 this is because OpenSSL has called into some Python code and requires a
276 return value. The exceptions are saved to be raised later when it is
277 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000278 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400279
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400280 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800281 self._problems = []
282
Cory Benfield0ea76e72015-03-22 09:05:28 +0000283 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400284 """
285 Raise an exception from the OpenSSL error queue or that was previously
286 captured whe running a callback.
287 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288 if self._problems:
289 try:
290 _raise_current_error()
291 except Error:
292 pass
293 raise self._problems.pop(0)
294
295
296class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400297 """
298 Wrap a callback such that it can be used as a certificate verification
299 callback.
300 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400301
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800302 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400303 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800304
305 @wraps(callback)
306 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800307 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
308 _lib.X509_up_ref(x509)
309 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500310 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
311 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800312
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400313 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
314 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
315 connection = Connection._reverse_mapping[ssl]
316
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800317 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400318 result = callback(
319 connection, cert, error_number, error_depth, ok
320 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800321 except Exception as e:
322 self._problems.append(e)
323 return 0
324 else:
325 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500326 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800327 return 1
328 else:
329 return 0
330
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500331 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400332 "int (*)(int, X509_STORE_CTX *)", wrapper
333 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800334
335
Mark Williams5d890a02019-11-17 19:56:26 -0800336NO_OVERLAPPING_PROTOCOLS = object()
337
338
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400339class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400340 """
341 Wrap a callback such that it can be used as an ALPN selection callback.
342 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400343
Cory Benfieldf1177e72015-04-12 09:11:49 -0400344 def __init__(self, callback):
345 _CallbackExceptionHelper.__init__(self)
346
347 @wraps(callback)
348 def wrapper(ssl, out, outlen, in_, inlen, arg):
349 try:
350 conn = Connection._reverse_mapping[ssl]
351
352 # The string passed to us is made up of multiple
353 # length-prefixed bytestrings. We need to split that into a
354 # list.
355 instr = _ffi.buffer(in_, inlen)[:]
356 protolist = []
357 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400358 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400359 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400360 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400361 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400362
363 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800364 outbytes = callback(conn, protolist)
365 any_accepted = True
366 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400367 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800368 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500369 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800370 raise TypeError(
371 "ALPN callback must return a bytestring or the "
372 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
373 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400374
375 # Save our callback arguments on the connection object to make
376 # sure that they don't get freed before OpenSSL can use them.
377 # Then, return them in the appropriate output parameters.
378 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800379 _ffi.new("unsigned char *", len(outbytes)),
380 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400381 ]
382 outlen[0] = conn._alpn_select_callback_args[0][0]
383 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800384 if not any_accepted:
385 return _lib.SSL_TLSEXT_ERR_NOACK
386 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400387 except Exception as e:
388 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800389 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400390
391 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400392 (
393 "int (*)(SSL *, unsigned char **, unsigned char *, "
394 "const unsigned char *, unsigned int, void *)"
395 ),
396 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400397 )
398
399
Cory Benfield496652a2017-01-24 11:42:56 +0000400class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
401 """
402 Wrap a callback such that it can be used as an OCSP callback for the server
403 side.
404
405 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
406 ways. For servers, that callback is expected to retrieve some OCSP data and
407 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
408 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
409 is expected to check the OCSP data, and returns a negative value on error,
410 0 if the response is not acceptable, or positive if it is. These are
411 mutually exclusive return code behaviours, and they mean that we need two
412 helpers so that we always return an appropriate error code if the user's
413 code throws an exception.
414
415 Given that we have to have two helpers anyway, these helpers are a bit more
416 helpery than most: specifically, they hide a few more of the OpenSSL
417 functions so that the user has an easier time writing these callbacks.
418
419 This helper implements the server side.
420 """
421
422 def __init__(self, callback):
423 _CallbackExceptionHelper.__init__(self)
424
425 @wraps(callback)
426 def wrapper(ssl, cdata):
427 try:
428 conn = Connection._reverse_mapping[ssl]
429
430 # Extract the data if any was provided.
431 if cdata != _ffi.NULL:
432 data = _ffi.from_handle(cdata)
433 else:
434 data = None
435
436 # Call the callback.
437 ocsp_data = callback(conn, data)
438
Alex Gaynor12576002019-11-18 00:18:50 -0500439 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000440 raise TypeError("OCSP callback must return a bytestring.")
441
442 # If the OCSP data was provided, we will pass it to OpenSSL.
443 # However, we have an early exit here: if no OCSP data was
444 # provided we will just exit out and tell OpenSSL that there
445 # is nothing to do.
446 if not ocsp_data:
447 return 3 # SSL_TLSEXT_ERR_NOACK
448
David Benjamin7ac5f272018-05-21 21:24:04 -0400449 # OpenSSL takes ownership of this data and expects it to have
450 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000451 ocsp_data_length = len(ocsp_data)
452 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
453 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
454
455 _lib.SSL_set_tlsext_status_ocsp_resp(
456 ssl, data_ptr, ocsp_data_length
457 )
458
459 return 0
460 except Exception as e:
461 self._problems.append(e)
462 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
463
464 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
465
466
467class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
468 """
469 Wrap a callback such that it can be used as an OCSP callback for the client
470 side.
471
472 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
473 ways. For servers, that callback is expected to retrieve some OCSP data and
474 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
475 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
476 is expected to check the OCSP data, and returns a negative value on error,
477 0 if the response is not acceptable, or positive if it is. These are
478 mutually exclusive return code behaviours, and they mean that we need two
479 helpers so that we always return an appropriate error code if the user's
480 code throws an exception.
481
482 Given that we have to have two helpers anyway, these helpers are a bit more
483 helpery than most: specifically, they hide a few more of the OpenSSL
484 functions so that the user has an easier time writing these callbacks.
485
486 This helper implements the client side.
487 """
488
489 def __init__(self, callback):
490 _CallbackExceptionHelper.__init__(self)
491
492 @wraps(callback)
493 def wrapper(ssl, cdata):
494 try:
495 conn = Connection._reverse_mapping[ssl]
496
497 # Extract the data if any was provided.
498 if cdata != _ffi.NULL:
499 data = _ffi.from_handle(cdata)
500 else:
501 data = None
502
503 # Get the OCSP data.
504 ocsp_ptr = _ffi.new("unsigned char **")
505 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
506 if ocsp_len < 0:
507 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400508 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000509 else:
510 # Copy the OCSP data, then pass it to the callback.
511 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
512
513 valid = callback(conn, ocsp_data, data)
514
515 # Return 1 on success or 0 on error.
516 return int(bool(valid))
517
518 except Exception as e:
519 self._problems.append(e)
520 # Return negative value if an exception is hit.
521 return -1
522
523 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
524
525
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800526def _asFileDescriptor(obj):
527 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800528 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800529 meth = getattr(obj, "fileno", None)
530 if meth is not None:
531 obj = meth()
532
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800533 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800534 fd = obj
535
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800536 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800537 raise TypeError("argument must be an int, or have a fileno() method.")
538 elif fd < 0:
539 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400540 "file descriptor cannot be a negative integer (%i)" % (fd,)
541 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800542
543 return fd
544
545
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800546def SSLeay_version(type):
547 """
548 Return a string describing the version of OpenSSL in use.
549
Alex Chand072cae2018-02-15 09:57:59 +0000550 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800551 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500552 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800553
554
Cory Benfieldef404df2016-03-29 15:32:48 +0100555def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400556 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100557 Builds a decorator that ensures that functions that rely on OpenSSL
558 functions that are not present in this build raise NotImplementedError,
559 rather than AttributeError coming out of cryptography.
560
561 :param flag: A cryptography flag that guards the functions, e.g.
562 ``Cryptography_HAS_NEXTPROTONEG``.
563 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400564 """
Alex Gaynor03737182020-07-23 20:40:46 -0400565
Cory Benfieldef404df2016-03-29 15:32:48 +0100566 def _requires_decorator(func):
567 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400568
Cory Benfieldef404df2016-03-29 15:32:48 +0100569 @wraps(func)
570 def explode(*args, **kwargs):
571 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400572
Cory Benfieldef404df2016-03-29 15:32:48 +0100573 return explode
574 else:
575 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400576
Cory Benfieldef404df2016-03-29 15:32:48 +0100577 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400578
579
Cory Benfieldef404df2016-03-29 15:32:48 +0100580_requires_alpn = _make_requires(
581 _lib.Cryptography_HAS_ALPN, "ALPN not available"
582)
Cory Benfielde6f35882016-03-29 11:21:04 +0100583
Cory Benfielde6f35882016-03-29 11:21:04 +0100584
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200585_requires_keylog = _make_requires(
586 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
587)
588
589
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800590class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000591 """
592 A class representing an SSL session. A session defines certain connection
593 parameters which may be re-used to speed up the setup of subsequent
594 connections.
595
596 .. versionadded:: 0.14
597 """
Alex Gaynor03737182020-07-23 20:40:46 -0400598
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800599 pass
600
601
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800602class Context(object):
603 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100604 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400605 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000606
607 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
608 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800609 """
Alex Gaynor03737182020-07-23 20:40:46 -0400610
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800611 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800612 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500613 SSLv3_METHOD: "SSLv3_method",
614 SSLv23_METHOD: "SSLv23_method",
615 TLSv1_METHOD: "TLSv1_method",
616 TLSv1_1_METHOD: "TLSv1_1_method",
617 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400618 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500619 _methods = dict(
620 (identifier, getattr(_lib, name))
621 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400622 if getattr(_lib, name, None) is not None
623 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800624
625 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500626 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800627 raise TypeError("method must be an integer")
628
629 try:
630 method_func = self._methods[method]
631 except KeyError:
632 raise ValueError("No such protocol")
633
634 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700635 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800636
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500637 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700638 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500639 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800640
Alex Gaynor77debda2020-04-07 13:40:59 -0400641 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
642 # auto-selected. This function was added in 1.0.2 and made a noop in
643 # 1.1.0+ (where it is set automatically).
644 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
645 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600646
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800647 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800648 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800649 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800650 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800651 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800652 self._verify_callback = None
653 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200654 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656 self._app_data = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400657 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100658 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000659 self._ocsp_helper = None
660 self._ocsp_callback = None
661 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800662
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500663 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800665 def load_verify_locations(self, cafile, capath=None):
666 """
667 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000668 chain. Note that the certificates have to be in PEM format.
669
670 If capath is passed, it must be a directory prepared using the
671 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
672 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400674 :param cafile: In which file we can find the certificates (``bytes`` or
675 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800676 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400677 (``bytes`` or ``unicode``).
678
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800679 :return: None
680 """
681 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500682 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400683 else:
684 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800685
686 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500687 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400688 else:
689 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690
Alex Gaynor62da94d2015-09-05 14:37:34 -0400691 load_result = _lib.SSL_CTX_load_verify_locations(
692 self._context, cafile, capath
693 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500695 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 def _wrap_callback(self, callback):
698 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800699 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800700 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400701
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800702 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400703 FILETYPE_PEM, wrapper, more_args=True, truncate=True
704 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800706 def set_passwd_cb(self, callback, userdata=None):
707 """
Alex Chand072cae2018-02-15 09:57:59 +0000708 Set the passphrase callback. This function will be called
709 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800710
Alex Chand072cae2018-02-15 09:57:59 +0000711 :param callback: The Python callback to use. This must accept three
712 positional arguments. First, an integer giving the maximum length
713 of the passphrase it may return. If the returned passphrase is
714 longer than this, it will be truncated. Second, a boolean value
715 which will be true if the user should be prompted for the
716 passphrase twice and the callback should verify that the two values
717 supplied are equal. Third, the value given as the *userdata*
718 parameter to :meth:`set_passwd_cb`. The *callback* must return
719 a byte string. If an error occurs, *callback* should return a false
720 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800721 :param userdata: (optional) A Python object which will be given as
722 argument to the callback
723 :return: None
724 """
725 if not callable(callback):
726 raise TypeError("callback must be callable")
727
728 self._passphrase_helper = self._wrap_callback(callback)
729 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500730 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400731 self._context, self._passphrase_callback
732 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800733 self._passphrase_userdata = userdata
734
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 def set_default_verify_paths(self):
736 """
Alex Chand072cae2018-02-15 09:57:59 +0000737 Specify that the platform provided CA certificates are to be used for
738 verification purposes. This method has some caveats related to the
739 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
740
741 * macOS will only load certificates using this method if the user has
742 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
743 in the default location.
744 * Windows will not work.
745 * manylinux1 cryptography wheels will work on most common Linux
746 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
747 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748
749 :return: None
750 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500751 # SSL_CTX_set_default_verify_paths will attempt to load certs from
752 # both a cafile and capath that are set at compile time. However,
753 # it will first check environment variables and, if present, load
754 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500755 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400756 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500757 # After attempting to set default_verify_paths we need to know whether
758 # to go down the fallback path.
759 # First we'll check to see if any env vars have been set. If so,
760 # we won't try to do anything else because the user has set the path
761 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400762 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
763 "ascii"
764 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500765 file_env_var = _ffi.string(
766 _lib.X509_get_default_cert_file_env()
767 ).decode("ascii")
768 if not self._check_env_vars_set(dir_env_var, file_env_var):
769 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
770 default_file = _ffi.string(_lib.X509_get_default_cert_file())
771 # Now we check to see if the default_dir and default_file are set
772 # to the exact values we use in our manylinux1 builds. If they are
773 # then we know to load the fallbacks
774 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400775 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
776 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500777 ):
778 # This is manylinux1, let's load our fallback paths
779 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400780 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500781 )
782
783 def _check_env_vars_set(self, dir_env_var, file_env_var):
784 """
785 Check to see if the default cert dir/file environment vars are present.
786
787 :return: bool
788 """
789 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400790 os.environ.get(file_env_var) is not None
791 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500792 )
793
794 def _fallback_default_verify_paths(self, file_path, dir_path):
795 """
796 Default verify paths are based on the compiled version of OpenSSL.
797 However, when pyca/cryptography is compiled as a manylinux1 wheel
798 that compiled location can potentially be wrong. So, like Go, we
799 will try a predefined set of paths and attempt to load roots
800 from there.
801
802 :return: None
803 """
804 for cafile in file_path:
805 if os.path.isfile(cafile):
806 self.load_verify_locations(cafile)
807 break
808
809 for capath in dir_path:
810 if os.path.isdir(capath):
811 self.load_verify_locations(None, capath)
812 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800813
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814 def use_certificate_chain_file(self, certfile):
815 """
Alex Chand072cae2018-02-15 09:57:59 +0000816 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400818 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000819 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400820
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800821 :return: None
822 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400823 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800824
Alex Gaynor62da94d2015-09-05 14:37:34 -0400825 result = _lib.SSL_CTX_use_certificate_chain_file(
826 self._context, certfile
827 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800828 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500829 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800830
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800831 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800832 """
833 Load a certificate from a file
834
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400835 :param certfile: The name of the certificate file (``bytes`` or
836 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000837 :param filetype: (optional) The encoding of the file, which is either
838 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
839 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400840
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800841 :return: None
842 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400843 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500844 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800845 raise TypeError("filetype must be an integer")
846
Alex Gaynor62da94d2015-09-05 14:37:34 -0400847 use_result = _lib.SSL_CTX_use_certificate_file(
848 self._context, certfile, filetype
849 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800850 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500851 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800852
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800853 def use_certificate(self, cert):
854 """
855 Load a certificate from a X509 object
856
857 :param cert: The X509 object
858 :return: None
859 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800860 if not isinstance(cert, X509):
861 raise TypeError("cert must be an X509 instance")
862
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500863 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800864 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500865 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800866
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800867 def add_extra_chain_cert(self, certobj):
868 """
869 Add certificate to chain
870
871 :param certobj: The X509 certificate object to add to the chain
872 :return: None
873 """
874 if not isinstance(certobj, X509):
875 raise TypeError("certobj must be an X509 instance")
876
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500877 copy = _lib.X509_dup(certobj._x509)
878 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800879 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500880 # TODO: This is untested.
881 _lib.X509_free(copy)
882 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800883
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800884 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500885 if self._passphrase_helper is not None:
886 self._passphrase_helper.raise_if_problem(Error)
887
888 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800889
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400890 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891 """
892 Load a private key from a file
893
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400894 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000895 :param filetype: (optional) The encoding of the file, which is either
896 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
897 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400898
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899 :return: None
900 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400901 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800902
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400903 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800904 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500905 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800906 raise TypeError("filetype must be an integer")
907
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500908 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -0400909 self._context, keyfile, filetype
910 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800912 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800913
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800914 def use_privatekey(self, pkey):
915 """
916 Load a private key from a PKey object
917
918 :param pkey: The PKey object
919 :return: None
920 """
921 if not isinstance(pkey, PKey):
922 raise TypeError("pkey must be a PKey instance")
923
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500924 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800926 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800928 def check_privatekey(self):
929 """
Alex Chand072cae2018-02-15 09:57:59 +0000930 Check if the private key (loaded with :meth:`use_privatekey`) matches
931 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800932
Alex Chand072cae2018-02-15 09:57:59 +0000933 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500935 if not _lib.SSL_CTX_check_private_key(self._context):
936 _raise_current_error()
937
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800938 def load_client_ca(self, cafile):
939 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100940 Load the trusted certificates that will be sent to the client. Does
941 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400942 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100944 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800945 :return: None
946 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100947 ca_list = _lib.SSL_load_client_CA_file(
948 _text_to_bytes_and_warn("cafile", cafile)
949 )
950 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100951 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952
953 def set_session_id(self, buf):
954 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100955 Set the session id to *buf* within which a session can be reused for
956 this Context object. This is needed when doing session resumption,
957 because there is no way for a stored session to know which Context
958 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100960 :param bytes buf: The session id.
961
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 :returns: None
963 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100964 buf = _text_to_bytes_and_warn("buf", buf)
965 _openssl_assert(
Alex Gaynor124a0132020-10-27 00:15:17 -0400966 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf))
Alex Gaynor03737182020-07-23 20:40:46 -0400967 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100968 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800969
970 def set_session_cache_mode(self, mode):
971 """
Alex Chand072cae2018-02-15 09:57:59 +0000972 Set the behavior of the session cache used by all connections using
973 this Context. The previously set mode is returned. See
974 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975
976 :param mode: One or more of the SESS_CACHE_* flags (combine using
977 bitwise or)
978 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000979
980 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800981 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500982 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983 raise TypeError("mode must be an integer")
984
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500985 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987 def get_session_cache_mode(self):
988 """
Alex Chand072cae2018-02-15 09:57:59 +0000989 Get the current session cache mode.
990
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +0000992
993 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500995 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996
Maximilian Hils79b9c792020-08-08 03:08:17 +0200997 def set_verify(self, mode, callback=None):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800998 """
Arne Schwabee93aea72020-11-13 15:12:49 +0100999 Set the verification flags for this Context object to *mode* and
1000 specify that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001
Alex Chand072cae2018-02-15 09:57:59 +00001002 :param mode: The verify mode, this should be one of
1003 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1004 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1005 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1006 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
Maximilian Hils79b9c792020-08-08 03:08:17 +02001007 :param callback: The optional Python verification callback to use.
1008 This should take five arguments: A Connection object, an X509
1009 object, and three integer variables, which are in turn potential
1010 error number, error depth and return code. *callback* should
1011 return True if verification passes and False otherwise.
1012 If omitted, OpenSSL's default verification is used.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001013 :return: None
1014
1015 See SSL_CTX_set_verify(3SSL) for further details.
1016 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001017 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001018 raise TypeError("mode must be an integer")
1019
Maximilian Hils79b9c792020-08-08 03:08:17 +02001020 if callback is None:
1021 self._verify_helper = None
1022 self._verify_callback = None
1023 _lib.SSL_CTX_set_verify(self._context, mode, _ffi.NULL)
1024 else:
1025 if not callable(callback):
1026 raise TypeError("callback must be callable")
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001027
Maximilian Hils79b9c792020-08-08 03:08:17 +02001028 self._verify_helper = _VerifyHelper(callback)
1029 self._verify_callback = self._verify_helper.callback
1030 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001031
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032 def set_verify_depth(self, depth):
1033 """
Alex Chand072cae2018-02-15 09:57:59 +00001034 Set the maximum depth for the certificate chain verification that shall
1035 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001036
1037 :param depth: An integer specifying the verify depth
1038 :return: None
1039 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001040 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041 raise TypeError("depth must be an integer")
1042
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001043 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045 def get_verify_mode(self):
1046 """
Alex Chand072cae2018-02-15 09:57:59 +00001047 Retrieve the Context object's verify mode, as set by
1048 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001049
1050 :return: The verify mode
1051 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001052 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001053
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054 def get_verify_depth(self):
1055 """
Alex Chand072cae2018-02-15 09:57:59 +00001056 Retrieve the Context object's verify depth, as set by
1057 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001058
1059 :return: The verify depth
1060 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001061 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001062
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001063 def load_tmp_dh(self, dhfile):
1064 """
1065 Load parameters for Ephemeral Diffie-Hellman
1066
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001067 :param dhfile: The file to load EDH parameters from (``bytes`` or
1068 ``unicode``).
1069
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070 :return: None
1071 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001072 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001074 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001075 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001076 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001078
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1080 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001081 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1082 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001084 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001085 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001086 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001087
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001088 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001089 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1090 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001091
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001092 :return: None
1093 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001094 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001095
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096 def set_cipher_list(self, cipher_list):
1097 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001098 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001100 See the OpenSSL manual for more information (e.g.
1101 :manpage:`ciphers(1)`).
1102
1103 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001104 :return: None
1105 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001106 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001107
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001108 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001109 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001110
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001111 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001112 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001113 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001114 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1115 # ciphers even if you pass an invalid cipher. Applications (like
1116 # Twisted) have tests that depend on an error being raised if an
1117 # invalid cipher string is passed, but without the following check
1118 # for the TLS 1.3 specific cipher suites it would never error.
1119 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001120 if tmpconn.get_cipher_list() == [
1121 "TLS_AES_256_GCM_SHA384",
1122 "TLS_CHACHA20_POLY1305_SHA256",
1123 "TLS_AES_128_GCM_SHA256",
1124 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001125 raise Error(
1126 [
1127 (
Alex Gaynor03737182020-07-23 20:40:46 -04001128 "SSL routines",
1129 "SSL_CTX_set_cipher_list",
1130 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001131 ),
1132 ],
1133 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001134
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001135 def set_client_ca_list(self, certificate_authorities):
1136 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001137 Set the list of preferred client certificate signers for this server
1138 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001139
Alex Gaynor62da94d2015-09-05 14:37:34 -04001140 This list of certificate authorities will be sent to the client when
1141 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
1143 :param certificate_authorities: a sequence of X509Names.
1144 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001145
1146 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001149 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001150
1151 try:
1152 for ca_name in certificate_authorities:
1153 if not isinstance(ca_name, X509Name):
1154 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001155 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001156 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001157 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001158 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001159 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001161 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001163 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001164 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001166 raise
1167
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001169
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001170 def add_client_ca(self, certificate_authority):
1171 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001172 Add the CA certificate to the list of preferred signers for this
1173 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001174
1175 The list of certificate authorities will be sent to the client when the
1176 server requests a client certificate.
1177
1178 :param certificate_authority: certificate authority's X509 certificate.
1179 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001180
1181 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001183 if not isinstance(certificate_authority, X509):
1184 raise TypeError("certificate_authority must be an X509 instance")
1185
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001186 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001187 self._context, certificate_authority._x509
1188 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001189 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001190
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001191 def set_timeout(self, timeout):
1192 """
Alex Chand072cae2018-02-15 09:57:59 +00001193 Set the timeout for newly created sessions for this Context object to
1194 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1195 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001196
Alex Chand072cae2018-02-15 09:57:59 +00001197 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198 :return: The previous session timeout
1199 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001200 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201 raise TypeError("timeout must be an integer")
1202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001203 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001205 def get_timeout(self):
1206 """
Alex Chand072cae2018-02-15 09:57:59 +00001207 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1208 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001209
1210 :return: The session timeout
1211 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001212 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001213
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001214 def set_info_callback(self, callback):
1215 """
Alex Chand072cae2018-02-15 09:57:59 +00001216 Set the information callback to *callback*. This function will be
1217 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001218
Alex Chand072cae2018-02-15 09:57:59 +00001219 :param callback: The Python callback to use. This should take three
1220 arguments: a Connection object and two integers. The first integer
1221 specifies where in the SSL handshake the function was called, and
1222 the other the return code from a (possibly failed) internal
1223 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001224 :return: None
1225 """
Alex Gaynor03737182020-07-23 20:40:46 -04001226
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001227 @wraps(callback)
1228 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001229 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001230
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001231 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001232 "void (*)(const SSL *, int, int)", wrapper
1233 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001234 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001235
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001236 @_requires_keylog
1237 def set_keylog_callback(self, callback):
1238 """
1239 Set the TLS key logging callback to *callback*. This function will be
1240 called whenever TLS key material is generated or received, in order
1241 to allow applications to store this keying material for debugging
1242 purposes.
1243
1244 :param callback: The Python callback to use. This should take two
1245 arguments: a Connection object and a bytestring that contains
1246 the key material in the format used by NSS for its SSLKEYLOGFILE
1247 debugging output.
1248 :return: None
1249 """
1250
1251 @wraps(callback)
1252 def wrapper(ssl, line):
1253 line = _ffi.string(line)
1254 callback(Connection._reverse_mapping[ssl], line)
1255
1256 self._keylog_callback = _ffi.callback(
1257 "void (*)(const SSL *, const char *)", wrapper
1258 )
1259 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1260
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001261 def get_app_data(self):
1262 """
Alex Chand072cae2018-02-15 09:57:59 +00001263 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264
1265 :return: The application data
1266 """
1267 return self._app_data
1268
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001269 def set_app_data(self, data):
1270 """
1271 Set the application data (will be returned from get_app_data())
1272
1273 :param data: Any Python object
1274 :return: None
1275 """
1276 self._app_data = data
1277
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001278 def get_cert_store(self):
1279 """
Alex Chand072cae2018-02-15 09:57:59 +00001280 Get the certificate store for the context. This can be used to add
1281 "trusted" certificates without using the
1282 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001283
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001284 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001285 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001286 store = _lib.SSL_CTX_get_cert_store(self._context)
1287 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001288 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001289 return None
1290
1291 pystore = X509Store.__new__(X509Store)
1292 pystore._store = store
1293 return pystore
1294
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001295 def set_options(self, options):
1296 """
1297 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001298 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001299
1300 :param options: The options to add.
1301 :return: The new option bitmask.
1302 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001303 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001304 raise TypeError("options must be an integer")
1305
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001306 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001307
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001308 def set_mode(self, mode):
1309 """
Alex Chand072cae2018-02-15 09:57:59 +00001310 Add modes via bitmask. Modes set before are not cleared! This method
1311 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001312
1313 :param mode: The mode to add.
1314 :return: The new mode bitmask.
1315 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001316 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317 raise TypeError("mode must be an integer")
1318
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001319 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001320
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321 def set_tlsext_servername_callback(self, callback):
1322 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001323 Specify a callback function to be called when clients specify a server
1324 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001325
1326 :param callback: The callback function. It will be invoked with one
1327 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001328
1329 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001330 """
Alex Gaynor03737182020-07-23 20:40:46 -04001331
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001332 @wraps(callback)
1333 def wrapper(ssl, alert, arg):
1334 callback(Connection._reverse_mapping[ssl])
1335 return 0
1336
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001337 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001338 "int (*)(SSL *, int *, void *)", wrapper
1339 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001340 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001341 self._context, self._tlsext_servername_callback
1342 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001343
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001344 def set_tlsext_use_srtp(self, profiles):
1345 """
1346 Enable support for negotiating SRTP keying material.
1347
1348 :param bytes profiles: A colon delimited list of protection profile
1349 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1350 :return: None
1351 """
1352 if not isinstance(profiles, bytes):
1353 raise TypeError("profiles must be a byte string.")
1354
1355 _openssl_assert(
1356 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1357 )
1358
Cory Benfield7907e332015-04-13 17:18:25 -04001359 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001360 def set_alpn_protos(self, protos):
1361 """
Alex Chand072cae2018-02-15 09:57:59 +00001362 Specify the protocols that the client is prepared to speak after the
1363 TLS connection has been negotiated using Application Layer Protocol
1364 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001365
1366 :param protos: A list of the protocols to be offered to the server.
1367 This list should be a Python list of bytestrings representing the
1368 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1369 """
1370 # Take the list of protocols and join them together, prefixing them
1371 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001372 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001373 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1374 )
1375
1376 # Build a C string from the list. We don't need to save this off
1377 # because OpenSSL immediately copies the data out.
1378 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001379 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001380
Cory Benfield7907e332015-04-13 17:18:25 -04001381 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001382 def set_alpn_select_callback(self, callback):
1383 """
Alex Chand072cae2018-02-15 09:57:59 +00001384 Specify a callback function that will be called on the server when a
1385 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001386
1387 :param callback: The callback function. It will be invoked with two
1388 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001389 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1390 one of those bytestrings to indicate the chosen protocol, the
1391 empty bytestring to terminate the TLS connection, or the
1392 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1393 protocol was selected, but that the connection should not be
1394 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001395 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001396 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001397 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001398 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001399 self._context, self._alpn_select_callback, _ffi.NULL
1400 )
Cory Benfield12eae892014-06-07 15:42:56 +01001401
Cory Benfield496652a2017-01-24 11:42:56 +00001402 def _set_ocsp_callback(self, helper, data):
1403 """
1404 This internal helper does the common work for
1405 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1406 almost all of it.
1407 """
1408 self._ocsp_helper = helper
1409 self._ocsp_callback = helper.callback
1410 if data is None:
1411 self._ocsp_data = _ffi.NULL
1412 else:
1413 self._ocsp_data = _ffi.new_handle(data)
1414
1415 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1416 self._context, self._ocsp_callback
1417 )
1418 _openssl_assert(rc == 1)
1419 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1420 _openssl_assert(rc == 1)
1421
1422 def set_ocsp_server_callback(self, callback, data=None):
1423 """
1424 Set a callback to provide OCSP data to be stapled to the TLS handshake
1425 on the server side.
1426
1427 :param callback: The callback function. It will be invoked with two
1428 arguments: the Connection, and the optional arbitrary data you have
1429 provided. The callback must return a bytestring that contains the
1430 OCSP data to staple to the handshake. If no OCSP data is available
1431 for this connection, return the empty bytestring.
1432 :param data: Some opaque data that will be passed into the callback
1433 function when called. This can be used to avoid needing to do
1434 complex data lookups or to keep track of what context is being
1435 used. This parameter is optional.
1436 """
1437 helper = _OCSPServerCallbackHelper(callback)
1438 self._set_ocsp_callback(helper, data)
1439
1440 def set_ocsp_client_callback(self, callback, data=None):
1441 """
1442 Set a callback to validate OCSP data stapled to the TLS handshake on
1443 the client side.
1444
1445 :param callback: The callback function. It will be invoked with three
1446 arguments: the Connection, a bytestring containing the stapled OCSP
1447 assertion, and the optional arbitrary data you have provided. The
1448 callback must return a boolean that indicates the result of
1449 validating the OCSP data: ``True`` if the OCSP data is valid and
1450 the certificate can be trusted, or ``False`` if either the OCSP
1451 data is invalid or the certificate has been revoked.
1452 :param data: Some opaque data that will be passed into the callback
1453 function when called. This can be used to avoid needing to do
1454 complex data lookups or to keep track of what context is being
1455 used. This parameter is optional.
1456 """
1457 helper = _OCSPClientCallbackHelper(callback)
1458 self._set_ocsp_callback(helper, data)
1459
Alex Chanc6077062016-11-18 13:53:39 +00001460
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001461class Connection(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001462 _reverse_mapping = WeakValueDictionary()
1463
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001464 def __init__(self, context, socket=None):
1465 """
1466 Create a new Connection object, using the given OpenSSL.SSL.Context
1467 instance and socket.
1468
1469 :param context: An SSL Context to use for this connection
1470 :param socket: The socket to use for transport layer
1471 """
1472 if not isinstance(context, Context):
1473 raise TypeError("context must be a Context instance")
1474
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001475 ssl = _lib.SSL_new(context._context)
1476 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001477 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1478 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1479 # even though there is still data on the underlying transport.
1480 # See https://github.com/openssl/openssl/issues/6234 for more details.
1481 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001482 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001483 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001484
Cory Benfield12eae892014-06-07 15:42:56 +01001485 # References to strings used for Application Layer Protocol
1486 # Negotiation. These strings get copied at some point but it's well
1487 # after the callback returns, so we have to hang them somewhere to
1488 # avoid them getting freed.
1489 self._alpn_select_callback_args = None
1490
Arne Schwabe3562df82020-11-27 19:29:49 +01001491 # Reference the verify_callback of the Context. This ensures that if
1492 # set_verify is called again after the SSL object has been created we
1493 # do not point to a dangling reference
1494 self._verify_helper = context._verify_helper
1495 self._verify_callback = context._verify_callback
1496
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001497 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498
1499 if socket is None:
1500 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001501 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001502 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001503 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504
Alex Gaynora829e902016-06-04 18:16:01 -07001505 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1506 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001508 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001509 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001510 self._into_ssl = None
1511 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001513 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001514 self._ssl, _asFileDescriptor(self._socket)
1515 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001516 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001518 def __getattr__(self, name):
1519 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001520 Look up attributes on the wrapped socket object if they are not found
1521 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001522 """
kjav0b66fa12015-09-02 11:51:26 +01001523 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001524 raise AttributeError(
1525 "'%s' object has no attribute '%s'"
1526 % (self.__class__.__name__, name)
1527 )
kjav0b66fa12015-09-02 11:51:26 +01001528 else:
1529 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001530
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001531 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001532 if self._context._verify_helper is not None:
1533 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001534 if self._context._alpn_select_helper is not None:
1535 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001536 if self._context._ocsp_helper is not None:
1537 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001538
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001539 error = _lib.SSL_get_error(ssl, result)
1540 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001541 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001543 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001544 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001545 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001546 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001547 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001548 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001549 elif error == _lib.SSL_ERROR_SYSCALL:
1550 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001552 if platform == "win32":
1553 errno = _ffi.getwinerror()[0]
1554 else:
1555 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001556
1557 if errno != 0:
1558 raise SysCallError(errno, errorcode.get(errno))
1559 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001560 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001561 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001562 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001563 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001564 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001566 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001568 def get_context(self):
1569 """
Alex Chand072cae2018-02-15 09:57:59 +00001570 Retrieve the :class:`Context` object associated with this
1571 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001575 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576 """
Alex Chand072cae2018-02-15 09:57:59 +00001577 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578
Alex Chand072cae2018-02-15 09:57:59 +00001579 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582 if not isinstance(context, Context):
1583 raise TypeError("context must be a Context instance")
1584
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001585 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 self._context = context
1587
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 def get_servername(self):
1589 """
1590 Retrieve the servername extension value if provided in the client hello
1591 message, or None if there wasn't one.
1592
Alex Chand072cae2018-02-15 09:57:59 +00001593 :return: A byte string giving the server name or :data:`None`.
1594
1595 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001597 name = _lib.SSL_get_servername(
1598 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1599 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001600 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001601 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001602
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001606 """
1607 Set the value of the servername extension to send in the client hello.
1608
1609 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001610
1611 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 if not isinstance(name, bytes):
1614 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001615 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001616 raise TypeError("name must not contain NUL byte")
1617
1618 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001619 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001620
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001621 def pending(self):
1622 """
Alex Chand072cae2018-02-15 09:57:59 +00001623 Get the number of bytes that can be safely read from the SSL buffer
1624 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625
1626 :return: The number of bytes available in the receive buffer.
1627 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001630 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631 """
1632 Send data on the connection. NOTE: If you get one of the WantRead,
1633 WantWrite or WantX509Lookup exceptions on this, you have to call the
1634 method again with the SAME buffer.
1635
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001636 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637 :param flags: (optional) Included for compatibility with the socket
1638 API, the value is ignored
1639 :return: The number of bytes written
1640 """
Abraham Martine82326c2015-02-04 10:18:10 +00001641 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001642 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001643
Daniel Holth079c9632019-11-17 22:45:52 -05001644 with _from_buffer(buf) as data:
1645 # check len(buf) instead of len(data) for testability
1646 if len(buf) > 2147483647:
1647 raise ValueError(
1648 "Cannot send more than 2**31-1 bytes at once."
1649 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001650
Daniel Holth079c9632019-11-17 22:45:52 -05001651 result = _lib.SSL_write(self._ssl, data, len(data))
1652 self._raise_ssl_error(self._ssl, result)
1653
1654 return result
1655
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656 write = send
1657
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001659 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001660 Send "all" data on the connection. This calls send() repeatedly until
1661 all data is sent. If an error occurs, it's impossible to tell how much
1662 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001664 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 :param flags: (optional) Included for compatibility with the socket
1666 API, the value is ignored
1667 :return: The number of bytes written
1668 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001669 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001670
Daniel Holth079c9632019-11-17 22:45:52 -05001671 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672
Daniel Holth079c9632019-11-17 22:45:52 -05001673 left_to_send = len(buf)
1674 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675
Daniel Holth079c9632019-11-17 22:45:52 -05001676 while left_to_send:
1677 # SSL_write's num arg is an int,
1678 # so we cannot send more than 2**31-1 bytes at once.
1679 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001680 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001681 )
1682 self._raise_ssl_error(self._ssl, result)
1683 total_sent += result
1684 left_to_send -= result
1685
1686 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001688 def recv(self, bufsiz, flags=None):
1689 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001690 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001691
1692 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001693 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1694 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001695 :return: The string read from the Connection
1696 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001697 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001698 if flags is not None and flags & socket.MSG_PEEK:
1699 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1700 else:
1701 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001702 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001704
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705 read = recv
1706
Cory Benfield62d10332014-06-15 10:03:41 +01001707 def recv_into(self, buffer, nbytes=None, flags=None):
1708 """
Alex Chand072cae2018-02-15 09:57:59 +00001709 Receive data on the connection and copy it directly into the provided
1710 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001711
1712 :param buffer: The buffer to copy into.
1713 :param nbytes: (optional) The maximum number of bytes to read into the
1714 buffer. If not present, defaults to the size of the buffer. If
1715 larger than the size of the buffer, is reduced to the size of the
1716 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001717 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1718 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001719 :return: The number of bytes read into the buffer.
1720 """
1721 if nbytes is None:
1722 nbytes = len(buffer)
1723 else:
1724 nbytes = min(nbytes, len(buffer))
1725
1726 # We need to create a temporary buffer. This is annoying, it would be
1727 # better if we could pass memoryviews straight into the SSL_read call,
1728 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001729 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001730 if flags is not None and flags & socket.MSG_PEEK:
1731 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1732 else:
1733 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001734 self._raise_ssl_error(self._ssl, result)
1735
1736 # This strange line is all to avoid a memory copy. The buffer protocol
1737 # should allow us to assign a CFFI buffer to the LHS of this line, but
1738 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001739 # wrap it in a memoryview.
1740 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001741
1742 return result
1743
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001744 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 if _lib.BIO_should_retry(bio):
1746 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001747 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001749 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001750 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001751 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001752 # TODO: This is untested. I think io_special means the socket
1753 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001754 raise ValueError("BIO_should_io_special")
1755 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001756 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001757 raise ValueError("unknown bio failure")
1758 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001759 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001760 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001762 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001763 """
Alex Chand072cae2018-02-15 09:57:59 +00001764 If the Connection was created with a memory BIO, this method can be
1765 used to read bytes from the write end of that memory BIO. Many
1766 Connection methods will add bytes which must be read in this manner or
1767 the buffer will eventually fill up and the Connection will be able to
1768 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001769
1770 :param bufsiz: The maximum number of bytes to read
1771 :return: The string read.
1772 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001773 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001774 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001775
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001776 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001777 raise TypeError("bufsiz must be an integer")
1778
Cory Benfielde62840e2016-11-28 12:17:08 +00001779 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001780 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001781 if result <= 0:
1782 self._handle_bio_errors(self._from_ssl, result)
1783
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001784 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001785
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001786 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001787 """
Alex Chand072cae2018-02-15 09:57:59 +00001788 If the Connection was created with a memory BIO, this method can be
1789 used to add bytes to the read end of that memory BIO. The Connection
1790 can then read the bytes (for example, in response to a call to
1791 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792
1793 :param buf: The string to put into the memory BIO.
1794 :return: The number of bytes written
1795 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001796 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001797
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001798 if self._into_ssl is None:
1799 raise TypeError("Connection sock was not None")
1800
Daniel Holth079c9632019-11-17 22:45:52 -05001801 with _from_buffer(buf) as data:
1802 result = _lib.BIO_write(self._into_ssl, data, len(data))
1803 if result <= 0:
1804 self._handle_bio_errors(self._into_ssl, result)
1805 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001806
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001807 def renegotiate(self):
1808 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001809 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001810
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001811 :return: True if the renegotiation can be started, False otherwise
1812 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001813 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001814 if not self.renegotiate_pending():
1815 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1816 return True
1817 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001818
1819 def do_handshake(self):
1820 """
Alex Chand072cae2018-02-15 09:57:59 +00001821 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001822 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001823 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001824
1825 :return: None.
1826 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001827 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001828 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001829
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001830 def renegotiate_pending(self):
1831 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001832 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001833 a renegotiation is finished.
1834
1835 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001836 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001838 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839
1840 def total_renegotiations(self):
1841 """
1842 Find out the total number of renegotiations.
1843
1844 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001845 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001846 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001847 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001849 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001850 """
Alex Chand072cae2018-02-15 09:57:59 +00001851 Call the :meth:`connect` method of the underlying socket and set up SSL
1852 on the socket, using the :class:`Context` object supplied to this
1853 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001854
1855 :param addr: A remote address
1856 :return: What the socket's connect method returns
1857 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001858 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001859 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001861 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001862 """
Alex Chand072cae2018-02-15 09:57:59 +00001863 Call the :meth:`connect_ex` method of the underlying socket and set up
1864 SSL on the socket, using the Context object supplied to this Connection
1865 object at creation. Note that if the :meth:`connect_ex` method of the
1866 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867
1868 :param addr: A remove address
1869 :return: What the socket's connect_ex method returns
1870 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001871 connect_ex = self._socket.connect_ex
1872 self.set_connect_state()
1873 return connect_ex(addr)
1874
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875 def accept(self):
1876 """
Alex Chand072cae2018-02-15 09:57:59 +00001877 Call the :meth:`accept` method of the underlying socket and set up SSL
1878 on the returned socket, using the Context object supplied to this
1879 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880
Alex Chand072cae2018-02-15 09:57:59 +00001881 :return: A *(conn, addr)* pair where *conn* is the new
1882 :class:`Connection` object created, and *address* is as returned by
1883 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001884 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001885 client, addr = self._socket.accept()
1886 conn = Connection(self._context, client)
1887 conn.set_accept_state()
1888 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001890 def bio_shutdown(self):
1891 """
Alex Chand072cae2018-02-15 09:57:59 +00001892 If the Connection was created with a memory BIO, this method can be
1893 used to indicate that *end of file* has been reached on the read end of
1894 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001895
1896 :return: None
1897 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001898 if self._from_ssl is None:
1899 raise TypeError("Connection sock was not None")
1900
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001901 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001902
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001903 def shutdown(self):
1904 """
Alex Chand072cae2018-02-15 09:57:59 +00001905 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906
1907 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001908 have sent closure alerts), False otherwise (in which case you
1909 call :meth:`recv` or :meth:`send` when the connection becomes
1910 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001912 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001914 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 else:
1918 return False
1919
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001920 def get_cipher_list(self):
1921 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001922 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001924 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001925 """
1926 ciphers = []
1927 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001928 result = _lib.SSL_get_cipher_list(self._ssl, i)
1929 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001931 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932 return ciphers
1933
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934 def get_client_ca_list(self):
1935 """
1936 Get CAs whose certificates are suggested for client authentication.
1937
Alex Chand072cae2018-02-15 09:57:59 +00001938 :return: If this is a server connection, the list of certificate
1939 authorities that will be sent or has been sent to the client, as
1940 controlled by this :class:`Connection`'s :class:`Context`.
1941
1942 If this is a client connection, the list will be empty until the
1943 connection with the server is established.
1944
1945 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001946 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001947 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1948 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001949 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 return []
1951
1952 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1954 name = _lib.sk_X509_NAME_value(ca_names, i)
1955 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001956 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957
1958 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001959 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001960 result.append(pyname)
1961 return result
1962
Aykee7f33452018-05-16 19:18:16 +02001963 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001965 The makefile() method is not implemented, since there is no dup
1966 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001967
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001968 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001969 """
Alex Gaynor83284952015-09-05 10:43:30 -04001970 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001971 "Cannot make file object of OpenSSL.SSL.Connection"
1972 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
1974 def get_app_data(self):
1975 """
Alex Chand072cae2018-02-15 09:57:59 +00001976 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001977
1978 :return: The application data
1979 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001981
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001982 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983 """
1984 Set application data
1985
Alex Chand072cae2018-02-15 09:57:59 +00001986 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001987 :return: None
1988 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 self._app_data = data
1990
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001991 def get_shutdown(self):
1992 """
Alex Chand072cae2018-02-15 09:57:59 +00001993 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994
Alex Gaynor62da94d2015-09-05 14:37:34 -04001995 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1996 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001998 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 """
Alex Chand072cae2018-02-15 09:57:59 +00002002 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003
Alex Chand072cae2018-02-15 09:57:59 +00002004 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005 :return: None
2006 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002007 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002008 raise TypeError("state must be an integer")
2009
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002010 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002011
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002012 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002014 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015
2016 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002017 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018 """
kjavc704a2e2015-09-07 12:12:27 +01002019 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020
2021 def server_random(self):
2022 """
Alex Chand072cae2018-02-15 09:57:59 +00002023 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024
2025 :return: A string representing the state
2026 """
Alex Gaynor93603062016-06-01 20:13:09 -07002027 session = _lib.SSL_get_session(self._ssl)
2028 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002029 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002030 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002031 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002032 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002033 _lib.SSL_get_server_random(self._ssl, outp, length)
2034 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002035
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036 def client_random(self):
2037 """
Alex Chand072cae2018-02-15 09:57:59 +00002038 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002039
2040 :return: A string representing the state
2041 """
Alex Gaynor93603062016-06-01 20:13:09 -07002042 session = _lib.SSL_get_session(self._ssl)
2043 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002044 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002045
2046 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002047 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002048 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002049 _lib.SSL_get_client_random(self._ssl, outp, length)
2050 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052 def master_key(self):
2053 """
Alex Chand072cae2018-02-15 09:57:59 +00002054 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055
2056 :return: A string representing the state
2057 """
Alex Gaynor93603062016-06-01 20:13:09 -07002058 session = _lib.SSL_get_session(self._ssl)
2059 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002060 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002061
2062 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002063 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002064 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002065 _lib.SSL_SESSION_get_master_key(session, outp, length)
2066 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002067
Paul Kehrerbdb76392017-12-01 04:54:32 +08002068 def export_keying_material(self, label, olen, context=None):
2069 """
2070 Obtain keying material for application use.
2071
Alex Chand072cae2018-02-15 09:57:59 +00002072 :param: label - a disambiguating label string as described in RFC 5705
2073 :param: olen - the length of the exported key material in bytes
2074 :param: context - a per-association context value
2075 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002076 """
2077 outp = _no_zero_allocator("unsigned char[]", olen)
2078 context_buf = _ffi.NULL
2079 context_len = 0
2080 use_context = 0
2081 if context is not None:
2082 context_buf = context
2083 context_len = len(context)
2084 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002085 success = _lib.SSL_export_keying_material(
2086 self._ssl,
2087 outp,
2088 olen,
2089 label,
2090 len(label),
2091 context_buf,
2092 context_len,
2093 use_context,
2094 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002095 _openssl_assert(success == 1)
2096 return _ffi.buffer(outp, olen)[:]
2097
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002098 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002099 """
Alex Chand072cae2018-02-15 09:57:59 +00002100 Call the :meth:`shutdown` method of the underlying socket.
2101 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
2103 :return: What the socket's shutdown() method returns
2104 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002105 return self._socket.shutdown(*args, **kwargs)
2106
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002107 def get_certificate(self):
2108 """
2109 Retrieve the local certificate (if any)
2110
2111 :return: The local certificate
2112 """
2113 cert = _lib.SSL_get_certificate(self._ssl)
2114 if cert != _ffi.NULL:
2115 _lib.X509_up_ref(cert)
2116 return X509._from_raw_x509_ptr(cert)
2117 return None
2118
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002119 def get_peer_certificate(self):
2120 """
2121 Retrieve the other side's certificate (if any)
2122
2123 :return: The peer's certificate
2124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002125 cert = _lib.SSL_get_peer_certificate(self._ssl)
2126 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002127 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002128 return None
2129
Shane Harvey33c54992020-08-05 16:48:51 -07002130 @staticmethod
2131 def _cert_stack_to_list(cert_stack):
2132 """
2133 Internal helper to convert a STACK_OF(X509) to a list of X509
2134 instances.
2135 """
2136 result = []
2137 for i in range(_lib.sk_X509_num(cert_stack)):
2138 cert = _lib.sk_X509_value(cert_stack, i)
2139 _openssl_assert(cert != _ffi.NULL)
2140 res = _lib.X509_up_ref(cert)
2141 _openssl_assert(res >= 1)
2142 pycert = X509._from_raw_x509_ptr(cert)
2143 result.append(pycert)
2144 return result
2145
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002146 def get_peer_cert_chain(self):
2147 """
2148 Retrieve the other side's certificate (if any)
2149
2150 :return: A list of X509 instances giving the peer's certificate chain,
2151 or None if it does not have one.
2152 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002153 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2154 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002155 return None
2156
Shane Harvey33c54992020-08-05 16:48:51 -07002157 return self._cert_stack_to_list(cert_stack)
2158
2159 def get_verified_chain(self):
2160 """
2161 Retrieve the verified certificate chain of the peer including the
2162 peer's end entity certificate. It must be called after a session has
2163 been successfully established. If peer verification was not successful
2164 the chain may be incomplete, invalid, or None.
2165
2166 :return: A list of X509 instances giving the peer's verified
2167 certificate chain, or None if it does not have one.
2168
2169 .. versionadded:: 20.0
2170 """
Alex Gaynor124a0132020-10-27 00:15:17 -04002171 # OpenSSL 1.1+
2172 cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2173 if cert_stack == _ffi.NULL:
Shane Harvey33c54992020-08-05 16:48:51 -07002174 return None
2175
Alex Gaynor124a0132020-10-27 00:15:17 -04002176 return self._cert_stack_to_list(cert_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002177
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178 def want_read(self):
2179 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002180 Checks if more data has to be read from the transport layer to complete
2181 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002182
2183 :return: True iff more data has to be read
2184 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002185 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002186
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002187 def want_write(self):
2188 """
2189 Checks if there is data to write to the transport layer to complete an
2190 operation.
2191
2192 :return: True iff there is data to write
2193 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002194 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002195
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196 def set_accept_state(self):
2197 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002198 Set the connection to work in server mode. The handshake will be
2199 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002200
2201 :return: None
2202 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002203 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002204
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002205 def set_connect_state(self):
2206 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002207 Set the connection to work in client mode. The handshake will be
2208 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002209
2210 :return: None
2211 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002212 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002213
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002214 def get_session(self):
2215 """
2216 Returns the Session currently used.
2217
Alex Chand072cae2018-02-15 09:57:59 +00002218 :return: An instance of :class:`OpenSSL.SSL.Session` or
2219 :obj:`None` if no session exists.
2220
2221 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002222 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 session = _lib.SSL_get1_session(self._ssl)
2224 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002225 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002226
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002227 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002228 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002229 return pysession
2230
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002231 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002232 """
2233 Set the session to be used when the TLS/SSL connection is established.
2234
2235 :param session: A Session instance representing the session to use.
2236 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002237
2238 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002239 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002240 if not isinstance(session, Session):
2241 raise TypeError("session must be a Session instance")
2242
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002243 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002244 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002245
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002246 def _get_finished_message(self, function):
2247 """
Alex Chand072cae2018-02-15 09:57:59 +00002248 Helper to implement :meth:`get_finished` and
2249 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002250
Alex Chand072cae2018-02-15 09:57:59 +00002251 :param function: Either :data:`SSL_get_finished`: or
2252 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002253
Alex Chand072cae2018-02-15 09:57:59 +00002254 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002255 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002256 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002257 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002258 # The OpenSSL documentation says nothing about what might happen if the
2259 # count argument given is zero. Specifically, it doesn't say whether
2260 # the output buffer may be NULL in that case or not. Inspection of the
2261 # implementation reveals that it calls memcpy() unconditionally.
2262 # Section 7.1.4, paragraph 1 of the C standard suggests that
2263 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2264 # alone desirable) behavior (though it probably does on just about
2265 # every implementation...)
2266 #
2267 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2268 # one might expect) for the initial call so as to be safe against this
2269 # potentially undefined behavior.
2270 empty = _ffi.new("char[]", 0)
2271 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002272 if size == 0:
2273 # No Finished message so far.
2274 return None
2275
Cory Benfielde62840e2016-11-28 12:17:08 +00002276 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002277 function(self._ssl, buf, size)
2278 return _ffi.buffer(buf, size)[:]
2279
Fedor Brunner5747b932014-03-05 14:22:34 +01002280 def get_finished(self):
2281 """
Alex Chand072cae2018-02-15 09:57:59 +00002282 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002283
Alex Chand072cae2018-02-15 09:57:59 +00002284 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002285 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002286 :rtype: :class:`bytes` or :class:`NoneType`
2287
2288 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002289 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002290 return self._get_finished_message(_lib.SSL_get_finished)
2291
Fedor Brunner5747b932014-03-05 14:22:34 +01002292 def get_peer_finished(self):
2293 """
Alex Chand072cae2018-02-15 09:57:59 +00002294 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002295
Alex Chand072cae2018-02-15 09:57:59 +00002296 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002297 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002298 :rtype: :class:`bytes` or :class:`NoneType`
2299
2300 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002301 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002302 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002303
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002304 def get_cipher_name(self):
2305 """
2306 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002307
Alex Chand072cae2018-02-15 09:57:59 +00002308 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002309 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002310 :rtype: :class:`unicode` or :class:`NoneType`
2311
2312 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002313 """
2314 cipher = _lib.SSL_get_current_cipher(self._ssl)
2315 if cipher == _ffi.NULL:
2316 return None
2317 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002318 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2319 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002320
2321 def get_cipher_bits(self):
2322 """
2323 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002324
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002325 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002326 or :obj:`None` if no connection has been established.
2327 :rtype: :class:`int` or :class:`NoneType`
2328
2329 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002330 """
2331 cipher = _lib.SSL_get_current_cipher(self._ssl)
2332 if cipher == _ffi.NULL:
2333 return None
2334 else:
2335 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2336
2337 def get_cipher_version(self):
2338 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002339 Obtain the protocol version of the currently used cipher.
2340
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002341 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002342 or :obj:`None` if no connection has been established.
2343 :rtype: :class:`unicode` or :class:`NoneType`
2344
2345 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002346 """
2347 cipher = _lib.SSL_get_current_cipher(self._ssl)
2348 if cipher == _ffi.NULL:
2349 return None
2350 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002351 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002352 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002353
Jim Shaverabff1882015-05-27 09:15:55 -04002354 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002355 """
Alex Chand072cae2018-02-15 09:57:59 +00002356 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002357
2358 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002359 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002360 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002361 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002362 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002363 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002364 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002365
Jim Shaver208438c2015-05-28 09:52:38 -04002366 def get_protocol_version(self):
2367 """
Alex Chand072cae2018-02-15 09:57:59 +00002368 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002369
Alex Chand072cae2018-02-15 09:57:59 +00002370 :returns: The TLS version of the current connection. For example,
2371 it will return ``0x769`` for connections made over TLS version 1.
2372 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002373 """
2374 version = _lib.SSL_version(self._ssl)
2375 return version
2376
Cory Benfield7907e332015-04-13 17:18:25 -04002377 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002378 def set_alpn_protos(self, protos):
2379 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002380 Specify the client's ALPN protocol list.
2381
2382 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002383
2384 :param protos: A list of the protocols to be offered to the server.
2385 This list should be a Python list of bytestrings representing the
2386 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2387 """
2388 # Take the list of protocols and join them together, prefixing them
2389 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002390 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002391 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2392 )
2393
2394 # Build a C string from the list. We don't need to save this off
2395 # because OpenSSL immediately copies the data out.
2396 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002397 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002398
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002399 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002400 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002401 """
2402 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002403
2404 :returns: A bytestring of the protocol name. If no protocol has been
2405 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002406 """
Cory Benfield12eae892014-06-07 15:42:56 +01002407 data = _ffi.new("unsigned char **")
2408 data_len = _ffi.new("unsigned int *")
2409
2410 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2411
Cory Benfielde8e9c382015-04-11 17:33:48 -04002412 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002413 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002414
Cory Benfield12eae892014-06-07 15:42:56 +01002415 return _ffi.buffer(data[0], data_len[0])[:]
2416
Cory Benfield496652a2017-01-24 11:42:56 +00002417 def request_ocsp(self):
2418 """
2419 Called to request that the server sends stapled OCSP data, if
2420 available. If this is not called on the client side then the server
2421 will not send OCSP data. Should be used in conjunction with
2422 :meth:`Context.set_ocsp_client_callback`.
2423 """
2424 rc = _lib.SSL_set_tlsext_status_type(
2425 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2426 )
2427 _openssl_assert(rc == 1)
2428
Cory Benfield12eae892014-06-07 15:42:56 +01002429
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002430# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2431# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002432_lib.SSL_library_init()