blob: d809743fe832942628ce28b0ecc27250bd15a76b [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
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700149try:
150 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
151except AttributeError:
152 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800153
Alex Gaynorbf012872016-06-04 13:18:39 -0700154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
Alex Gaynorbf012872016-06-04 13:18:39 -0700179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800184
Alex Gaynorc4889812015-09-04 08:43:17 -0400185OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400204if _lib.Cryptography_HAS_SSL_ST:
205 SSL_ST_INIT = _lib.SSL_ST_INIT
206 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
207 SSL_ST_OK = _lib.SSL_ST_OK
208 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Alex Gaynor03737182020-07-23 20:40:46 -0400209 __all__.extend(
210 ["SSL_ST_INIT", "SSL_ST_BEFORE", "SSL_ST_OK", "SSL_ST_RENEGOTIATE"]
211 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800212
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500213SSL_CB_LOOP = _lib.SSL_CB_LOOP
214SSL_CB_EXIT = _lib.SSL_CB_EXIT
215SSL_CB_READ = _lib.SSL_CB_READ
216SSL_CB_WRITE = _lib.SSL_CB_WRITE
217SSL_CB_ALERT = _lib.SSL_CB_ALERT
218SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
219SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
220SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
221SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
222SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
223SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
224SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
225SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800226
Paul Kehrer55fb3412017-06-29 18:44:08 -0500227# Taken from https://golang.org/src/crypto/x509/root_linux.go
228_CERTIFICATE_FILE_LOCATIONS = [
229 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
230 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
231 "/etc/ssl/ca-bundle.pem", # OpenSUSE
232 "/etc/pki/tls/cacert.pem", # OpenELEC
233 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
234]
235
236_CERTIFICATE_PATH_LOCATIONS = [
237 "/etc/ssl/certs", # SLES10/SLES11
238]
239
Paul Kehrera92a1a72017-07-19 15:53:23 +0200240# These values are compared to output from cffi's ffi.string so they must be
241# byte strings.
242_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
243_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500244
Alex Gaynor83284952015-09-05 10:43:30 -0400245
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500246class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500247 """
248 An error occurred in an `OpenSSL.SSL` API.
249 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500250
251
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500252_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100253_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500254
255
256class WantReadError(Error):
257 pass
258
259
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500260class WantWriteError(Error):
261 pass
262
263
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500264class WantX509LookupError(Error):
265 pass
266
267
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500268class ZeroReturnError(Error):
269 pass
270
271
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500272class SysCallError(Error):
273 pass
274
275
Cory Benfield0ea76e72015-03-22 09:05:28 +0000276class _CallbackExceptionHelper(object):
277 """
278 A base class for wrapper classes that allow for intelligent exception
279 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500280
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400281 :ivar list _problems: Any exceptions that occurred while executing in a
282 context where they could not be raised in the normal way. Typically
283 this is because OpenSSL has called into some Python code and requires a
284 return value. The exceptions are saved to be raised later when it is
285 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000286 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400287
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400288 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800289 self._problems = []
290
Cory Benfield0ea76e72015-03-22 09:05:28 +0000291 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400292 """
293 Raise an exception from the OpenSSL error queue or that was previously
294 captured whe running a callback.
295 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000296 if self._problems:
297 try:
298 _raise_current_error()
299 except Error:
300 pass
301 raise self._problems.pop(0)
302
303
304class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400305 """
306 Wrap a callback such that it can be used as a certificate verification
307 callback.
308 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400309
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800310 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400311 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800312
313 @wraps(callback)
314 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800315 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
316 _lib.X509_up_ref(x509)
317 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500318 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
319 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800320
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400321 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
322 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
323 connection = Connection._reverse_mapping[ssl]
324
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400326 result = callback(
327 connection, cert, error_number, error_depth, ok
328 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800329 except Exception as e:
330 self._problems.append(e)
331 return 0
332 else:
333 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500334 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800335 return 1
336 else:
337 return 0
338
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500339 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400340 "int (*)(int, X509_STORE_CTX *)", wrapper
341 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800342
343
Mark Williams5d890a02019-11-17 19:56:26 -0800344NO_OVERLAPPING_PROTOCOLS = object()
345
346
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400347class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400348 """
349 Wrap a callback such that it can be used as an ALPN selection callback.
350 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400351
Cory Benfieldf1177e72015-04-12 09:11:49 -0400352 def __init__(self, callback):
353 _CallbackExceptionHelper.__init__(self)
354
355 @wraps(callback)
356 def wrapper(ssl, out, outlen, in_, inlen, arg):
357 try:
358 conn = Connection._reverse_mapping[ssl]
359
360 # The string passed to us is made up of multiple
361 # length-prefixed bytestrings. We need to split that into a
362 # list.
363 instr = _ffi.buffer(in_, inlen)[:]
364 protolist = []
365 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400366 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400367 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400368 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400369 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400370
371 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800372 outbytes = callback(conn, protolist)
373 any_accepted = True
374 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400375 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800376 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500377 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800378 raise TypeError(
379 "ALPN callback must return a bytestring or the "
380 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
381 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400382
383 # Save our callback arguments on the connection object to make
384 # sure that they don't get freed before OpenSSL can use them.
385 # Then, return them in the appropriate output parameters.
386 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800387 _ffi.new("unsigned char *", len(outbytes)),
388 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400389 ]
390 outlen[0] = conn._alpn_select_callback_args[0][0]
391 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800392 if not any_accepted:
393 return _lib.SSL_TLSEXT_ERR_NOACK
394 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400395 except Exception as e:
396 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800397 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400398
399 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400400 (
401 "int (*)(SSL *, unsigned char **, unsigned char *, "
402 "const unsigned char *, unsigned int, void *)"
403 ),
404 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400405 )
406
407
Cory Benfield496652a2017-01-24 11:42:56 +0000408class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
409 """
410 Wrap a callback such that it can be used as an OCSP callback for the server
411 side.
412
413 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
414 ways. For servers, that callback is expected to retrieve some OCSP data and
415 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
416 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
417 is expected to check the OCSP data, and returns a negative value on error,
418 0 if the response is not acceptable, or positive if it is. These are
419 mutually exclusive return code behaviours, and they mean that we need two
420 helpers so that we always return an appropriate error code if the user's
421 code throws an exception.
422
423 Given that we have to have two helpers anyway, these helpers are a bit more
424 helpery than most: specifically, they hide a few more of the OpenSSL
425 functions so that the user has an easier time writing these callbacks.
426
427 This helper implements the server side.
428 """
429
430 def __init__(self, callback):
431 _CallbackExceptionHelper.__init__(self)
432
433 @wraps(callback)
434 def wrapper(ssl, cdata):
435 try:
436 conn = Connection._reverse_mapping[ssl]
437
438 # Extract the data if any was provided.
439 if cdata != _ffi.NULL:
440 data = _ffi.from_handle(cdata)
441 else:
442 data = None
443
444 # Call the callback.
445 ocsp_data = callback(conn, data)
446
Alex Gaynor12576002019-11-18 00:18:50 -0500447 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000448 raise TypeError("OCSP callback must return a bytestring.")
449
450 # If the OCSP data was provided, we will pass it to OpenSSL.
451 # However, we have an early exit here: if no OCSP data was
452 # provided we will just exit out and tell OpenSSL that there
453 # is nothing to do.
454 if not ocsp_data:
455 return 3 # SSL_TLSEXT_ERR_NOACK
456
David Benjamin7ac5f272018-05-21 21:24:04 -0400457 # OpenSSL takes ownership of this data and expects it to have
458 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000459 ocsp_data_length = len(ocsp_data)
460 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
461 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
462
463 _lib.SSL_set_tlsext_status_ocsp_resp(
464 ssl, data_ptr, ocsp_data_length
465 )
466
467 return 0
468 except Exception as e:
469 self._problems.append(e)
470 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
471
472 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
473
474
475class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
476 """
477 Wrap a callback such that it can be used as an OCSP callback for the client
478 side.
479
480 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
481 ways. For servers, that callback is expected to retrieve some OCSP data and
482 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
483 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
484 is expected to check the OCSP data, and returns a negative value on error,
485 0 if the response is not acceptable, or positive if it is. These are
486 mutually exclusive return code behaviours, and they mean that we need two
487 helpers so that we always return an appropriate error code if the user's
488 code throws an exception.
489
490 Given that we have to have two helpers anyway, these helpers are a bit more
491 helpery than most: specifically, they hide a few more of the OpenSSL
492 functions so that the user has an easier time writing these callbacks.
493
494 This helper implements the client side.
495 """
496
497 def __init__(self, callback):
498 _CallbackExceptionHelper.__init__(self)
499
500 @wraps(callback)
501 def wrapper(ssl, cdata):
502 try:
503 conn = Connection._reverse_mapping[ssl]
504
505 # Extract the data if any was provided.
506 if cdata != _ffi.NULL:
507 data = _ffi.from_handle(cdata)
508 else:
509 data = None
510
511 # Get the OCSP data.
512 ocsp_ptr = _ffi.new("unsigned char **")
513 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
514 if ocsp_len < 0:
515 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400516 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000517 else:
518 # Copy the OCSP data, then pass it to the callback.
519 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
520
521 valid = callback(conn, ocsp_data, data)
522
523 # Return 1 on success or 0 on error.
524 return int(bool(valid))
525
526 except Exception as e:
527 self._problems.append(e)
528 # Return negative value if an exception is hit.
529 return -1
530
531 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
532
533
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800534def _asFileDescriptor(obj):
535 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800536 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800537 meth = getattr(obj, "fileno", None)
538 if meth is not None:
539 obj = meth()
540
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800541 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800542 fd = obj
543
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800544 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800545 raise TypeError("argument must be an int, or have a fileno() method.")
546 elif fd < 0:
547 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400548 "file descriptor cannot be a negative integer (%i)" % (fd,)
549 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800550
551 return fd
552
553
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800554def SSLeay_version(type):
555 """
556 Return a string describing the version of OpenSSL in use.
557
Alex Chand072cae2018-02-15 09:57:59 +0000558 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800559 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500560 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800561
562
Cory Benfieldef404df2016-03-29 15:32:48 +0100563def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400564 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100565 Builds a decorator that ensures that functions that rely on OpenSSL
566 functions that are not present in this build raise NotImplementedError,
567 rather than AttributeError coming out of cryptography.
568
569 :param flag: A cryptography flag that guards the functions, e.g.
570 ``Cryptography_HAS_NEXTPROTONEG``.
571 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400572 """
Alex Gaynor03737182020-07-23 20:40:46 -0400573
Cory Benfieldef404df2016-03-29 15:32:48 +0100574 def _requires_decorator(func):
575 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400576
Cory Benfieldef404df2016-03-29 15:32:48 +0100577 @wraps(func)
578 def explode(*args, **kwargs):
579 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400580
Cory Benfieldef404df2016-03-29 15:32:48 +0100581 return explode
582 else:
583 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400584
Cory Benfieldef404df2016-03-29 15:32:48 +0100585 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400586
587
Cory Benfieldef404df2016-03-29 15:32:48 +0100588_requires_alpn = _make_requires(
589 _lib.Cryptography_HAS_ALPN, "ALPN not available"
590)
Cory Benfielde6f35882016-03-29 11:21:04 +0100591
Cory Benfielde6f35882016-03-29 11:21:04 +0100592
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200593_requires_keylog = _make_requires(
594 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
595)
596
597
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800598class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000599 """
600 A class representing an SSL session. A session defines certain connection
601 parameters which may be re-used to speed up the setup of subsequent
602 connections.
603
604 .. versionadded:: 0.14
605 """
Alex Gaynor03737182020-07-23 20:40:46 -0400606
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800607 pass
608
609
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800610class Context(object):
611 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100612 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400613 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000614
615 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
616 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800617 """
Alex Gaynor03737182020-07-23 20:40:46 -0400618
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800619 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800620 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500621 SSLv3_METHOD: "SSLv3_method",
622 SSLv23_METHOD: "SSLv23_method",
623 TLSv1_METHOD: "TLSv1_method",
624 TLSv1_1_METHOD: "TLSv1_1_method",
625 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400626 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500627 _methods = dict(
628 (identifier, getattr(_lib, name))
629 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400630 if getattr(_lib, name, None) is not None
631 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800632
633 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500634 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800635 raise TypeError("method must be an integer")
636
637 try:
638 method_func = self._methods[method]
639 except KeyError:
640 raise ValueError("No such protocol")
641
642 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700643 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500645 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700646 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500647 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800648
Alex Gaynor77debda2020-04-07 13:40:59 -0400649 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
650 # auto-selected. This function was added in 1.0.2 and made a noop in
651 # 1.1.0+ (where it is set automatically).
652 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
653 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600654
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800656 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800658 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800659 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800660 self._verify_callback = None
661 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200662 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800663 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664 self._app_data = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400665 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100666 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000667 self._ocsp_helper = None
668 self._ocsp_callback = None
669 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500671 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673 def load_verify_locations(self, cafile, capath=None):
674 """
675 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000676 chain. Note that the certificates have to be in PEM format.
677
678 If capath is passed, it must be a directory prepared using the
679 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
680 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800681
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400682 :param cafile: In which file we can find the certificates (``bytes`` or
683 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400685 (``bytes`` or ``unicode``).
686
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800687 :return: None
688 """
689 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500690 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400691 else:
692 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693
694 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500695 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400696 else:
697 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800698
Alex Gaynor62da94d2015-09-05 14:37:34 -0400699 load_result = _lib.SSL_CTX_load_verify_locations(
700 self._context, cafile, capath
701 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800702 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500703 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705 def _wrap_callback(self, callback):
706 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800707 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800708 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400709
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800710 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400711 FILETYPE_PEM, wrapper, more_args=True, truncate=True
712 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714 def set_passwd_cb(self, callback, userdata=None):
715 """
Alex Chand072cae2018-02-15 09:57:59 +0000716 Set the passphrase callback. This function will be called
717 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718
Alex Chand072cae2018-02-15 09:57:59 +0000719 :param callback: The Python callback to use. This must accept three
720 positional arguments. First, an integer giving the maximum length
721 of the passphrase it may return. If the returned passphrase is
722 longer than this, it will be truncated. Second, a boolean value
723 which will be true if the user should be prompted for the
724 passphrase twice and the callback should verify that the two values
725 supplied are equal. Third, the value given as the *userdata*
726 parameter to :meth:`set_passwd_cb`. The *callback* must return
727 a byte string. If an error occurs, *callback* should return a false
728 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729 :param userdata: (optional) A Python object which will be given as
730 argument to the callback
731 :return: None
732 """
733 if not callable(callback):
734 raise TypeError("callback must be callable")
735
736 self._passphrase_helper = self._wrap_callback(callback)
737 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500738 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400739 self._context, self._passphrase_callback
740 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 self._passphrase_userdata = userdata
742
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800743 def set_default_verify_paths(self):
744 """
Alex Chand072cae2018-02-15 09:57:59 +0000745 Specify that the platform provided CA certificates are to be used for
746 verification purposes. This method has some caveats related to the
747 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
748
749 * macOS will only load certificates using this method if the user has
750 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
751 in the default location.
752 * Windows will not work.
753 * manylinux1 cryptography wheels will work on most common Linux
754 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
755 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756
757 :return: None
758 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500759 # SSL_CTX_set_default_verify_paths will attempt to load certs from
760 # both a cafile and capath that are set at compile time. However,
761 # it will first check environment variables and, if present, load
762 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500763 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400764 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500765 # After attempting to set default_verify_paths we need to know whether
766 # to go down the fallback path.
767 # First we'll check to see if any env vars have been set. If so,
768 # we won't try to do anything else because the user has set the path
769 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400770 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
771 "ascii"
772 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500773 file_env_var = _ffi.string(
774 _lib.X509_get_default_cert_file_env()
775 ).decode("ascii")
776 if not self._check_env_vars_set(dir_env_var, file_env_var):
777 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
778 default_file = _ffi.string(_lib.X509_get_default_cert_file())
779 # Now we check to see if the default_dir and default_file are set
780 # to the exact values we use in our manylinux1 builds. If they are
781 # then we know to load the fallbacks
782 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400783 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
784 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500785 ):
786 # This is manylinux1, let's load our fallback paths
787 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400788 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500789 )
790
791 def _check_env_vars_set(self, dir_env_var, file_env_var):
792 """
793 Check to see if the default cert dir/file environment vars are present.
794
795 :return: bool
796 """
797 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400798 os.environ.get(file_env_var) is not None
799 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500800 )
801
802 def _fallback_default_verify_paths(self, file_path, dir_path):
803 """
804 Default verify paths are based on the compiled version of OpenSSL.
805 However, when pyca/cryptography is compiled as a manylinux1 wheel
806 that compiled location can potentially be wrong. So, like Go, we
807 will try a predefined set of paths and attempt to load roots
808 from there.
809
810 :return: None
811 """
812 for cafile in file_path:
813 if os.path.isfile(cafile):
814 self.load_verify_locations(cafile)
815 break
816
817 for capath in dir_path:
818 if os.path.isdir(capath):
819 self.load_verify_locations(None, capath)
820 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800821
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800822 def use_certificate_chain_file(self, certfile):
823 """
Alex Chand072cae2018-02-15 09:57:59 +0000824 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400826 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000827 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400828
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829 :return: None
830 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400831 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800832
Alex Gaynor62da94d2015-09-05 14:37:34 -0400833 result = _lib.SSL_CTX_use_certificate_chain_file(
834 self._context, certfile
835 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800836 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500837 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800838
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800839 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800840 """
841 Load a certificate from a file
842
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400843 :param certfile: The name of the certificate file (``bytes`` or
844 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000845 :param filetype: (optional) The encoding of the file, which is either
846 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
847 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400848
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800849 :return: None
850 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400851 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500852 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800853 raise TypeError("filetype must be an integer")
854
Alex Gaynor62da94d2015-09-05 14:37:34 -0400855 use_result = _lib.SSL_CTX_use_certificate_file(
856 self._context, certfile, filetype
857 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800858 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500859 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800860
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800861 def use_certificate(self, cert):
862 """
863 Load a certificate from a X509 object
864
865 :param cert: The X509 object
866 :return: None
867 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800868 if not isinstance(cert, X509):
869 raise TypeError("cert must be an X509 instance")
870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500871 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800872 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500873 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800874
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800875 def add_extra_chain_cert(self, certobj):
876 """
877 Add certificate to chain
878
879 :param certobj: The X509 certificate object to add to the chain
880 :return: None
881 """
882 if not isinstance(certobj, X509):
883 raise TypeError("certobj must be an X509 instance")
884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500885 copy = _lib.X509_dup(certobj._x509)
886 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800887 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500888 # TODO: This is untested.
889 _lib.X509_free(copy)
890 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800892 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500893 if self._passphrase_helper is not None:
894 self._passphrase_helper.raise_if_problem(Error)
895
896 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800897
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400898 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899 """
900 Load a private key from a file
901
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400902 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000903 :param filetype: (optional) The encoding of the file, which is either
904 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
905 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400906
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 :return: None
908 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400909 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400911 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500913 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800914 raise TypeError("filetype must be an integer")
915
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500916 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -0400917 self._context, keyfile, filetype
918 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800920 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800921
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 def use_privatekey(self, pkey):
923 """
924 Load a private key from a PKey object
925
926 :param pkey: The PKey object
927 :return: None
928 """
929 if not isinstance(pkey, PKey):
930 raise TypeError("pkey must be a PKey instance")
931
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500932 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800933 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800934 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 def check_privatekey(self):
937 """
Alex Chand072cae2018-02-15 09:57:59 +0000938 Check if the private key (loaded with :meth:`use_privatekey`) matches
939 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940
Alex Chand072cae2018-02-15 09:57:59 +0000941 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500943 if not _lib.SSL_CTX_check_private_key(self._context):
944 _raise_current_error()
945
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946 def load_client_ca(self, cafile):
947 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100948 Load the trusted certificates that will be sent to the client. Does
949 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400950 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100952 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800953 :return: None
954 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100955 ca_list = _lib.SSL_load_client_CA_file(
956 _text_to_bytes_and_warn("cafile", cafile)
957 )
958 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100959 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960
961 def set_session_id(self, buf):
962 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100963 Set the session id to *buf* within which a session can be reused for
964 this Context object. This is needed when doing session resumption,
965 because there is no way for a stored session to know which Context
966 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100968 :param bytes buf: The session id.
969
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800970 :returns: None
971 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100972 buf = _text_to_bytes_and_warn("buf", buf)
973 _openssl_assert(
Alex Gaynor03737182020-07-23 20:40:46 -0400974 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf),)
975 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100976 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800977
978 def set_session_cache_mode(self, mode):
979 """
Alex Chand072cae2018-02-15 09:57:59 +0000980 Set the behavior of the session cache used by all connections using
981 this Context. The previously set mode is returned. See
982 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983
984 :param mode: One or more of the SESS_CACHE_* flags (combine using
985 bitwise or)
986 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000987
988 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500990 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 raise TypeError("mode must be an integer")
992
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995 def get_session_cache_mode(self):
996 """
Alex Chand072cae2018-02-15 09:57:59 +0000997 Get the current session cache mode.
998
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001000
1001 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001002 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001004
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001005 def set_verify(self, mode, callback):
1006 """
Alex Chand072cae2018-02-15 09:57:59 +00001007 et the verification flags for this Context object to *mode* and specify
1008 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009
Alex Chand072cae2018-02-15 09:57:59 +00001010 :param mode: The verify mode, this should be one of
1011 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1012 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1013 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1014 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1015 :param callback: The Python callback to use. This should take five
1016 arguments: A Connection object, an X509 object, and three integer
1017 variables, which are in turn potential error number, error depth
1018 and return code. *callback* should return True if verification
1019 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020 :return: None
1021
1022 See SSL_CTX_set_verify(3SSL) for further details.
1023 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001024 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025 raise TypeError("mode must be an integer")
1026
1027 if not callable(callback):
1028 raise TypeError("callback must be callable")
1029
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001030 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001031 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001032 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001034 def set_verify_depth(self, depth):
1035 """
Alex Chand072cae2018-02-15 09:57:59 +00001036 Set the maximum depth for the certificate chain verification that shall
1037 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038
1039 :param depth: An integer specifying the verify depth
1040 :return: None
1041 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001042 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 raise TypeError("depth must be an integer")
1044
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001045 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001047 def get_verify_mode(self):
1048 """
Alex Chand072cae2018-02-15 09:57:59 +00001049 Retrieve the Context object's verify mode, as set by
1050 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051
1052 :return: The verify mode
1053 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001054 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056 def get_verify_depth(self):
1057 """
Alex Chand072cae2018-02-15 09:57:59 +00001058 Retrieve the Context object's verify depth, as set by
1059 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001060
1061 :return: The verify depth
1062 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001063 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065 def load_tmp_dh(self, dhfile):
1066 """
1067 Load parameters for Ephemeral Diffie-Hellman
1068
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001069 :param dhfile: The file to load EDH parameters from (``bytes`` or
1070 ``unicode``).
1071
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072 :return: None
1073 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001074 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001076 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001078 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1082 dh = _ffi.gc(dh, _lib.DH_free)
1083 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001084
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001085 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001086 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001087 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001088
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001089 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001090 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1091 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001092
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001093 :return: None
1094 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001095 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001096
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001097 def set_cipher_list(self, cipher_list):
1098 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001099 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001100
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001101 See the OpenSSL manual for more information (e.g.
1102 :manpage:`ciphers(1)`).
1103
1104 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 :return: None
1106 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001107 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001108
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001109 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001110 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001111
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001112 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001113 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001114 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001115 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1116 # ciphers even if you pass an invalid cipher. Applications (like
1117 # Twisted) have tests that depend on an error being raised if an
1118 # invalid cipher string is passed, but without the following check
1119 # for the TLS 1.3 specific cipher suites it would never error.
1120 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001121 if tmpconn.get_cipher_list() == [
1122 "TLS_AES_256_GCM_SHA384",
1123 "TLS_CHACHA20_POLY1305_SHA256",
1124 "TLS_AES_128_GCM_SHA256",
1125 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001126 raise Error(
1127 [
1128 (
Alex Gaynor03737182020-07-23 20:40:46 -04001129 "SSL routines",
1130 "SSL_CTX_set_cipher_list",
1131 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001132 ),
1133 ],
1134 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001135
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001136 def set_client_ca_list(self, certificate_authorities):
1137 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001138 Set the list of preferred client certificate signers for this server
1139 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001140
Alex Gaynor62da94d2015-09-05 14:37:34 -04001141 This list of certificate authorities will be sent to the client when
1142 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143
1144 :param certificate_authorities: a sequence of X509Names.
1145 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001146
1147 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001148 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001150 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001151
1152 try:
1153 for ca_name in certificate_authorities:
1154 if not isinstance(ca_name, X509Name):
1155 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001156 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001157 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001158 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001160 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001162 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001164 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001165 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001167 raise
1168
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001171 def add_client_ca(self, certificate_authority):
1172 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001173 Add the CA certificate to the list of preferred signers for this
1174 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001175
1176 The list of certificate authorities will be sent to the client when the
1177 server requests a client certificate.
1178
1179 :param certificate_authority: certificate authority's X509 certificate.
1180 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001181
1182 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001184 if not isinstance(certificate_authority, X509):
1185 raise TypeError("certificate_authority must be an X509 instance")
1186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001187 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001188 self._context, certificate_authority._x509
1189 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001190 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001192 def set_timeout(self, timeout):
1193 """
Alex Chand072cae2018-02-15 09:57:59 +00001194 Set the timeout for newly created sessions for this Context object to
1195 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1196 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001197
Alex Chand072cae2018-02-15 09:57:59 +00001198 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001199 :return: The previous session timeout
1200 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001201 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001202 raise TypeError("timeout must be an integer")
1203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001205
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001206 def get_timeout(self):
1207 """
Alex Chand072cae2018-02-15 09:57:59 +00001208 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1209 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001210
1211 :return: The session timeout
1212 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001213 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001214
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215 def set_info_callback(self, callback):
1216 """
Alex Chand072cae2018-02-15 09:57:59 +00001217 Set the information callback to *callback*. This function will be
1218 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001219
Alex Chand072cae2018-02-15 09:57:59 +00001220 :param callback: The Python callback to use. This should take three
1221 arguments: a Connection object and two integers. The first integer
1222 specifies where in the SSL handshake the function was called, and
1223 the other the return code from a (possibly failed) internal
1224 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001225 :return: None
1226 """
Alex Gaynor03737182020-07-23 20:40:46 -04001227
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001228 @wraps(callback)
1229 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001230 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001231
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001232 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001233 "void (*)(const SSL *, int, int)", wrapper
1234 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001235 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001236
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001237 @_requires_keylog
1238 def set_keylog_callback(self, callback):
1239 """
1240 Set the TLS key logging callback to *callback*. This function will be
1241 called whenever TLS key material is generated or received, in order
1242 to allow applications to store this keying material for debugging
1243 purposes.
1244
1245 :param callback: The Python callback to use. This should take two
1246 arguments: a Connection object and a bytestring that contains
1247 the key material in the format used by NSS for its SSLKEYLOGFILE
1248 debugging output.
1249 :return: None
1250 """
1251
1252 @wraps(callback)
1253 def wrapper(ssl, line):
1254 line = _ffi.string(line)
1255 callback(Connection._reverse_mapping[ssl], line)
1256
1257 self._keylog_callback = _ffi.callback(
1258 "void (*)(const SSL *, const char *)", wrapper
1259 )
1260 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1261
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001262 def get_app_data(self):
1263 """
Alex Chand072cae2018-02-15 09:57:59 +00001264 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001265
1266 :return: The application data
1267 """
1268 return self._app_data
1269
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001270 def set_app_data(self, data):
1271 """
1272 Set the application data (will be returned from get_app_data())
1273
1274 :param data: Any Python object
1275 :return: None
1276 """
1277 self._app_data = data
1278
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001279 def get_cert_store(self):
1280 """
Alex Chand072cae2018-02-15 09:57:59 +00001281 Get the certificate store for the context. This can be used to add
1282 "trusted" certificates without using the
1283 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001284
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001285 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001286 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 store = _lib.SSL_CTX_get_cert_store(self._context)
1288 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001289 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001290 return None
1291
1292 pystore = X509Store.__new__(X509Store)
1293 pystore._store = store
1294 return pystore
1295
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296 def set_options(self, options):
1297 """
1298 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001299 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001300
1301 :param options: The options to add.
1302 :return: The new option bitmask.
1303 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001304 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001305 raise TypeError("options must be an integer")
1306
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001307 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001308
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309 def set_mode(self, mode):
1310 """
Alex Chand072cae2018-02-15 09:57:59 +00001311 Add modes via bitmask. Modes set before are not cleared! This method
1312 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001313
1314 :param mode: The mode to add.
1315 :return: The new mode bitmask.
1316 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001317 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001318 raise TypeError("mode must be an integer")
1319
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001322 def set_tlsext_servername_callback(self, callback):
1323 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001324 Specify a callback function to be called when clients specify a server
1325 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001326
1327 :param callback: The callback function. It will be invoked with one
1328 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001329
1330 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001331 """
Alex Gaynor03737182020-07-23 20:40:46 -04001332
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001333 @wraps(callback)
1334 def wrapper(ssl, alert, arg):
1335 callback(Connection._reverse_mapping[ssl])
1336 return 0
1337
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001338 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001339 "int (*)(SSL *, int *, void *)", wrapper
1340 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001341 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001342 self._context, self._tlsext_servername_callback
1343 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001344
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001345 def set_tlsext_use_srtp(self, profiles):
1346 """
1347 Enable support for negotiating SRTP keying material.
1348
1349 :param bytes profiles: A colon delimited list of protection profile
1350 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1351 :return: None
1352 """
1353 if not isinstance(profiles, bytes):
1354 raise TypeError("profiles must be a byte string.")
1355
1356 _openssl_assert(
1357 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1358 )
1359
Cory Benfield7907e332015-04-13 17:18:25 -04001360 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001361 def set_alpn_protos(self, protos):
1362 """
Alex Chand072cae2018-02-15 09:57:59 +00001363 Specify the protocols that the client is prepared to speak after the
1364 TLS connection has been negotiated using Application Layer Protocol
1365 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001366
1367 :param protos: A list of the protocols to be offered to the server.
1368 This list should be a Python list of bytestrings representing the
1369 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1370 """
1371 # Take the list of protocols and join them together, prefixing them
1372 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001373 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001374 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1375 )
1376
1377 # Build a C string from the list. We don't need to save this off
1378 # because OpenSSL immediately copies the data out.
1379 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001380 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001381
Cory Benfield7907e332015-04-13 17:18:25 -04001382 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001383 def set_alpn_select_callback(self, callback):
1384 """
Alex Chand072cae2018-02-15 09:57:59 +00001385 Specify a callback function that will be called on the server when a
1386 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001387
1388 :param callback: The callback function. It will be invoked with two
1389 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001390 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1391 one of those bytestrings to indicate the chosen protocol, the
1392 empty bytestring to terminate the TLS connection, or the
1393 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1394 protocol was selected, but that the connection should not be
1395 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001396 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001397 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001398 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001399 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001400 self._context, self._alpn_select_callback, _ffi.NULL
1401 )
Cory Benfield12eae892014-06-07 15:42:56 +01001402
Cory Benfield496652a2017-01-24 11:42:56 +00001403 def _set_ocsp_callback(self, helper, data):
1404 """
1405 This internal helper does the common work for
1406 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1407 almost all of it.
1408 """
1409 self._ocsp_helper = helper
1410 self._ocsp_callback = helper.callback
1411 if data is None:
1412 self._ocsp_data = _ffi.NULL
1413 else:
1414 self._ocsp_data = _ffi.new_handle(data)
1415
1416 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1417 self._context, self._ocsp_callback
1418 )
1419 _openssl_assert(rc == 1)
1420 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1421 _openssl_assert(rc == 1)
1422
1423 def set_ocsp_server_callback(self, callback, data=None):
1424 """
1425 Set a callback to provide OCSP data to be stapled to the TLS handshake
1426 on the server side.
1427
1428 :param callback: The callback function. It will be invoked with two
1429 arguments: the Connection, and the optional arbitrary data you have
1430 provided. The callback must return a bytestring that contains the
1431 OCSP data to staple to the handshake. If no OCSP data is available
1432 for this connection, return the empty bytestring.
1433 :param data: Some opaque data that will be passed into the callback
1434 function when called. This can be used to avoid needing to do
1435 complex data lookups or to keep track of what context is being
1436 used. This parameter is optional.
1437 """
1438 helper = _OCSPServerCallbackHelper(callback)
1439 self._set_ocsp_callback(helper, data)
1440
1441 def set_ocsp_client_callback(self, callback, data=None):
1442 """
1443 Set a callback to validate OCSP data stapled to the TLS handshake on
1444 the client side.
1445
1446 :param callback: The callback function. It will be invoked with three
1447 arguments: the Connection, a bytestring containing the stapled OCSP
1448 assertion, and the optional arbitrary data you have provided. The
1449 callback must return a boolean that indicates the result of
1450 validating the OCSP data: ``True`` if the OCSP data is valid and
1451 the certificate can be trusted, or ``False`` if either the OCSP
1452 data is invalid or the certificate has been revoked.
1453 :param data: Some opaque data that will be passed into the callback
1454 function when called. This can be used to avoid needing to do
1455 complex data lookups or to keep track of what context is being
1456 used. This parameter is optional.
1457 """
1458 helper = _OCSPClientCallbackHelper(callback)
1459 self._set_ocsp_callback(helper, data)
1460
Alex Chanc6077062016-11-18 13:53:39 +00001461
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001462class Connection(object):
1463 """
1464 """
Alex Gaynor03737182020-07-23 20:40:46 -04001465
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 _reverse_mapping = WeakValueDictionary()
1467
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001468 def __init__(self, context, socket=None):
1469 """
1470 Create a new Connection object, using the given OpenSSL.SSL.Context
1471 instance and socket.
1472
1473 :param context: An SSL Context to use for this connection
1474 :param socket: The socket to use for transport layer
1475 """
1476 if not isinstance(context, Context):
1477 raise TypeError("context must be a Context instance")
1478
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001479 ssl = _lib.SSL_new(context._context)
1480 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001481 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1482 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1483 # even though there is still data on the underlying transport.
1484 # See https://github.com/openssl/openssl/issues/6234 for more details.
1485 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001486 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001487 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001488
Cory Benfield12eae892014-06-07 15:42:56 +01001489 # References to strings used for Application Layer Protocol
1490 # Negotiation. These strings get copied at some point but it's well
1491 # after the callback returns, so we have to hang them somewhere to
1492 # avoid them getting freed.
1493 self._alpn_select_callback_args = None
1494
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001495 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001496
1497 if socket is None:
1498 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001499 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001500 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001501 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001502
Alex Gaynora829e902016-06-04 18:16:01 -07001503 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1504 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001505
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001506 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001508 self._into_ssl = None
1509 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001511 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001512 self._ssl, _asFileDescriptor(self._socket)
1513 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001514 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001515
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516 def __getattr__(self, name):
1517 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001518 Look up attributes on the wrapped socket object if they are not found
1519 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001520 """
kjav0b66fa12015-09-02 11:51:26 +01001521 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001522 raise AttributeError(
1523 "'%s' object has no attribute '%s'"
1524 % (self.__class__.__name__, name)
1525 )
kjav0b66fa12015-09-02 11:51:26 +01001526 else:
1527 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001528
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001529 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001530 if self._context._verify_helper is not None:
1531 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001532 if self._context._alpn_select_helper is not None:
1533 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001534 if self._context._ocsp_helper is not None:
1535 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001536
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001537 error = _lib.SSL_get_error(ssl, result)
1538 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001539 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001540 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001541 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001543 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001544 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001545 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001546 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001547 elif error == _lib.SSL_ERROR_SYSCALL:
1548 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001549 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001550 if platform == "win32":
1551 errno = _ffi.getwinerror()[0]
1552 else:
1553 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001554
1555 if errno != 0:
1556 raise SysCallError(errno, errorcode.get(errno))
1557 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001558 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001559 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001560 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001561 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001562 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001563 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001564 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001566 def get_context(self):
1567 """
Alex Chand072cae2018-02-15 09:57:59 +00001568 Retrieve the :class:`Context` object associated with this
1569 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001570 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574 """
Alex Chand072cae2018-02-15 09:57:59 +00001575 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576
Alex Chand072cae2018-02-15 09:57:59 +00001577 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001578 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 if not isinstance(context, Context):
1581 raise TypeError("context must be a Context instance")
1582
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001583 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 self._context = context
1585
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001586 def get_servername(self):
1587 """
1588 Retrieve the servername extension value if provided in the client hello
1589 message, or None if there wasn't one.
1590
Alex Chand072cae2018-02-15 09:57:59 +00001591 :return: A byte string giving the server name or :data:`None`.
1592
1593 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001595 name = _lib.SSL_get_servername(
1596 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1597 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001598 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001599 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001600
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001601 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001602
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001603 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001604 """
1605 Set the value of the servername extension to send in the client hello.
1606
1607 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001608
1609 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001611 if not isinstance(name, bytes):
1612 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001613 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001614 raise TypeError("name must not contain NUL byte")
1615
1616 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001617 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001618
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001619 def pending(self):
1620 """
Alex Chand072cae2018-02-15 09:57:59 +00001621 Get the number of bytes that can be safely read from the SSL buffer
1622 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001623
1624 :return: The number of bytes available in the receive buffer.
1625 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001626 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001627
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001628 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629 """
1630 Send data on the connection. NOTE: If you get one of the WantRead,
1631 WantWrite or WantX509Lookup exceptions on this, you have to call the
1632 method again with the SAME buffer.
1633
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001634 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635 :param flags: (optional) Included for compatibility with the socket
1636 API, the value is ignored
1637 :return: The number of bytes written
1638 """
Abraham Martine82326c2015-02-04 10:18:10 +00001639 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001640 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001641
Daniel Holth079c9632019-11-17 22:45:52 -05001642 with _from_buffer(buf) as data:
1643 # check len(buf) instead of len(data) for testability
1644 if len(buf) > 2147483647:
1645 raise ValueError(
1646 "Cannot send more than 2**31-1 bytes at once."
1647 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001648
Daniel Holth079c9632019-11-17 22:45:52 -05001649 result = _lib.SSL_write(self._ssl, data, len(data))
1650 self._raise_ssl_error(self._ssl, result)
1651
1652 return result
1653
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654 write = send
1655
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001657 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658 Send "all" data on the connection. This calls send() repeatedly until
1659 all data is sent. If an error occurs, it's impossible to tell how much
1660 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001662 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663 :param flags: (optional) Included for compatibility with the socket
1664 API, the value is ignored
1665 :return: The number of bytes written
1666 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001667 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001668
Daniel Holth079c9632019-11-17 22:45:52 -05001669 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670
Daniel Holth079c9632019-11-17 22:45:52 -05001671 left_to_send = len(buf)
1672 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001673
Daniel Holth079c9632019-11-17 22:45:52 -05001674 while left_to_send:
1675 # SSL_write's num arg is an int,
1676 # so we cannot send more than 2**31-1 bytes at once.
1677 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001678 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001679 )
1680 self._raise_ssl_error(self._ssl, result)
1681 total_sent += result
1682 left_to_send -= result
1683
1684 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001685
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 def recv(self, bufsiz, flags=None):
1687 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001688 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001689
1690 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001691 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1692 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001693 :return: The string read from the Connection
1694 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001695 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001696 if flags is not None and flags & socket.MSG_PEEK:
1697 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1698 else:
1699 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001700 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001701 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001702
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001703 read = recv
1704
Cory Benfield62d10332014-06-15 10:03:41 +01001705 def recv_into(self, buffer, nbytes=None, flags=None):
1706 """
Alex Chand072cae2018-02-15 09:57:59 +00001707 Receive data on the connection and copy it directly into the provided
1708 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001709
1710 :param buffer: The buffer to copy into.
1711 :param nbytes: (optional) The maximum number of bytes to read into the
1712 buffer. If not present, defaults to the size of the buffer. If
1713 larger than the size of the buffer, is reduced to the size of the
1714 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001715 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1716 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001717 :return: The number of bytes read into the buffer.
1718 """
1719 if nbytes is None:
1720 nbytes = len(buffer)
1721 else:
1722 nbytes = min(nbytes, len(buffer))
1723
1724 # We need to create a temporary buffer. This is annoying, it would be
1725 # better if we could pass memoryviews straight into the SSL_read call,
1726 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001727 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001728 if flags is not None and flags & socket.MSG_PEEK:
1729 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1730 else:
1731 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001732 self._raise_ssl_error(self._ssl, result)
1733
1734 # This strange line is all to avoid a memory copy. The buffer protocol
1735 # should allow us to assign a CFFI buffer to the LHS of this line, but
1736 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001737 # wrap it in a memoryview.
1738 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001739
1740 return result
1741
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001743 if _lib.BIO_should_retry(bio):
1744 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001746 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001747 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001748 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001749 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001750 # TODO: This is untested. I think io_special means the socket
1751 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001752 raise ValueError("BIO_should_io_special")
1753 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001754 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001755 raise ValueError("unknown bio failure")
1756 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001757 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001758 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001759
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001760 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001761 """
Alex Chand072cae2018-02-15 09:57:59 +00001762 If the Connection was created with a memory BIO, this method can be
1763 used to read bytes from the write end of that memory BIO. Many
1764 Connection methods will add bytes which must be read in this manner or
1765 the buffer will eventually fill up and the Connection will be able to
1766 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001767
1768 :param bufsiz: The maximum number of bytes to read
1769 :return: The string read.
1770 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001771 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001772 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001773
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001774 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001775 raise TypeError("bufsiz must be an integer")
1776
Cory Benfielde62840e2016-11-28 12:17:08 +00001777 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001778 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001779 if result <= 0:
1780 self._handle_bio_errors(self._from_ssl, result)
1781
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001782 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001783
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001784 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001785 """
Alex Chand072cae2018-02-15 09:57:59 +00001786 If the Connection was created with a memory BIO, this method can be
1787 used to add bytes to the read end of that memory BIO. The Connection
1788 can then read the bytes (for example, in response to a call to
1789 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001790
1791 :param buf: The string to put into the memory BIO.
1792 :return: The number of bytes written
1793 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001794 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001795
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001796 if self._into_ssl is None:
1797 raise TypeError("Connection sock was not None")
1798
Daniel Holth079c9632019-11-17 22:45:52 -05001799 with _from_buffer(buf) as data:
1800 result = _lib.BIO_write(self._into_ssl, data, len(data))
1801 if result <= 0:
1802 self._handle_bio_errors(self._into_ssl, result)
1803 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001804
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001805 def renegotiate(self):
1806 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001807 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001808
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001809 :return: True if the renegotiation can be started, False otherwise
1810 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001811 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001812 if not self.renegotiate_pending():
1813 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1814 return True
1815 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816
1817 def do_handshake(self):
1818 """
Alex Chand072cae2018-02-15 09:57:59 +00001819 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001820 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001821 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001822
1823 :return: None.
1824 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001825 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001826 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001827
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001828 def renegotiate_pending(self):
1829 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001830 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001831 a renegotiation is finished.
1832
1833 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001834 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001835 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001836 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837
1838 def total_renegotiations(self):
1839 """
1840 Find out the total number of renegotiations.
1841
1842 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001843 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001844 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001845 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001846
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001847 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848 """
Alex Chand072cae2018-02-15 09:57:59 +00001849 Call the :meth:`connect` method of the underlying socket and set up SSL
1850 on the socket, using the :class:`Context` object supplied to this
1851 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001852
1853 :param addr: A remote address
1854 :return: What the socket's connect method returns
1855 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001856 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001857 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001858
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001859 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860 """
Alex Chand072cae2018-02-15 09:57:59 +00001861 Call the :meth:`connect_ex` method of the underlying socket and set up
1862 SSL on the socket, using the Context object supplied to this Connection
1863 object at creation. Note that if the :meth:`connect_ex` method of the
1864 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001865
1866 :param addr: A remove address
1867 :return: What the socket's connect_ex method returns
1868 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001869 connect_ex = self._socket.connect_ex
1870 self.set_connect_state()
1871 return connect_ex(addr)
1872
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001873 def accept(self):
1874 """
Alex Chand072cae2018-02-15 09:57:59 +00001875 Call the :meth:`accept` method of the underlying socket and set up SSL
1876 on the returned socket, using the Context object supplied to this
1877 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001878
Alex Chand072cae2018-02-15 09:57:59 +00001879 :return: A *(conn, addr)* pair where *conn* is the new
1880 :class:`Connection` object created, and *address* is as returned by
1881 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001882 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001883 client, addr = self._socket.accept()
1884 conn = Connection(self._context, client)
1885 conn.set_accept_state()
1886 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001887
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001888 def bio_shutdown(self):
1889 """
Alex Chand072cae2018-02-15 09:57:59 +00001890 If the Connection was created with a memory BIO, this method can be
1891 used to indicate that *end of file* has been reached on the read end of
1892 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001893
1894 :return: None
1895 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001896 if self._from_ssl is None:
1897 raise TypeError("Connection sock was not None")
1898
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001899 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001900
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001901 def shutdown(self):
1902 """
Alex Chand072cae2018-02-15 09:57:59 +00001903 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904
1905 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001906 have sent closure alerts), False otherwise (in which case you
1907 call :meth:`recv` or :meth:`send` when the connection becomes
1908 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001909 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001910 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001912 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001914 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915 else:
1916 return False
1917
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001918 def get_cipher_list(self):
1919 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001920 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001922 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923 """
1924 ciphers = []
1925 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001926 result = _lib.SSL_get_cipher_list(self._ssl, i)
1927 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001928 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001929 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930 return ciphers
1931
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932 def get_client_ca_list(self):
1933 """
1934 Get CAs whose certificates are suggested for client authentication.
1935
Alex Chand072cae2018-02-15 09:57:59 +00001936 :return: If this is a server connection, the list of certificate
1937 authorities that will be sent or has been sent to the client, as
1938 controlled by this :class:`Connection`'s :class:`Context`.
1939
1940 If this is a client connection, the list will be empty until the
1941 connection with the server is established.
1942
1943 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001944 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001945 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1946 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001947 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948 return []
1949
1950 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001951 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1952 name = _lib.sk_X509_NAME_value(ca_names, i)
1953 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001954 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001955
1956 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001957 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001958 result.append(pyname)
1959 return result
1960
Aykee7f33452018-05-16 19:18:16 +02001961 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001963 The makefile() method is not implemented, since there is no dup
1964 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001965
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001966 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001967 """
Alex Gaynor83284952015-09-05 10:43:30 -04001968 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001969 "Cannot make file object of OpenSSL.SSL.Connection"
1970 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001971
1972 def get_app_data(self):
1973 """
Alex Chand072cae2018-02-15 09:57:59 +00001974 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001975
1976 :return: The application data
1977 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001978 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001979
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001981 """
1982 Set application data
1983
Alex Chand072cae2018-02-15 09:57:59 +00001984 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001985 :return: None
1986 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001987 self._app_data = data
1988
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989 def get_shutdown(self):
1990 """
Alex Chand072cae2018-02-15 09:57:59 +00001991 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001992
Alex Gaynor62da94d2015-09-05 14:37:34 -04001993 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1994 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001995 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001996 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001998 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999 """
Alex Chand072cae2018-02-15 09:57:59 +00002000 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001
Alex Chand072cae2018-02-15 09:57:59 +00002002 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003 :return: None
2004 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002005 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 raise TypeError("state must be an integer")
2007
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002008 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002010 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002012 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013
2014 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002015 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016 """
kjavc704a2e2015-09-07 12:12:27 +01002017 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018
2019 def server_random(self):
2020 """
Alex Chand072cae2018-02-15 09:57:59 +00002021 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002022
2023 :return: A string representing the state
2024 """
Alex Gaynor93603062016-06-01 20:13:09 -07002025 session = _lib.SSL_get_session(self._ssl)
2026 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002027 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002028 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002029 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002030 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002031 _lib.SSL_get_server_random(self._ssl, outp, length)
2032 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002033
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002034 def client_random(self):
2035 """
Alex Chand072cae2018-02-15 09:57:59 +00002036 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002037
2038 :return: A string representing the state
2039 """
Alex Gaynor93603062016-06-01 20:13:09 -07002040 session = _lib.SSL_get_session(self._ssl)
2041 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002042 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002043
2044 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002045 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002046 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002047 _lib.SSL_get_client_random(self._ssl, outp, length)
2048 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002049
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002050 def master_key(self):
2051 """
Alex Chand072cae2018-02-15 09:57:59 +00002052 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002053
2054 :return: A string representing the state
2055 """
Alex Gaynor93603062016-06-01 20:13:09 -07002056 session = _lib.SSL_get_session(self._ssl)
2057 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002058 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002059
2060 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002061 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002062 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002063 _lib.SSL_SESSION_get_master_key(session, outp, length)
2064 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002065
Paul Kehrerbdb76392017-12-01 04:54:32 +08002066 def export_keying_material(self, label, olen, context=None):
2067 """
2068 Obtain keying material for application use.
2069
Alex Chand072cae2018-02-15 09:57:59 +00002070 :param: label - a disambiguating label string as described in RFC 5705
2071 :param: olen - the length of the exported key material in bytes
2072 :param: context - a per-association context value
2073 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002074 """
2075 outp = _no_zero_allocator("unsigned char[]", olen)
2076 context_buf = _ffi.NULL
2077 context_len = 0
2078 use_context = 0
2079 if context is not None:
2080 context_buf = context
2081 context_len = len(context)
2082 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002083 success = _lib.SSL_export_keying_material(
2084 self._ssl,
2085 outp,
2086 olen,
2087 label,
2088 len(label),
2089 context_buf,
2090 context_len,
2091 use_context,
2092 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002093 _openssl_assert(success == 1)
2094 return _ffi.buffer(outp, olen)[:]
2095
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002096 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002097 """
Alex Chand072cae2018-02-15 09:57:59 +00002098 Call the :meth:`shutdown` method of the underlying socket.
2099 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002100
2101 :return: What the socket's shutdown() method returns
2102 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002103 return self._socket.shutdown(*args, **kwargs)
2104
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002105 def get_certificate(self):
2106 """
2107 Retrieve the local certificate (if any)
2108
2109 :return: The local certificate
2110 """
2111 cert = _lib.SSL_get_certificate(self._ssl)
2112 if cert != _ffi.NULL:
2113 _lib.X509_up_ref(cert)
2114 return X509._from_raw_x509_ptr(cert)
2115 return None
2116
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002117 def get_peer_certificate(self):
2118 """
2119 Retrieve the other side's certificate (if any)
2120
2121 :return: The peer's certificate
2122 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002123 cert = _lib.SSL_get_peer_certificate(self._ssl)
2124 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002125 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002126 return None
2127
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002128 def get_peer_cert_chain(self):
2129 """
2130 Retrieve the other side's certificate (if any)
2131
2132 :return: A list of X509 instances giving the peer's certificate chain,
2133 or None if it does not have one.
2134 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002135 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2136 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002137 return None
2138
2139 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002140 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002141 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002142 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002143 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002144 result.append(pycert)
2145 return result
2146
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002147 def want_read(self):
2148 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002149 Checks if more data has to be read from the transport layer to complete
2150 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002151
2152 :return: True iff more data has to be read
2153 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002154 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002155
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002156 def want_write(self):
2157 """
2158 Checks if there is data to write to the transport layer to complete an
2159 operation.
2160
2161 :return: True iff there is data to write
2162 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002163 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002164
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002165 def set_accept_state(self):
2166 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002167 Set the connection to work in server mode. The handshake will be
2168 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002169
2170 :return: None
2171 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002172 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002173
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002174 def set_connect_state(self):
2175 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002176 Set the connection to work in client mode. The handshake will be
2177 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178
2179 :return: None
2180 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002181 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002182
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002183 def get_session(self):
2184 """
2185 Returns the Session currently used.
2186
Alex Chand072cae2018-02-15 09:57:59 +00002187 :return: An instance of :class:`OpenSSL.SSL.Session` or
2188 :obj:`None` if no session exists.
2189
2190 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002191 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002192 session = _lib.SSL_get1_session(self._ssl)
2193 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002194 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002195
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002196 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002197 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002198 return pysession
2199
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002200 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002201 """
2202 Set the session to be used when the TLS/SSL connection is established.
2203
2204 :param session: A Session instance representing the session to use.
2205 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002206
2207 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002208 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002209 if not isinstance(session, Session):
2210 raise TypeError("session must be a Session instance")
2211
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002212 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002213 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002214
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002215 def _get_finished_message(self, function):
2216 """
Alex Chand072cae2018-02-15 09:57:59 +00002217 Helper to implement :meth:`get_finished` and
2218 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002219
Alex Chand072cae2018-02-15 09:57:59 +00002220 :param function: Either :data:`SSL_get_finished`: or
2221 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002222
Alex Chand072cae2018-02-15 09:57:59 +00002223 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002224 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002225 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002226 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002227 # The OpenSSL documentation says nothing about what might happen if the
2228 # count argument given is zero. Specifically, it doesn't say whether
2229 # the output buffer may be NULL in that case or not. Inspection of the
2230 # implementation reveals that it calls memcpy() unconditionally.
2231 # Section 7.1.4, paragraph 1 of the C standard suggests that
2232 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2233 # alone desirable) behavior (though it probably does on just about
2234 # every implementation...)
2235 #
2236 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2237 # one might expect) for the initial call so as to be safe against this
2238 # potentially undefined behavior.
2239 empty = _ffi.new("char[]", 0)
2240 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002241 if size == 0:
2242 # No Finished message so far.
2243 return None
2244
Cory Benfielde62840e2016-11-28 12:17:08 +00002245 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002246 function(self._ssl, buf, size)
2247 return _ffi.buffer(buf, size)[:]
2248
Fedor Brunner5747b932014-03-05 14:22:34 +01002249 def get_finished(self):
2250 """
Alex Chand072cae2018-02-15 09:57:59 +00002251 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002252
Alex Chand072cae2018-02-15 09:57:59 +00002253 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002254 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002255 :rtype: :class:`bytes` or :class:`NoneType`
2256
2257 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002258 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002259 return self._get_finished_message(_lib.SSL_get_finished)
2260
Fedor Brunner5747b932014-03-05 14:22:34 +01002261 def get_peer_finished(self):
2262 """
Alex Chand072cae2018-02-15 09:57:59 +00002263 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002264
Alex Chand072cae2018-02-15 09:57:59 +00002265 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002266 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002267 :rtype: :class:`bytes` or :class:`NoneType`
2268
2269 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002270 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002271 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002272
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002273 def get_cipher_name(self):
2274 """
2275 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002276
Alex Chand072cae2018-02-15 09:57:59 +00002277 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002278 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002279 :rtype: :class:`unicode` or :class:`NoneType`
2280
2281 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002282 """
2283 cipher = _lib.SSL_get_current_cipher(self._ssl)
2284 if cipher == _ffi.NULL:
2285 return None
2286 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002287 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2288 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002289
2290 def get_cipher_bits(self):
2291 """
2292 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002293
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002294 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002295 or :obj:`None` if no connection has been established.
2296 :rtype: :class:`int` or :class:`NoneType`
2297
2298 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002299 """
2300 cipher = _lib.SSL_get_current_cipher(self._ssl)
2301 if cipher == _ffi.NULL:
2302 return None
2303 else:
2304 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2305
2306 def get_cipher_version(self):
2307 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002308 Obtain the protocol version of the currently used cipher.
2309
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002310 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002311 or :obj:`None` if no connection has been established.
2312 :rtype: :class:`unicode` or :class:`NoneType`
2313
2314 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002315 """
2316 cipher = _lib.SSL_get_current_cipher(self._ssl)
2317 if cipher == _ffi.NULL:
2318 return None
2319 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002320 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002321 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002322
Jim Shaverabff1882015-05-27 09:15:55 -04002323 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002324 """
Alex Chand072cae2018-02-15 09:57:59 +00002325 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002326
2327 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002328 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002329 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002330 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002331 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002332 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002333 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002334
Jim Shaver208438c2015-05-28 09:52:38 -04002335 def get_protocol_version(self):
2336 """
Alex Chand072cae2018-02-15 09:57:59 +00002337 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002338
Alex Chand072cae2018-02-15 09:57:59 +00002339 :returns: The TLS version of the current connection. For example,
2340 it will return ``0x769`` for connections made over TLS version 1.
2341 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002342 """
2343 version = _lib.SSL_version(self._ssl)
2344 return version
2345
Cory Benfield7907e332015-04-13 17:18:25 -04002346 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002347 def set_alpn_protos(self, protos):
2348 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002349 Specify the client's ALPN protocol list.
2350
2351 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002352
2353 :param protos: A list of the protocols to be offered to the server.
2354 This list should be a Python list of bytestrings representing the
2355 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2356 """
2357 # Take the list of protocols and join them together, prefixing them
2358 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002359 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002360 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2361 )
2362
2363 # Build a C string from the list. We don't need to save this off
2364 # because OpenSSL immediately copies the data out.
2365 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002366 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002367
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002368 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002369 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002370 """
2371 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002372
2373 :returns: A bytestring of the protocol name. If no protocol has been
2374 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002375 """
Cory Benfield12eae892014-06-07 15:42:56 +01002376 data = _ffi.new("unsigned char **")
2377 data_len = _ffi.new("unsigned int *")
2378
2379 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2380
Cory Benfielde8e9c382015-04-11 17:33:48 -04002381 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002382 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002383
Cory Benfield12eae892014-06-07 15:42:56 +01002384 return _ffi.buffer(data[0], data_len[0])[:]
2385
Cory Benfield496652a2017-01-24 11:42:56 +00002386 def request_ocsp(self):
2387 """
2388 Called to request that the server sends stapled OCSP data, if
2389 available. If this is not called on the client side then the server
2390 will not send OCSP data. Should be used in conjunction with
2391 :meth:`Context.set_ocsp_client_callback`.
2392 """
2393 rc = _lib.SSL_set_tlsext_status_type(
2394 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2395 )
2396 _openssl_assert(rc == 1)
2397
Cory Benfield12eae892014-06-07 15:42:56 +01002398
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002399# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2400# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002401_lib.SSL_library_init()