blob: 9b9f638a1bdb5052dca62ab2f79125d7f6b0a1c5 [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 Gaynor124a0132020-10-27 00:15:17 -0400149OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800150
Alex Gaynorbf012872016-06-04 13:18:39 -0700151MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800152
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500153OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900154OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500155OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
156OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
157OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400158OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
159 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
160)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500161OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
162OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400163OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
165OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
166OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
167OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
168OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
169OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
170OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
171OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
172OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400173OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
174 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
175)
Alex Gaynorbf012872016-06-04 13:18:39 -0700176OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800177
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500178OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
179OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400180OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800181
Alex Gaynorc4889812015-09-04 08:43:17 -0400182OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800183
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500184VERIFY_PEER = _lib.SSL_VERIFY_PEER
185VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
186VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
187VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800188
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500189SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
190SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
191SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
192SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
193SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
194SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
195SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
196SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800197
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500198SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
199SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
200SSL_ST_MASK = _lib.SSL_ST_MASK
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800201
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500202SSL_CB_LOOP = _lib.SSL_CB_LOOP
203SSL_CB_EXIT = _lib.SSL_CB_EXIT
204SSL_CB_READ = _lib.SSL_CB_READ
205SSL_CB_WRITE = _lib.SSL_CB_WRITE
206SSL_CB_ALERT = _lib.SSL_CB_ALERT
207SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
208SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
209SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
210SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
211SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
212SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
213SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
214SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800215
Paul Kehrer55fb3412017-06-29 18:44:08 -0500216# Taken from https://golang.org/src/crypto/x509/root_linux.go
217_CERTIFICATE_FILE_LOCATIONS = [
218 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
219 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
220 "/etc/ssl/ca-bundle.pem", # OpenSUSE
221 "/etc/pki/tls/cacert.pem", # OpenELEC
222 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
223]
224
225_CERTIFICATE_PATH_LOCATIONS = [
226 "/etc/ssl/certs", # SLES10/SLES11
227]
228
Paul Kehrera92a1a72017-07-19 15:53:23 +0200229# These values are compared to output from cffi's ffi.string so they must be
230# byte strings.
231_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
232_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500233
Alex Gaynor83284952015-09-05 10:43:30 -0400234
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500235class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500236 """
237 An error occurred in an `OpenSSL.SSL` API.
238 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500239
240
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500241_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100242_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243
244
245class WantReadError(Error):
246 pass
247
248
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500249class WantWriteError(Error):
250 pass
251
252
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500253class WantX509LookupError(Error):
254 pass
255
256
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500257class ZeroReturnError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class SysCallError(Error):
262 pass
263
264
Cory Benfield0ea76e72015-03-22 09:05:28 +0000265class _CallbackExceptionHelper(object):
266 """
267 A base class for wrapper classes that allow for intelligent exception
268 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400270 :ivar list _problems: Any exceptions that occurred while executing in a
271 context where they could not be raised in the normal way. Typically
272 this is because OpenSSL has called into some Python code and requires a
273 return value. The exceptions are saved to be raised later when it is
274 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000275 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400276
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400277 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800278 self._problems = []
279
Cory Benfield0ea76e72015-03-22 09:05:28 +0000280 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400281 """
282 Raise an exception from the OpenSSL error queue or that was previously
283 captured whe running a callback.
284 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000285 if self._problems:
286 try:
287 _raise_current_error()
288 except Error:
289 pass
290 raise self._problems.pop(0)
291
292
293class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400294 """
295 Wrap a callback such that it can be used as a certificate verification
296 callback.
297 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400298
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800299 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400300 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800301
302 @wraps(callback)
303 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800304 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
305 _lib.X509_up_ref(x509)
306 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500307 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
308 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800309
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400310 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
311 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
312 connection = Connection._reverse_mapping[ssl]
313
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800314 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400315 result = callback(
316 connection, cert, error_number, error_depth, ok
317 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800318 except Exception as e:
319 self._problems.append(e)
320 return 0
321 else:
322 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500323 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800324 return 1
325 else:
326 return 0
327
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500328 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400329 "int (*)(int, X509_STORE_CTX *)", wrapper
330 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800331
332
Mark Williams5d890a02019-11-17 19:56:26 -0800333NO_OVERLAPPING_PROTOCOLS = object()
334
335
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400336class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400337 """
338 Wrap a callback such that it can be used as an ALPN selection callback.
339 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400340
Cory Benfieldf1177e72015-04-12 09:11:49 -0400341 def __init__(self, callback):
342 _CallbackExceptionHelper.__init__(self)
343
344 @wraps(callback)
345 def wrapper(ssl, out, outlen, in_, inlen, arg):
346 try:
347 conn = Connection._reverse_mapping[ssl]
348
349 # The string passed to us is made up of multiple
350 # length-prefixed bytestrings. We need to split that into a
351 # list.
352 instr = _ffi.buffer(in_, inlen)[:]
353 protolist = []
354 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400355 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400356 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400357 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400358 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400359
360 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800361 outbytes = callback(conn, protolist)
362 any_accepted = True
363 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400364 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800365 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500366 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800367 raise TypeError(
368 "ALPN callback must return a bytestring or the "
369 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
370 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400371
372 # Save our callback arguments on the connection object to make
373 # sure that they don't get freed before OpenSSL can use them.
374 # Then, return them in the appropriate output parameters.
375 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800376 _ffi.new("unsigned char *", len(outbytes)),
377 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400378 ]
379 outlen[0] = conn._alpn_select_callback_args[0][0]
380 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800381 if not any_accepted:
382 return _lib.SSL_TLSEXT_ERR_NOACK
383 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400384 except Exception as e:
385 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800386 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400387
388 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400389 (
390 "int (*)(SSL *, unsigned char **, unsigned char *, "
391 "const unsigned char *, unsigned int, void *)"
392 ),
393 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400394 )
395
396
Cory Benfield496652a2017-01-24 11:42:56 +0000397class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
398 """
399 Wrap a callback such that it can be used as an OCSP callback for the server
400 side.
401
402 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
403 ways. For servers, that callback is expected to retrieve some OCSP data and
404 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
405 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
406 is expected to check the OCSP data, and returns a negative value on error,
407 0 if the response is not acceptable, or positive if it is. These are
408 mutually exclusive return code behaviours, and they mean that we need two
409 helpers so that we always return an appropriate error code if the user's
410 code throws an exception.
411
412 Given that we have to have two helpers anyway, these helpers are a bit more
413 helpery than most: specifically, they hide a few more of the OpenSSL
414 functions so that the user has an easier time writing these callbacks.
415
416 This helper implements the server side.
417 """
418
419 def __init__(self, callback):
420 _CallbackExceptionHelper.__init__(self)
421
422 @wraps(callback)
423 def wrapper(ssl, cdata):
424 try:
425 conn = Connection._reverse_mapping[ssl]
426
427 # Extract the data if any was provided.
428 if cdata != _ffi.NULL:
429 data = _ffi.from_handle(cdata)
430 else:
431 data = None
432
433 # Call the callback.
434 ocsp_data = callback(conn, data)
435
Alex Gaynor12576002019-11-18 00:18:50 -0500436 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000437 raise TypeError("OCSP callback must return a bytestring.")
438
439 # If the OCSP data was provided, we will pass it to OpenSSL.
440 # However, we have an early exit here: if no OCSP data was
441 # provided we will just exit out and tell OpenSSL that there
442 # is nothing to do.
443 if not ocsp_data:
444 return 3 # SSL_TLSEXT_ERR_NOACK
445
David Benjamin7ac5f272018-05-21 21:24:04 -0400446 # OpenSSL takes ownership of this data and expects it to have
447 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000448 ocsp_data_length = len(ocsp_data)
449 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
450 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
451
452 _lib.SSL_set_tlsext_status_ocsp_resp(
453 ssl, data_ptr, ocsp_data_length
454 )
455
456 return 0
457 except Exception as e:
458 self._problems.append(e)
459 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
460
461 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
462
463
464class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
465 """
466 Wrap a callback such that it can be used as an OCSP callback for the client
467 side.
468
469 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
470 ways. For servers, that callback is expected to retrieve some OCSP data and
471 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
472 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
473 is expected to check the OCSP data, and returns a negative value on error,
474 0 if the response is not acceptable, or positive if it is. These are
475 mutually exclusive return code behaviours, and they mean that we need two
476 helpers so that we always return an appropriate error code if the user's
477 code throws an exception.
478
479 Given that we have to have two helpers anyway, these helpers are a bit more
480 helpery than most: specifically, they hide a few more of the OpenSSL
481 functions so that the user has an easier time writing these callbacks.
482
483 This helper implements the client side.
484 """
485
486 def __init__(self, callback):
487 _CallbackExceptionHelper.__init__(self)
488
489 @wraps(callback)
490 def wrapper(ssl, cdata):
491 try:
492 conn = Connection._reverse_mapping[ssl]
493
494 # Extract the data if any was provided.
495 if cdata != _ffi.NULL:
496 data = _ffi.from_handle(cdata)
497 else:
498 data = None
499
500 # Get the OCSP data.
501 ocsp_ptr = _ffi.new("unsigned char **")
502 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
503 if ocsp_len < 0:
504 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400505 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000506 else:
507 # Copy the OCSP data, then pass it to the callback.
508 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
509
510 valid = callback(conn, ocsp_data, data)
511
512 # Return 1 on success or 0 on error.
513 return int(bool(valid))
514
515 except Exception as e:
516 self._problems.append(e)
517 # Return negative value if an exception is hit.
518 return -1
519
520 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
521
522
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800523def _asFileDescriptor(obj):
524 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800525 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800526 meth = getattr(obj, "fileno", None)
527 if meth is not None:
528 obj = meth()
529
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800530 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800531 fd = obj
532
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800533 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800534 raise TypeError("argument must be an int, or have a fileno() method.")
535 elif fd < 0:
536 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400537 "file descriptor cannot be a negative integer (%i)" % (fd,)
538 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800539
540 return fd
541
542
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800543def SSLeay_version(type):
544 """
545 Return a string describing the version of OpenSSL in use.
546
Alex Chand072cae2018-02-15 09:57:59 +0000547 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800548 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500549 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800550
551
Cory Benfieldef404df2016-03-29 15:32:48 +0100552def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400553 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100554 Builds a decorator that ensures that functions that rely on OpenSSL
555 functions that are not present in this build raise NotImplementedError,
556 rather than AttributeError coming out of cryptography.
557
558 :param flag: A cryptography flag that guards the functions, e.g.
559 ``Cryptography_HAS_NEXTPROTONEG``.
560 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400561 """
Alex Gaynor03737182020-07-23 20:40:46 -0400562
Cory Benfieldef404df2016-03-29 15:32:48 +0100563 def _requires_decorator(func):
564 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400565
Cory Benfieldef404df2016-03-29 15:32:48 +0100566 @wraps(func)
567 def explode(*args, **kwargs):
568 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400569
Cory Benfieldef404df2016-03-29 15:32:48 +0100570 return explode
571 else:
572 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400573
Cory Benfieldef404df2016-03-29 15:32:48 +0100574 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400575
576
Cory Benfieldef404df2016-03-29 15:32:48 +0100577_requires_alpn = _make_requires(
578 _lib.Cryptography_HAS_ALPN, "ALPN not available"
579)
Cory Benfielde6f35882016-03-29 11:21:04 +0100580
Cory Benfielde6f35882016-03-29 11:21:04 +0100581
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200582_requires_keylog = _make_requires(
583 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
584)
585
586
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800587class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000588 """
589 A class representing an SSL session. A session defines certain connection
590 parameters which may be re-used to speed up the setup of subsequent
591 connections.
592
593 .. versionadded:: 0.14
594 """
Alex Gaynor03737182020-07-23 20:40:46 -0400595
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800596 pass
597
598
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800599class Context(object):
600 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100601 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400602 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000603
604 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
605 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800606 """
Alex Gaynor03737182020-07-23 20:40:46 -0400607
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800609 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500610 SSLv3_METHOD: "SSLv3_method",
611 SSLv23_METHOD: "SSLv23_method",
612 TLSv1_METHOD: "TLSv1_method",
613 TLSv1_1_METHOD: "TLSv1_1_method",
614 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400615 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500616 _methods = dict(
617 (identifier, getattr(_lib, name))
618 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400619 if getattr(_lib, name, None) is not None
620 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800621
622 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500623 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800624 raise TypeError("method must be an integer")
625
626 try:
627 method_func = self._methods[method]
628 except KeyError:
629 raise ValueError("No such protocol")
630
631 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700632 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800633
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500634 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700635 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500636 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800637
Alex Gaynor77debda2020-04-07 13:40:59 -0400638 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
639 # auto-selected. This function was added in 1.0.2 and made a noop in
640 # 1.1.0+ (where it is set automatically).
641 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
642 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600643
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800645 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800646 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800647 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800648 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800649 self._verify_callback = None
650 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200651 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800652 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800653 self._app_data = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400654 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100655 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000656 self._ocsp_helper = None
657 self._ocsp_callback = None
658 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800659
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500660 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800662 def load_verify_locations(self, cafile, capath=None):
663 """
664 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000665 chain. Note that the certificates have to be in PEM format.
666
667 If capath is passed, it must be a directory prepared using the
668 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
669 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400671 :param cafile: In which file we can find the certificates (``bytes`` or
672 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400674 (``bytes`` or ``unicode``).
675
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800676 :return: None
677 """
678 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500679 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400680 else:
681 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682
683 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500684 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400685 else:
686 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800687
Alex Gaynor62da94d2015-09-05 14:37:34 -0400688 load_result = _lib.SSL_CTX_load_verify_locations(
689 self._context, cafile, capath
690 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500692 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694 def _wrap_callback(self, callback):
695 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800696 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400698
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800699 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400700 FILETYPE_PEM, wrapper, more_args=True, truncate=True
701 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800702
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800703 def set_passwd_cb(self, callback, userdata=None):
704 """
Alex Chand072cae2018-02-15 09:57:59 +0000705 Set the passphrase callback. This function will be called
706 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707
Alex Chand072cae2018-02-15 09:57:59 +0000708 :param callback: The Python callback to use. This must accept three
709 positional arguments. First, an integer giving the maximum length
710 of the passphrase it may return. If the returned passphrase is
711 longer than this, it will be truncated. Second, a boolean value
712 which will be true if the user should be prompted for the
713 passphrase twice and the callback should verify that the two values
714 supplied are equal. Third, the value given as the *userdata*
715 parameter to :meth:`set_passwd_cb`. The *callback* must return
716 a byte string. If an error occurs, *callback* should return a false
717 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718 :param userdata: (optional) A Python object which will be given as
719 argument to the callback
720 :return: None
721 """
722 if not callable(callback):
723 raise TypeError("callback must be callable")
724
725 self._passphrase_helper = self._wrap_callback(callback)
726 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500727 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400728 self._context, self._passphrase_callback
729 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 self._passphrase_userdata = userdata
731
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800732 def set_default_verify_paths(self):
733 """
Alex Chand072cae2018-02-15 09:57:59 +0000734 Specify that the platform provided CA certificates are to be used for
735 verification purposes. This method has some caveats related to the
736 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
737
738 * macOS will only load certificates using this method if the user has
739 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
740 in the default location.
741 * Windows will not work.
742 * manylinux1 cryptography wheels will work on most common Linux
743 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
744 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800745
746 :return: None
747 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500748 # SSL_CTX_set_default_verify_paths will attempt to load certs from
749 # both a cafile and capath that are set at compile time. However,
750 # it will first check environment variables and, if present, load
751 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500752 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400753 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500754 # After attempting to set default_verify_paths we need to know whether
755 # to go down the fallback path.
756 # First we'll check to see if any env vars have been set. If so,
757 # we won't try to do anything else because the user has set the path
758 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400759 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
760 "ascii"
761 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500762 file_env_var = _ffi.string(
763 _lib.X509_get_default_cert_file_env()
764 ).decode("ascii")
765 if not self._check_env_vars_set(dir_env_var, file_env_var):
766 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
767 default_file = _ffi.string(_lib.X509_get_default_cert_file())
768 # Now we check to see if the default_dir and default_file are set
769 # to the exact values we use in our manylinux1 builds. If they are
770 # then we know to load the fallbacks
771 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400772 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
773 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500774 ):
775 # This is manylinux1, let's load our fallback paths
776 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400777 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500778 )
779
780 def _check_env_vars_set(self, dir_env_var, file_env_var):
781 """
782 Check to see if the default cert dir/file environment vars are present.
783
784 :return: bool
785 """
786 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400787 os.environ.get(file_env_var) is not None
788 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500789 )
790
791 def _fallback_default_verify_paths(self, file_path, dir_path):
792 """
793 Default verify paths are based on the compiled version of OpenSSL.
794 However, when pyca/cryptography is compiled as a manylinux1 wheel
795 that compiled location can potentially be wrong. So, like Go, we
796 will try a predefined set of paths and attempt to load roots
797 from there.
798
799 :return: None
800 """
801 for cafile in file_path:
802 if os.path.isfile(cafile):
803 self.load_verify_locations(cafile)
804 break
805
806 for capath in dir_path:
807 if os.path.isdir(capath):
808 self.load_verify_locations(None, capath)
809 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800810
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800811 def use_certificate_chain_file(self, certfile):
812 """
Alex Chand072cae2018-02-15 09:57:59 +0000813 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400815 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000816 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400817
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 :return: None
819 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400820 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800821
Alex Gaynor62da94d2015-09-05 14:37:34 -0400822 result = _lib.SSL_CTX_use_certificate_chain_file(
823 self._context, certfile
824 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800825 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500826 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800827
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800828 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829 """
830 Load a certificate from a file
831
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400832 :param certfile: The name of the certificate file (``bytes`` or
833 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000834 :param filetype: (optional) The encoding of the file, which is either
835 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
836 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400837
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800838 :return: None
839 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400840 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500841 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800842 raise TypeError("filetype must be an integer")
843
Alex Gaynor62da94d2015-09-05 14:37:34 -0400844 use_result = _lib.SSL_CTX_use_certificate_file(
845 self._context, certfile, filetype
846 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800847 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500848 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800849
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800850 def use_certificate(self, cert):
851 """
852 Load a certificate from a X509 object
853
854 :param cert: The X509 object
855 :return: None
856 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800857 if not isinstance(cert, X509):
858 raise TypeError("cert must be an X509 instance")
859
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500860 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800861 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500862 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800863
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800864 def add_extra_chain_cert(self, certobj):
865 """
866 Add certificate to chain
867
868 :param certobj: The X509 certificate object to add to the chain
869 :return: None
870 """
871 if not isinstance(certobj, X509):
872 raise TypeError("certobj must be an X509 instance")
873
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500874 copy = _lib.X509_dup(certobj._x509)
875 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800876 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500877 # TODO: This is untested.
878 _lib.X509_free(copy)
879 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800880
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800881 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500882 if self._passphrase_helper is not None:
883 self._passphrase_helper.raise_if_problem(Error)
884
885 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800886
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400887 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800888 """
889 Load a private key from a file
890
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400891 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000892 :param filetype: (optional) The encoding of the file, which is either
893 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
894 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400895
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800896 :return: None
897 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400898 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400900 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800901 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500902 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800903 raise TypeError("filetype must be an integer")
904
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500905 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -0400906 self._context, keyfile, filetype
907 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800909 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911 def use_privatekey(self, pkey):
912 """
913 Load a private key from a PKey object
914
915 :param pkey: The PKey object
916 :return: None
917 """
918 if not isinstance(pkey, PKey):
919 raise TypeError("pkey must be a PKey instance")
920
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500921 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800923 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800924
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925 def check_privatekey(self):
926 """
Alex Chand072cae2018-02-15 09:57:59 +0000927 Check if the private key (loaded with :meth:`use_privatekey`) matches
928 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929
Alex Chand072cae2018-02-15 09:57:59 +0000930 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800931 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500932 if not _lib.SSL_CTX_check_private_key(self._context):
933 _raise_current_error()
934
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800935 def load_client_ca(self, cafile):
936 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100937 Load the trusted certificates that will be sent to the client. Does
938 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400939 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100941 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942 :return: None
943 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100944 ca_list = _lib.SSL_load_client_CA_file(
945 _text_to_bytes_and_warn("cafile", cafile)
946 )
947 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100948 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800949
950 def set_session_id(self, buf):
951 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100952 Set the session id to *buf* within which a session can be reused for
953 this Context object. This is needed when doing session resumption,
954 because there is no way for a stored session to know which Context
955 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800956
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100957 :param bytes buf: The session id.
958
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959 :returns: None
960 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100961 buf = _text_to_bytes_and_warn("buf", buf)
962 _openssl_assert(
Alex Gaynor124a0132020-10-27 00:15:17 -0400963 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf))
Alex Gaynor03737182020-07-23 20:40:46 -0400964 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100965 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966
967 def set_session_cache_mode(self, mode):
968 """
Alex Chand072cae2018-02-15 09:57:59 +0000969 Set the behavior of the session cache used by all connections using
970 this Context. The previously set mode is returned. See
971 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800972
973 :param mode: One or more of the SESS_CACHE_* flags (combine using
974 bitwise or)
975 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000976
977 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500979 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800980 raise TypeError("mode must be an integer")
981
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500982 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984 def get_session_cache_mode(self):
985 """
Alex Chand072cae2018-02-15 09:57:59 +0000986 Get the current session cache mode.
987
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800988 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +0000989
990 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500992 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800993
Maximilian Hils79b9c792020-08-08 03:08:17 +0200994 def set_verify(self, mode, callback=None):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995 """
Alex Chand072cae2018-02-15 09:57:59 +0000996 et the verification flags for this Context object to *mode* and specify
997 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800998
Alex Chand072cae2018-02-15 09:57:59 +0000999 :param mode: The verify mode, this should be one of
1000 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1001 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1002 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1003 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
Maximilian Hils79b9c792020-08-08 03:08:17 +02001004 :param callback: The optional Python verification callback to use.
1005 This should take five arguments: A Connection object, an X509
1006 object, and three integer variables, which are in turn potential
1007 error number, error depth and return code. *callback* should
1008 return True if verification passes and False otherwise.
1009 If omitted, OpenSSL's default verification is used.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010 :return: None
1011
1012 See SSL_CTX_set_verify(3SSL) for further details.
1013 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001014 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015 raise TypeError("mode must be an integer")
1016
Maximilian Hils79b9c792020-08-08 03:08:17 +02001017 if callback is None:
1018 self._verify_helper = None
1019 self._verify_callback = None
1020 _lib.SSL_CTX_set_verify(self._context, mode, _ffi.NULL)
1021 else:
1022 if not callable(callback):
1023 raise TypeError("callback must be callable")
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001024
Maximilian Hils79b9c792020-08-08 03:08:17 +02001025 self._verify_helper = _VerifyHelper(callback)
1026 self._verify_callback = self._verify_helper.callback
1027 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001029 def set_verify_depth(self, depth):
1030 """
Alex Chand072cae2018-02-15 09:57:59 +00001031 Set the maximum depth for the certificate chain verification that shall
1032 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033
1034 :param depth: An integer specifying the verify depth
1035 :return: None
1036 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001037 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038 raise TypeError("depth must be an integer")
1039
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001040 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042 def get_verify_mode(self):
1043 """
Alex Chand072cae2018-02-15 09:57:59 +00001044 Retrieve the Context object's verify mode, as set by
1045 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046
1047 :return: The verify mode
1048 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001049 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001050
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051 def get_verify_depth(self):
1052 """
Alex Chand072cae2018-02-15 09:57:59 +00001053 Retrieve the Context object's verify depth, as set by
1054 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
1056 :return: The verify depth
1057 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001058 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001059
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001060 def load_tmp_dh(self, dhfile):
1061 """
1062 Load parameters for Ephemeral Diffie-Hellman
1063
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001064 :param dhfile: The file to load EDH parameters from (``bytes`` or
1065 ``unicode``).
1066
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067 :return: None
1068 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001069 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001071 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001072 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001073 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001076 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1077 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001078 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1079 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001081 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001082 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001083 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001084
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001085 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001086 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1087 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001088
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001089 :return: None
1090 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001091 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001092
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093 def set_cipher_list(self, cipher_list):
1094 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001095 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001097 See the OpenSSL manual for more information (e.g.
1098 :manpage:`ciphers(1)`).
1099
1100 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001101 :return: None
1102 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001103 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001104
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001105 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001106 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001107
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001108 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001109 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001110 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001111 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1112 # ciphers even if you pass an invalid cipher. Applications (like
1113 # Twisted) have tests that depend on an error being raised if an
1114 # invalid cipher string is passed, but without the following check
1115 # for the TLS 1.3 specific cipher suites it would never error.
1116 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001117 if tmpconn.get_cipher_list() == [
1118 "TLS_AES_256_GCM_SHA384",
1119 "TLS_CHACHA20_POLY1305_SHA256",
1120 "TLS_AES_128_GCM_SHA256",
1121 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001122 raise Error(
1123 [
1124 (
Alex Gaynor03737182020-07-23 20:40:46 -04001125 "SSL routines",
1126 "SSL_CTX_set_cipher_list",
1127 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001128 ),
1129 ],
1130 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001132 def set_client_ca_list(self, certificate_authorities):
1133 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001134 Set the list of preferred client certificate signers for this server
1135 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001136
Alex Gaynor62da94d2015-09-05 14:37:34 -04001137 This list of certificate authorities will be sent to the client when
1138 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001139
1140 :param certificate_authorities: a sequence of X509Names.
1141 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001142
1143 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001146 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001147
1148 try:
1149 for ca_name in certificate_authorities:
1150 if not isinstance(ca_name, X509Name):
1151 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001152 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001153 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001154 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001156 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001158 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001160 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001161 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001163 raise
1164
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001166
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001167 def add_client_ca(self, certificate_authority):
1168 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001169 Add the CA certificate to the list of preferred signers for this
1170 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001171
1172 The list of certificate authorities will be sent to the client when the
1173 server requests a client certificate.
1174
1175 :param certificate_authority: certificate authority's X509 certificate.
1176 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001177
1178 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001179 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001180 if not isinstance(certificate_authority, X509):
1181 raise TypeError("certificate_authority must be an X509 instance")
1182
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001183 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001184 self._context, certificate_authority._x509
1185 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001186 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001187
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001188 def set_timeout(self, timeout):
1189 """
Alex Chand072cae2018-02-15 09:57:59 +00001190 Set the timeout for newly created sessions for this Context object to
1191 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1192 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001193
Alex Chand072cae2018-02-15 09:57:59 +00001194 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001195 :return: The previous session timeout
1196 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001197 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198 raise TypeError("timeout must be an integer")
1199
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001200 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001202 def get_timeout(self):
1203 """
Alex Chand072cae2018-02-15 09:57:59 +00001204 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1205 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001206
1207 :return: The session timeout
1208 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001209 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001210
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001211 def set_info_callback(self, callback):
1212 """
Alex Chand072cae2018-02-15 09:57:59 +00001213 Set the information callback to *callback*. This function will be
1214 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215
Alex Chand072cae2018-02-15 09:57:59 +00001216 :param callback: The Python callback to use. This should take three
1217 arguments: a Connection object and two integers. The first integer
1218 specifies where in the SSL handshake the function was called, and
1219 the other the return code from a (possibly failed) internal
1220 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001221 :return: None
1222 """
Alex Gaynor03737182020-07-23 20:40:46 -04001223
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001224 @wraps(callback)
1225 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001226 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001227
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001228 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001229 "void (*)(const SSL *, int, int)", wrapper
1230 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001231 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001232
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001233 @_requires_keylog
1234 def set_keylog_callback(self, callback):
1235 """
1236 Set the TLS key logging callback to *callback*. This function will be
1237 called whenever TLS key material is generated or received, in order
1238 to allow applications to store this keying material for debugging
1239 purposes.
1240
1241 :param callback: The Python callback to use. This should take two
1242 arguments: a Connection object and a bytestring that contains
1243 the key material in the format used by NSS for its SSLKEYLOGFILE
1244 debugging output.
1245 :return: None
1246 """
1247
1248 @wraps(callback)
1249 def wrapper(ssl, line):
1250 line = _ffi.string(line)
1251 callback(Connection._reverse_mapping[ssl], line)
1252
1253 self._keylog_callback = _ffi.callback(
1254 "void (*)(const SSL *, const char *)", wrapper
1255 )
1256 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1257
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001258 def get_app_data(self):
1259 """
Alex Chand072cae2018-02-15 09:57:59 +00001260 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001261
1262 :return: The application data
1263 """
1264 return self._app_data
1265
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001266 def set_app_data(self, data):
1267 """
1268 Set the application data (will be returned from get_app_data())
1269
1270 :param data: Any Python object
1271 :return: None
1272 """
1273 self._app_data = data
1274
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001275 def get_cert_store(self):
1276 """
Alex Chand072cae2018-02-15 09:57:59 +00001277 Get the certificate store for the context. This can be used to add
1278 "trusted" certificates without using the
1279 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001280
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001281 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001283 store = _lib.SSL_CTX_get_cert_store(self._context)
1284 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001285 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001286 return None
1287
1288 pystore = X509Store.__new__(X509Store)
1289 pystore._store = store
1290 return pystore
1291
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001292 def set_options(self, options):
1293 """
1294 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001295 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296
1297 :param options: The options to add.
1298 :return: The new option bitmask.
1299 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001300 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001301 raise TypeError("options must be an integer")
1302
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001304
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001305 def set_mode(self, mode):
1306 """
Alex Chand072cae2018-02-15 09:57:59 +00001307 Add modes via bitmask. Modes set before are not cleared! This method
1308 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309
1310 :param mode: The mode to add.
1311 :return: The new mode bitmask.
1312 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001313 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001314 raise TypeError("mode must be an integer")
1315
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001316 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001318 def set_tlsext_servername_callback(self, callback):
1319 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001320 Specify a callback function to be called when clients specify a server
1321 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001322
1323 :param callback: The callback function. It will be invoked with one
1324 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001325
1326 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001327 """
Alex Gaynor03737182020-07-23 20:40:46 -04001328
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001329 @wraps(callback)
1330 def wrapper(ssl, alert, arg):
1331 callback(Connection._reverse_mapping[ssl])
1332 return 0
1333
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001334 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001335 "int (*)(SSL *, int *, void *)", wrapper
1336 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001337 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001338 self._context, self._tlsext_servername_callback
1339 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001340
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001341 def set_tlsext_use_srtp(self, profiles):
1342 """
1343 Enable support for negotiating SRTP keying material.
1344
1345 :param bytes profiles: A colon delimited list of protection profile
1346 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1347 :return: None
1348 """
1349 if not isinstance(profiles, bytes):
1350 raise TypeError("profiles must be a byte string.")
1351
1352 _openssl_assert(
1353 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1354 )
1355
Cory Benfield7907e332015-04-13 17:18:25 -04001356 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001357 def set_alpn_protos(self, protos):
1358 """
Alex Chand072cae2018-02-15 09:57:59 +00001359 Specify the protocols that the client is prepared to speak after the
1360 TLS connection has been negotiated using Application Layer Protocol
1361 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001362
1363 :param protos: A list of the protocols to be offered to the server.
1364 This list should be a Python list of bytestrings representing the
1365 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1366 """
1367 # Take the list of protocols and join them together, prefixing them
1368 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001369 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001370 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1371 )
1372
1373 # Build a C string from the list. We don't need to save this off
1374 # because OpenSSL immediately copies the data out.
1375 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001376 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001377
Cory Benfield7907e332015-04-13 17:18:25 -04001378 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001379 def set_alpn_select_callback(self, callback):
1380 """
Alex Chand072cae2018-02-15 09:57:59 +00001381 Specify a callback function that will be called on the server when a
1382 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001383
1384 :param callback: The callback function. It will be invoked with two
1385 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001386 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1387 one of those bytestrings to indicate the chosen protocol, the
1388 empty bytestring to terminate the TLS connection, or the
1389 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1390 protocol was selected, but that the connection should not be
1391 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001392 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001393 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001394 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001395 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001396 self._context, self._alpn_select_callback, _ffi.NULL
1397 )
Cory Benfield12eae892014-06-07 15:42:56 +01001398
Cory Benfield496652a2017-01-24 11:42:56 +00001399 def _set_ocsp_callback(self, helper, data):
1400 """
1401 This internal helper does the common work for
1402 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1403 almost all of it.
1404 """
1405 self._ocsp_helper = helper
1406 self._ocsp_callback = helper.callback
1407 if data is None:
1408 self._ocsp_data = _ffi.NULL
1409 else:
1410 self._ocsp_data = _ffi.new_handle(data)
1411
1412 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1413 self._context, self._ocsp_callback
1414 )
1415 _openssl_assert(rc == 1)
1416 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1417 _openssl_assert(rc == 1)
1418
1419 def set_ocsp_server_callback(self, callback, data=None):
1420 """
1421 Set a callback to provide OCSP data to be stapled to the TLS handshake
1422 on the server side.
1423
1424 :param callback: The callback function. It will be invoked with two
1425 arguments: the Connection, and the optional arbitrary data you have
1426 provided. The callback must return a bytestring that contains the
1427 OCSP data to staple to the handshake. If no OCSP data is available
1428 for this connection, return the empty bytestring.
1429 :param data: Some opaque data that will be passed into the callback
1430 function when called. This can be used to avoid needing to do
1431 complex data lookups or to keep track of what context is being
1432 used. This parameter is optional.
1433 """
1434 helper = _OCSPServerCallbackHelper(callback)
1435 self._set_ocsp_callback(helper, data)
1436
1437 def set_ocsp_client_callback(self, callback, data=None):
1438 """
1439 Set a callback to validate OCSP data stapled to the TLS handshake on
1440 the client side.
1441
1442 :param callback: The callback function. It will be invoked with three
1443 arguments: the Connection, a bytestring containing the stapled OCSP
1444 assertion, and the optional arbitrary data you have provided. The
1445 callback must return a boolean that indicates the result of
1446 validating the OCSP data: ``True`` if the OCSP data is valid and
1447 the certificate can be trusted, or ``False`` if either the OCSP
1448 data is invalid or the certificate has been revoked.
1449 :param data: Some opaque data that will be passed into the callback
1450 function when called. This can be used to avoid needing to do
1451 complex data lookups or to keep track of what context is being
1452 used. This parameter is optional.
1453 """
1454 helper = _OCSPClientCallbackHelper(callback)
1455 self._set_ocsp_callback(helper, data)
1456
Alex Chanc6077062016-11-18 13:53:39 +00001457
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001458class Connection(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001459 _reverse_mapping = WeakValueDictionary()
1460
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001461 def __init__(self, context, socket=None):
1462 """
1463 Create a new Connection object, using the given OpenSSL.SSL.Context
1464 instance and socket.
1465
1466 :param context: An SSL Context to use for this connection
1467 :param socket: The socket to use for transport layer
1468 """
1469 if not isinstance(context, Context):
1470 raise TypeError("context must be a Context instance")
1471
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001472 ssl = _lib.SSL_new(context._context)
1473 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001474 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1475 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1476 # even though there is still data on the underlying transport.
1477 # See https://github.com/openssl/openssl/issues/6234 for more details.
1478 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001479 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001480 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001481
Cory Benfield12eae892014-06-07 15:42:56 +01001482 # References to strings used for Application Layer Protocol
1483 # Negotiation. These strings get copied at some point but it's well
1484 # after the callback returns, so we have to hang them somewhere to
1485 # avoid them getting freed.
1486 self._alpn_select_callback_args = None
1487
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001488 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001489
1490 if socket is None:
1491 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001492 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001493 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001494 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495
Alex Gaynora829e902016-06-04 18:16:01 -07001496 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1497 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001499 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001500 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001501 self._into_ssl = None
1502 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001503 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001504 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001505 self._ssl, _asFileDescriptor(self._socket)
1506 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001507 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001508
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001509 def __getattr__(self, name):
1510 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001511 Look up attributes on the wrapped socket object if they are not found
1512 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513 """
kjav0b66fa12015-09-02 11:51:26 +01001514 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001515 raise AttributeError(
1516 "'%s' object has no attribute '%s'"
1517 % (self.__class__.__name__, name)
1518 )
kjav0b66fa12015-09-02 11:51:26 +01001519 else:
1520 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001522 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001523 if self._context._verify_helper is not None:
1524 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001525 if self._context._alpn_select_helper is not None:
1526 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001527 if self._context._ocsp_helper is not None:
1528 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001529
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001530 error = _lib.SSL_get_error(ssl, result)
1531 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001532 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001533 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001534 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001535 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001536 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001537 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001538 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001539 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001540 elif error == _lib.SSL_ERROR_SYSCALL:
1541 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001543 if platform == "win32":
1544 errno = _ffi.getwinerror()[0]
1545 else:
1546 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001547
1548 if errno != 0:
1549 raise SysCallError(errno, errorcode.get(errno))
1550 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001552 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001553 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001554 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001555 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001556 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001557 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001558
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559 def get_context(self):
1560 """
Alex Chand072cae2018-02-15 09:57:59 +00001561 Retrieve the :class:`Context` object associated with this
1562 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001563 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001564 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 """
Alex Chand072cae2018-02-15 09:57:59 +00001568 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001569
Alex Chand072cae2018-02-15 09:57:59 +00001570 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 if not isinstance(context, Context):
1574 raise TypeError("context must be a Context instance")
1575
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001576 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 self._context = context
1578
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579 def get_servername(self):
1580 """
1581 Retrieve the servername extension value if provided in the client hello
1582 message, or None if there wasn't one.
1583
Alex Chand072cae2018-02-15 09:57:59 +00001584 :return: A byte string giving the server name or :data:`None`.
1585
1586 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001588 name = _lib.SSL_get_servername(
1589 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1590 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001591 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001593
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001594 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001595
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001596 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597 """
1598 Set the value of the servername extension to send in the client hello.
1599
1600 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001601
1602 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001603 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604 if not isinstance(name, bytes):
1605 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001606 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 raise TypeError("name must not contain NUL byte")
1608
1609 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001610 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001611
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 def pending(self):
1613 """
Alex Chand072cae2018-02-15 09:57:59 +00001614 Get the number of bytes that can be safely read from the SSL buffer
1615 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001616
1617 :return: The number of bytes available in the receive buffer.
1618 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001619 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001621 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001622 """
1623 Send data on the connection. NOTE: If you get one of the WantRead,
1624 WantWrite or WantX509Lookup exceptions on this, you have to call the
1625 method again with the SAME buffer.
1626
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001627 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001628 :param flags: (optional) Included for compatibility with the socket
1629 API, the value is ignored
1630 :return: The number of bytes written
1631 """
Abraham Martine82326c2015-02-04 10:18:10 +00001632 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001633 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001634
Daniel Holth079c9632019-11-17 22:45:52 -05001635 with _from_buffer(buf) as data:
1636 # check len(buf) instead of len(data) for testability
1637 if len(buf) > 2147483647:
1638 raise ValueError(
1639 "Cannot send more than 2**31-1 bytes at once."
1640 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001641
Daniel Holth079c9632019-11-17 22:45:52 -05001642 result = _lib.SSL_write(self._ssl, data, len(data))
1643 self._raise_ssl_error(self._ssl, result)
1644
1645 return result
1646
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001647 write = send
1648
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001649 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001651 Send "all" data on the connection. This calls send() repeatedly until
1652 all data is sent. If an error occurs, it's impossible to tell how much
1653 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001655 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656 :param flags: (optional) Included for compatibility with the socket
1657 API, the value is ignored
1658 :return: The number of bytes written
1659 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001660 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001661
Daniel Holth079c9632019-11-17 22:45:52 -05001662 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001663
Daniel Holth079c9632019-11-17 22:45:52 -05001664 left_to_send = len(buf)
1665 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666
Daniel Holth079c9632019-11-17 22:45:52 -05001667 while left_to_send:
1668 # SSL_write's num arg is an int,
1669 # so we cannot send more than 2**31-1 bytes at once.
1670 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001671 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001672 )
1673 self._raise_ssl_error(self._ssl, result)
1674 total_sent += result
1675 left_to_send -= result
1676
1677 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679 def recv(self, bufsiz, flags=None):
1680 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001681 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682
1683 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001684 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1685 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 :return: The string read from the Connection
1687 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001688 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001689 if flags is not None and flags & socket.MSG_PEEK:
1690 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1691 else:
1692 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001695
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 read = recv
1697
Cory Benfield62d10332014-06-15 10:03:41 +01001698 def recv_into(self, buffer, nbytes=None, flags=None):
1699 """
Alex Chand072cae2018-02-15 09:57:59 +00001700 Receive data on the connection and copy it directly into the provided
1701 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001702
1703 :param buffer: The buffer to copy into.
1704 :param nbytes: (optional) The maximum number of bytes to read into the
1705 buffer. If not present, defaults to the size of the buffer. If
1706 larger than the size of the buffer, is reduced to the size of the
1707 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001708 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1709 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001710 :return: The number of bytes read into the buffer.
1711 """
1712 if nbytes is None:
1713 nbytes = len(buffer)
1714 else:
1715 nbytes = min(nbytes, len(buffer))
1716
1717 # We need to create a temporary buffer. This is annoying, it would be
1718 # better if we could pass memoryviews straight into the SSL_read call,
1719 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001720 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001721 if flags is not None and flags & socket.MSG_PEEK:
1722 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1723 else:
1724 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001725 self._raise_ssl_error(self._ssl, result)
1726
1727 # This strange line is all to avoid a memory copy. The buffer protocol
1728 # should allow us to assign a CFFI buffer to the LHS of this line, but
1729 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001730 # wrap it in a memoryview.
1731 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001732
1733 return result
1734
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001735 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001736 if _lib.BIO_should_retry(bio):
1737 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001738 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001740 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001741 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001742 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001743 # TODO: This is untested. I think io_special means the socket
1744 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001745 raise ValueError("BIO_should_io_special")
1746 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001747 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001748 raise ValueError("unknown bio failure")
1749 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001750 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001751 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001752
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001753 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001754 """
Alex Chand072cae2018-02-15 09:57:59 +00001755 If the Connection was created with a memory BIO, this method can be
1756 used to read bytes from the write end of that memory BIO. Many
1757 Connection methods will add bytes which must be read in this manner or
1758 the buffer will eventually fill up and the Connection will be able to
1759 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001760
1761 :param bufsiz: The maximum number of bytes to read
1762 :return: The string read.
1763 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001764 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001765 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001766
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001767 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001768 raise TypeError("bufsiz must be an integer")
1769
Cory Benfielde62840e2016-11-28 12:17:08 +00001770 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001771 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001772 if result <= 0:
1773 self._handle_bio_errors(self._from_ssl, result)
1774
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001775 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001776
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001777 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001778 """
Alex Chand072cae2018-02-15 09:57:59 +00001779 If the Connection was created with a memory BIO, this method can be
1780 used to add bytes to the read end of that memory BIO. The Connection
1781 can then read the bytes (for example, in response to a call to
1782 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001783
1784 :param buf: The string to put into the memory BIO.
1785 :return: The number of bytes written
1786 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001787 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001788
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001789 if self._into_ssl is None:
1790 raise TypeError("Connection sock was not None")
1791
Daniel Holth079c9632019-11-17 22:45:52 -05001792 with _from_buffer(buf) as data:
1793 result = _lib.BIO_write(self._into_ssl, data, len(data))
1794 if result <= 0:
1795 self._handle_bio_errors(self._into_ssl, result)
1796 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001797
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001798 def renegotiate(self):
1799 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001800 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001801
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001802 :return: True if the renegotiation can be started, False otherwise
1803 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001804 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001805 if not self.renegotiate_pending():
1806 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1807 return True
1808 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809
1810 def do_handshake(self):
1811 """
Alex Chand072cae2018-02-15 09:57:59 +00001812 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001813 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001814 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001815
1816 :return: None.
1817 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001818 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001819 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001820
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001821 def renegotiate_pending(self):
1822 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001823 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001824 a renegotiation is finished.
1825
1826 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001827 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001828 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001829 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001830
1831 def total_renegotiations(self):
1832 """
1833 Find out the total number of renegotiations.
1834
1835 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001836 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001838 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001840 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001841 """
Alex Chand072cae2018-02-15 09:57:59 +00001842 Call the :meth:`connect` method of the underlying socket and set up SSL
1843 on the socket, using the :class:`Context` object supplied to this
1844 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001845
1846 :param addr: A remote address
1847 :return: What the socket's connect method returns
1848 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001849 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001850 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001851
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001852 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001853 """
Alex Chand072cae2018-02-15 09:57:59 +00001854 Call the :meth:`connect_ex` method of the underlying socket and set up
1855 SSL on the socket, using the Context object supplied to this Connection
1856 object at creation. Note that if the :meth:`connect_ex` method of the
1857 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001858
1859 :param addr: A remove address
1860 :return: What the socket's connect_ex method returns
1861 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001862 connect_ex = self._socket.connect_ex
1863 self.set_connect_state()
1864 return connect_ex(addr)
1865
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866 def accept(self):
1867 """
Alex Chand072cae2018-02-15 09:57:59 +00001868 Call the :meth:`accept` method of the underlying socket and set up SSL
1869 on the returned socket, using the Context object supplied to this
1870 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001871
Alex Chand072cae2018-02-15 09:57:59 +00001872 :return: A *(conn, addr)* pair where *conn* is the new
1873 :class:`Connection` object created, and *address* is as returned by
1874 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001876 client, addr = self._socket.accept()
1877 conn = Connection(self._context, client)
1878 conn.set_accept_state()
1879 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881 def bio_shutdown(self):
1882 """
Alex Chand072cae2018-02-15 09:57:59 +00001883 If the Connection was created with a memory BIO, this method can be
1884 used to indicate that *end of file* has been reached on the read end of
1885 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001886
1887 :return: None
1888 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001889 if self._from_ssl is None:
1890 raise TypeError("Connection sock was not None")
1891
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001892 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001893
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001894 def shutdown(self):
1895 """
Alex Chand072cae2018-02-15 09:57:59 +00001896 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001897
1898 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001899 have sent closure alerts), False otherwise (in which case you
1900 call :meth:`recv` or :meth:`send` when the connection becomes
1901 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001902 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001903 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001905 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001907 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001908 else:
1909 return False
1910
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911 def get_cipher_list(self):
1912 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001913 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001914
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001915 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916 """
1917 ciphers = []
1918 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001919 result = _lib.SSL_get_cipher_list(self._ssl, i)
1920 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001922 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923 return ciphers
1924
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001925 def get_client_ca_list(self):
1926 """
1927 Get CAs whose certificates are suggested for client authentication.
1928
Alex Chand072cae2018-02-15 09:57:59 +00001929 :return: If this is a server connection, the list of certificate
1930 authorities that will be sent or has been sent to the client, as
1931 controlled by this :class:`Connection`'s :class:`Context`.
1932
1933 If this is a client connection, the list will be empty until the
1934 connection with the server is established.
1935
1936 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001937 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001938 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1939 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001940 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001941 return []
1942
1943 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001944 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1945 name = _lib.sk_X509_NAME_value(ca_names, i)
1946 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001947 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948
1949 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001950 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001951 result.append(pyname)
1952 return result
1953
Aykee7f33452018-05-16 19:18:16 +02001954 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001955 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001956 The makefile() method is not implemented, since there is no dup
1957 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001959 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001960 """
Alex Gaynor83284952015-09-05 10:43:30 -04001961 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001962 "Cannot make file object of OpenSSL.SSL.Connection"
1963 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964
1965 def get_app_data(self):
1966 """
Alex Chand072cae2018-02-15 09:57:59 +00001967 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968
1969 :return: The application data
1970 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001971 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001972
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001973 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001974 """
1975 Set application data
1976
Alex Chand072cae2018-02-15 09:57:59 +00001977 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001978 :return: None
1979 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 self._app_data = data
1981
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982 def get_shutdown(self):
1983 """
Alex Chand072cae2018-02-15 09:57:59 +00001984 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001985
Alex Gaynor62da94d2015-09-05 14:37:34 -04001986 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1987 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001988 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001989 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001992 """
Alex Chand072cae2018-02-15 09:57:59 +00001993 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994
Alex Chand072cae2018-02-15 09:57:59 +00001995 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001996 :return: None
1997 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001998 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001999 raise TypeError("state must be an integer")
2000
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002001 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002002
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002003 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002005 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002006
2007 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002008 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002009 """
kjavc704a2e2015-09-07 12:12:27 +01002010 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011
2012 def server_random(self):
2013 """
Alex Chand072cae2018-02-15 09:57:59 +00002014 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015
2016 :return: A string representing the state
2017 """
Alex Gaynor93603062016-06-01 20:13:09 -07002018 session = _lib.SSL_get_session(self._ssl)
2019 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002020 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002021 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002022 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002023 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002024 _lib.SSL_get_server_random(self._ssl, outp, length)
2025 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002026
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027 def client_random(self):
2028 """
Alex Chand072cae2018-02-15 09:57:59 +00002029 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002030
2031 :return: A string representing the state
2032 """
Alex Gaynor93603062016-06-01 20:13:09 -07002033 session = _lib.SSL_get_session(self._ssl)
2034 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002035 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002036
2037 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002038 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002039 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002040 _lib.SSL_get_client_random(self._ssl, outp, length)
2041 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002042
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002043 def master_key(self):
2044 """
Alex Chand072cae2018-02-15 09:57:59 +00002045 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002046
2047 :return: A string representing the state
2048 """
Alex Gaynor93603062016-06-01 20:13:09 -07002049 session = _lib.SSL_get_session(self._ssl)
2050 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002052
2053 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002054 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002055 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002056 _lib.SSL_SESSION_get_master_key(session, outp, length)
2057 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002058
Paul Kehrerbdb76392017-12-01 04:54:32 +08002059 def export_keying_material(self, label, olen, context=None):
2060 """
2061 Obtain keying material for application use.
2062
Alex Chand072cae2018-02-15 09:57:59 +00002063 :param: label - a disambiguating label string as described in RFC 5705
2064 :param: olen - the length of the exported key material in bytes
2065 :param: context - a per-association context value
2066 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002067 """
2068 outp = _no_zero_allocator("unsigned char[]", olen)
2069 context_buf = _ffi.NULL
2070 context_len = 0
2071 use_context = 0
2072 if context is not None:
2073 context_buf = context
2074 context_len = len(context)
2075 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002076 success = _lib.SSL_export_keying_material(
2077 self._ssl,
2078 outp,
2079 olen,
2080 label,
2081 len(label),
2082 context_buf,
2083 context_len,
2084 use_context,
2085 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002086 _openssl_assert(success == 1)
2087 return _ffi.buffer(outp, olen)[:]
2088
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002089 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002090 """
Alex Chand072cae2018-02-15 09:57:59 +00002091 Call the :meth:`shutdown` method of the underlying socket.
2092 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002093
2094 :return: What the socket's shutdown() method returns
2095 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002096 return self._socket.shutdown(*args, **kwargs)
2097
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002098 def get_certificate(self):
2099 """
2100 Retrieve the local certificate (if any)
2101
2102 :return: The local certificate
2103 """
2104 cert = _lib.SSL_get_certificate(self._ssl)
2105 if cert != _ffi.NULL:
2106 _lib.X509_up_ref(cert)
2107 return X509._from_raw_x509_ptr(cert)
2108 return None
2109
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110 def get_peer_certificate(self):
2111 """
2112 Retrieve the other side's certificate (if any)
2113
2114 :return: The peer's certificate
2115 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002116 cert = _lib.SSL_get_peer_certificate(self._ssl)
2117 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002118 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002119 return None
2120
Shane Harvey33c54992020-08-05 16:48:51 -07002121 @staticmethod
2122 def _cert_stack_to_list(cert_stack):
2123 """
2124 Internal helper to convert a STACK_OF(X509) to a list of X509
2125 instances.
2126 """
2127 result = []
2128 for i in range(_lib.sk_X509_num(cert_stack)):
2129 cert = _lib.sk_X509_value(cert_stack, i)
2130 _openssl_assert(cert != _ffi.NULL)
2131 res = _lib.X509_up_ref(cert)
2132 _openssl_assert(res >= 1)
2133 pycert = X509._from_raw_x509_ptr(cert)
2134 result.append(pycert)
2135 return result
2136
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002137 def get_peer_cert_chain(self):
2138 """
2139 Retrieve the other side's certificate (if any)
2140
2141 :return: A list of X509 instances giving the peer's certificate chain,
2142 or None if it does not have one.
2143 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002144 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2145 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002146 return None
2147
Shane Harvey33c54992020-08-05 16:48:51 -07002148 return self._cert_stack_to_list(cert_stack)
2149
2150 def get_verified_chain(self):
2151 """
2152 Retrieve the verified certificate chain of the peer including the
2153 peer's end entity certificate. It must be called after a session has
2154 been successfully established. If peer verification was not successful
2155 the chain may be incomplete, invalid, or None.
2156
2157 :return: A list of X509 instances giving the peer's verified
2158 certificate chain, or None if it does not have one.
2159
2160 .. versionadded:: 20.0
2161 """
Alex Gaynor124a0132020-10-27 00:15:17 -04002162 # OpenSSL 1.1+
2163 cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2164 if cert_stack == _ffi.NULL:
Shane Harvey33c54992020-08-05 16:48:51 -07002165 return None
2166
Alex Gaynor124a0132020-10-27 00:15:17 -04002167 return self._cert_stack_to_list(cert_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002168
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002169 def want_read(self):
2170 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002171 Checks if more data has to be read from the transport layer to complete
2172 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002173
2174 :return: True iff more data has to be read
2175 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002176 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002177
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178 def want_write(self):
2179 """
2180 Checks if there is data to write to the transport layer to complete an
2181 operation.
2182
2183 :return: True iff there is data to write
2184 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002185 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002186
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002187 def set_accept_state(self):
2188 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002189 Set the connection to work in server mode. The handshake will be
2190 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002191
2192 :return: None
2193 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002194 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002195
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196 def set_connect_state(self):
2197 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002198 Set the connection to work in client 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_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002204
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002205 def get_session(self):
2206 """
2207 Returns the Session currently used.
2208
Alex Chand072cae2018-02-15 09:57:59 +00002209 :return: An instance of :class:`OpenSSL.SSL.Session` or
2210 :obj:`None` if no session exists.
2211
2212 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002213 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002214 session = _lib.SSL_get1_session(self._ssl)
2215 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002216 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002217
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002218 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002219 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002220 return pysession
2221
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002222 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002223 """
2224 Set the session to be used when the TLS/SSL connection is established.
2225
2226 :param session: A Session instance representing the session to use.
2227 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002228
2229 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002230 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002231 if not isinstance(session, Session):
2232 raise TypeError("session must be a Session instance")
2233
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002234 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002235 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002236
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002237 def _get_finished_message(self, function):
2238 """
Alex Chand072cae2018-02-15 09:57:59 +00002239 Helper to implement :meth:`get_finished` and
2240 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002241
Alex Chand072cae2018-02-15 09:57:59 +00002242 :param function: Either :data:`SSL_get_finished`: or
2243 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002244
Alex Chand072cae2018-02-15 09:57:59 +00002245 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002246 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002247 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002248 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002249 # The OpenSSL documentation says nothing about what might happen if the
2250 # count argument given is zero. Specifically, it doesn't say whether
2251 # the output buffer may be NULL in that case or not. Inspection of the
2252 # implementation reveals that it calls memcpy() unconditionally.
2253 # Section 7.1.4, paragraph 1 of the C standard suggests that
2254 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2255 # alone desirable) behavior (though it probably does on just about
2256 # every implementation...)
2257 #
2258 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2259 # one might expect) for the initial call so as to be safe against this
2260 # potentially undefined behavior.
2261 empty = _ffi.new("char[]", 0)
2262 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002263 if size == 0:
2264 # No Finished message so far.
2265 return None
2266
Cory Benfielde62840e2016-11-28 12:17:08 +00002267 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002268 function(self._ssl, buf, size)
2269 return _ffi.buffer(buf, size)[:]
2270
Fedor Brunner5747b932014-03-05 14:22:34 +01002271 def get_finished(self):
2272 """
Alex Chand072cae2018-02-15 09:57:59 +00002273 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002274
Alex Chand072cae2018-02-15 09:57:59 +00002275 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002276 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002277 :rtype: :class:`bytes` or :class:`NoneType`
2278
2279 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002280 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002281 return self._get_finished_message(_lib.SSL_get_finished)
2282
Fedor Brunner5747b932014-03-05 14:22:34 +01002283 def get_peer_finished(self):
2284 """
Alex Chand072cae2018-02-15 09:57:59 +00002285 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002286
Alex Chand072cae2018-02-15 09:57:59 +00002287 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002288 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002289 :rtype: :class:`bytes` or :class:`NoneType`
2290
2291 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002292 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002293 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002294
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002295 def get_cipher_name(self):
2296 """
2297 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002298
Alex Chand072cae2018-02-15 09:57:59 +00002299 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002300 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002301 :rtype: :class:`unicode` or :class:`NoneType`
2302
2303 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002304 """
2305 cipher = _lib.SSL_get_current_cipher(self._ssl)
2306 if cipher == _ffi.NULL:
2307 return None
2308 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002309 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2310 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002311
2312 def get_cipher_bits(self):
2313 """
2314 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002315
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002316 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002317 or :obj:`None` if no connection has been established.
2318 :rtype: :class:`int` or :class:`NoneType`
2319
2320 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002321 """
2322 cipher = _lib.SSL_get_current_cipher(self._ssl)
2323 if cipher == _ffi.NULL:
2324 return None
2325 else:
2326 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2327
2328 def get_cipher_version(self):
2329 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002330 Obtain the protocol version of the currently used cipher.
2331
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002332 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002333 or :obj:`None` if no connection has been established.
2334 :rtype: :class:`unicode` or :class:`NoneType`
2335
2336 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002337 """
2338 cipher = _lib.SSL_get_current_cipher(self._ssl)
2339 if cipher == _ffi.NULL:
2340 return None
2341 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002342 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002343 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002344
Jim Shaverabff1882015-05-27 09:15:55 -04002345 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002346 """
Alex Chand072cae2018-02-15 09:57:59 +00002347 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002348
2349 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002350 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002351 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002352 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002353 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002354 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002355 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002356
Jim Shaver208438c2015-05-28 09:52:38 -04002357 def get_protocol_version(self):
2358 """
Alex Chand072cae2018-02-15 09:57:59 +00002359 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002360
Alex Chand072cae2018-02-15 09:57:59 +00002361 :returns: The TLS version of the current connection. For example,
2362 it will return ``0x769`` for connections made over TLS version 1.
2363 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002364 """
2365 version = _lib.SSL_version(self._ssl)
2366 return version
2367
Cory Benfield7907e332015-04-13 17:18:25 -04002368 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002369 def set_alpn_protos(self, protos):
2370 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002371 Specify the client's ALPN protocol list.
2372
2373 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002374
2375 :param protos: A list of the protocols to be offered to the server.
2376 This list should be a Python list of bytestrings representing the
2377 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2378 """
2379 # Take the list of protocols and join them together, prefixing them
2380 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002381 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002382 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2383 )
2384
2385 # Build a C string from the list. We don't need to save this off
2386 # because OpenSSL immediately copies the data out.
2387 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002388 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002389
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002390 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002391 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002392 """
2393 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002394
2395 :returns: A bytestring of the protocol name. If no protocol has been
2396 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002397 """
Cory Benfield12eae892014-06-07 15:42:56 +01002398 data = _ffi.new("unsigned char **")
2399 data_len = _ffi.new("unsigned int *")
2400
2401 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2402
Cory Benfielde8e9c382015-04-11 17:33:48 -04002403 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002404 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002405
Cory Benfield12eae892014-06-07 15:42:56 +01002406 return _ffi.buffer(data[0], data_len[0])[:]
2407
Cory Benfield496652a2017-01-24 11:42:56 +00002408 def request_ocsp(self):
2409 """
2410 Called to request that the server sends stapled OCSP data, if
2411 available. If this is not called on the client side then the server
2412 will not send OCSP data. Should be used in conjunction with
2413 :meth:`Context.set_ocsp_client_callback`.
2414 """
2415 rc = _lib.SSL_set_tlsext_status_type(
2416 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2417 )
2418 _openssl_assert(rc == 1)
2419
Cory Benfield12eae892014-06-07 15:42:56 +01002420
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002421# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2422# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002423_lib.SSL_library_init()