blob: d8896241d1b11cc791feddc11d55d7845c2f37c2 [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,
Shane Harvey33c54992020-08-05 16:48:51 -070031 X509StoreContext,
Alex Gaynor03737182020-07-23 20:40:46 -040032)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080033
Nicolas Karolak736c6212017-11-26 14:40:28 +010034__all__ = [
Alex Gaynor03737182020-07-23 20:40:46 -040035 "OPENSSL_VERSION_NUMBER",
36 "SSLEAY_VERSION",
37 "SSLEAY_CFLAGS",
38 "SSLEAY_PLATFORM",
39 "SSLEAY_DIR",
40 "SSLEAY_BUILT_ON",
41 "SENT_SHUTDOWN",
42 "RECEIVED_SHUTDOWN",
43 "SSLv2_METHOD",
44 "SSLv3_METHOD",
45 "SSLv23_METHOD",
46 "TLSv1_METHOD",
47 "TLSv1_1_METHOD",
48 "TLSv1_2_METHOD",
49 "OP_NO_SSLv2",
50 "OP_NO_SSLv3",
51 "OP_NO_TLSv1",
52 "OP_NO_TLSv1_1",
53 "OP_NO_TLSv1_2",
54 "OP_NO_TLSv1_3",
55 "MODE_RELEASE_BUFFERS",
56 "OP_SINGLE_DH_USE",
57 "OP_SINGLE_ECDH_USE",
58 "OP_EPHEMERAL_RSA",
59 "OP_MICROSOFT_SESS_ID_BUG",
60 "OP_NETSCAPE_CHALLENGE_BUG",
61 "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
62 "OP_SSLREF2_REUSE_CERT_TYPE_BUG",
63 "OP_MICROSOFT_BIG_SSLV3_BUFFER",
64 "OP_MSIE_SSLV2_RSA_PADDING",
65 "OP_SSLEAY_080_CLIENT_DH_BUG",
66 "OP_TLS_D5_BUG",
67 "OP_TLS_BLOCK_PADDING_BUG",
68 "OP_DONT_INSERT_EMPTY_FRAGMENTS",
69 "OP_CIPHER_SERVER_PREFERENCE",
70 "OP_TLS_ROLLBACK_BUG",
71 "OP_PKCS1_CHECK_1",
72 "OP_PKCS1_CHECK_2",
73 "OP_NETSCAPE_CA_DN_BUG",
74 "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
75 "OP_NO_COMPRESSION",
76 "OP_NO_QUERY_MTU",
77 "OP_COOKIE_EXCHANGE",
78 "OP_NO_TICKET",
79 "OP_ALL",
80 "VERIFY_PEER",
81 "VERIFY_FAIL_IF_NO_PEER_CERT",
82 "VERIFY_CLIENT_ONCE",
83 "VERIFY_NONE",
84 "SESS_CACHE_OFF",
85 "SESS_CACHE_CLIENT",
86 "SESS_CACHE_SERVER",
87 "SESS_CACHE_BOTH",
88 "SESS_CACHE_NO_AUTO_CLEAR",
89 "SESS_CACHE_NO_INTERNAL_LOOKUP",
90 "SESS_CACHE_NO_INTERNAL_STORE",
91 "SESS_CACHE_NO_INTERNAL",
92 "SSL_ST_CONNECT",
93 "SSL_ST_ACCEPT",
94 "SSL_ST_MASK",
95 "SSL_CB_LOOP",
96 "SSL_CB_EXIT",
97 "SSL_CB_READ",
98 "SSL_CB_WRITE",
99 "SSL_CB_ALERT",
100 "SSL_CB_READ_ALERT",
101 "SSL_CB_WRITE_ALERT",
102 "SSL_CB_ACCEPT_LOOP",
103 "SSL_CB_ACCEPT_EXIT",
104 "SSL_CB_CONNECT_LOOP",
105 "SSL_CB_CONNECT_EXIT",
106 "SSL_CB_HANDSHAKE_START",
107 "SSL_CB_HANDSHAKE_DONE",
108 "Error",
109 "WantReadError",
110 "WantWriteError",
111 "WantX509LookupError",
112 "ZeroReturnError",
113 "SysCallError",
114 "SSLeay_version",
115 "Session",
116 "Context",
117 "Connection",
Nicolas Karolak736c6212017-11-26 14:40:28 +0100118]
119
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500120try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200121 _buffer = buffer
122except NameError:
Alex Gaynor03737182020-07-23 20:40:46 -0400123
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200124 class _buffer(object):
125 pass
126
Alex Gaynor03737182020-07-23 20:40:46 -0400127
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
129SSLEAY_VERSION = _lib.SSLEAY_VERSION
130SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
131SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
132SSLEAY_DIR = _lib.SSLEAY_DIR
133SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800134
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500135SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
136RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
138SSLv2_METHOD = 1
139SSLv3_METHOD = 2
140SSLv23_METHOD = 3
141TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500142TLSv1_1_METHOD = 5
143TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800144
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500145OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
146OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
147OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700148OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
149OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700150try:
151 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
152except AttributeError:
153 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800154
Alex Gaynorbf012872016-06-04 13:18:39 -0700155MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800156
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500157OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900158OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500159OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
160OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
161OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400162OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
163 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
164)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500165OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
166OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400167OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500168OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
169OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
170OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
171OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
172OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
173OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
174OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
175OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
176OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400177OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
178 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
179)
Alex Gaynorbf012872016-06-04 13:18:39 -0700180OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800181
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500182OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
183OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400184OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800185
Alex Gaynorc4889812015-09-04 08:43:17 -0400186OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800187
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500188VERIFY_PEER = _lib.SSL_VERIFY_PEER
189VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
190VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
191VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800192
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500193SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
194SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
195SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
196SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
197SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
198SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
199SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
200SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800201
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500202SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
203SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
204SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400205if _lib.Cryptography_HAS_SSL_ST:
206 SSL_ST_INIT = _lib.SSL_ST_INIT
207 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
208 SSL_ST_OK = _lib.SSL_ST_OK
209 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Alex Gaynor03737182020-07-23 20:40:46 -0400210 __all__.extend(
211 ["SSL_ST_INIT", "SSL_ST_BEFORE", "SSL_ST_OK", "SSL_ST_RENEGOTIATE"]
212 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800213
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500214SSL_CB_LOOP = _lib.SSL_CB_LOOP
215SSL_CB_EXIT = _lib.SSL_CB_EXIT
216SSL_CB_READ = _lib.SSL_CB_READ
217SSL_CB_WRITE = _lib.SSL_CB_WRITE
218SSL_CB_ALERT = _lib.SSL_CB_ALERT
219SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
220SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
221SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
222SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
223SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
224SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
225SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
226SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800227
Paul Kehrer55fb3412017-06-29 18:44:08 -0500228# Taken from https://golang.org/src/crypto/x509/root_linux.go
229_CERTIFICATE_FILE_LOCATIONS = [
230 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
231 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
232 "/etc/ssl/ca-bundle.pem", # OpenSUSE
233 "/etc/pki/tls/cacert.pem", # OpenELEC
234 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
235]
236
237_CERTIFICATE_PATH_LOCATIONS = [
238 "/etc/ssl/certs", # SLES10/SLES11
239]
240
Paul Kehrera92a1a72017-07-19 15:53:23 +0200241# These values are compared to output from cffi's ffi.string so they must be
242# byte strings.
243_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
244_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500245
Alex Gaynor83284952015-09-05 10:43:30 -0400246
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500248 """
249 An error occurred in an `OpenSSL.SSL` API.
250 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251
252
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500253_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100254_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500255
256
257class WantReadError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class WantWriteError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class WantX509LookupError(Error):
266 pass
267
268
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269class ZeroReturnError(Error):
270 pass
271
272
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500273class SysCallError(Error):
274 pass
275
276
Cory Benfield0ea76e72015-03-22 09:05:28 +0000277class _CallbackExceptionHelper(object):
278 """
279 A base class for wrapper classes that allow for intelligent exception
280 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500281
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400282 :ivar list _problems: Any exceptions that occurred while executing in a
283 context where they could not be raised in the normal way. Typically
284 this is because OpenSSL has called into some Python code and requires a
285 return value. The exceptions are saved to be raised later when it is
286 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000287 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400288
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400289 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800290 self._problems = []
291
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400293 """
294 Raise an exception from the OpenSSL error queue or that was previously
295 captured whe running a callback.
296 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000297 if self._problems:
298 try:
299 _raise_current_error()
300 except Error:
301 pass
302 raise self._problems.pop(0)
303
304
305class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400306 """
307 Wrap a callback such that it can be used as a certificate verification
308 callback.
309 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400310
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800311 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400312 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800313
314 @wraps(callback)
315 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800316 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
317 _lib.X509_up_ref(x509)
318 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500319 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
320 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800321
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400322 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
323 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
324 connection = Connection._reverse_mapping[ssl]
325
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800326 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400327 result = callback(
328 connection, cert, error_number, error_depth, ok
329 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800330 except Exception as e:
331 self._problems.append(e)
332 return 0
333 else:
334 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500335 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800336 return 1
337 else:
338 return 0
339
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500340 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400341 "int (*)(int, X509_STORE_CTX *)", wrapper
342 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800343
344
Mark Williams5d890a02019-11-17 19:56:26 -0800345NO_OVERLAPPING_PROTOCOLS = object()
346
347
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400348class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400349 """
350 Wrap a callback such that it can be used as an ALPN selection callback.
351 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400352
Cory Benfieldf1177e72015-04-12 09:11:49 -0400353 def __init__(self, callback):
354 _CallbackExceptionHelper.__init__(self)
355
356 @wraps(callback)
357 def wrapper(ssl, out, outlen, in_, inlen, arg):
358 try:
359 conn = Connection._reverse_mapping[ssl]
360
361 # The string passed to us is made up of multiple
362 # length-prefixed bytestrings. We need to split that into a
363 # list.
364 instr = _ffi.buffer(in_, inlen)[:]
365 protolist = []
366 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400367 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400368 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400369 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400370 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400371
372 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800373 outbytes = callback(conn, protolist)
374 any_accepted = True
375 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400376 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800377 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500378 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800379 raise TypeError(
380 "ALPN callback must return a bytestring or the "
381 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
382 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400383
384 # Save our callback arguments on the connection object to make
385 # sure that they don't get freed before OpenSSL can use them.
386 # Then, return them in the appropriate output parameters.
387 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800388 _ffi.new("unsigned char *", len(outbytes)),
389 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400390 ]
391 outlen[0] = conn._alpn_select_callback_args[0][0]
392 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800393 if not any_accepted:
394 return _lib.SSL_TLSEXT_ERR_NOACK
395 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400396 except Exception as e:
397 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800398 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400399
400 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400401 (
402 "int (*)(SSL *, unsigned char **, unsigned char *, "
403 "const unsigned char *, unsigned int, void *)"
404 ),
405 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400406 )
407
408
Cory Benfield496652a2017-01-24 11:42:56 +0000409class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
410 """
411 Wrap a callback such that it can be used as an OCSP callback for the server
412 side.
413
414 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
415 ways. For servers, that callback is expected to retrieve some OCSP data and
416 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
417 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
418 is expected to check the OCSP data, and returns a negative value on error,
419 0 if the response is not acceptable, or positive if it is. These are
420 mutually exclusive return code behaviours, and they mean that we need two
421 helpers so that we always return an appropriate error code if the user's
422 code throws an exception.
423
424 Given that we have to have two helpers anyway, these helpers are a bit more
425 helpery than most: specifically, they hide a few more of the OpenSSL
426 functions so that the user has an easier time writing these callbacks.
427
428 This helper implements the server side.
429 """
430
431 def __init__(self, callback):
432 _CallbackExceptionHelper.__init__(self)
433
434 @wraps(callback)
435 def wrapper(ssl, cdata):
436 try:
437 conn = Connection._reverse_mapping[ssl]
438
439 # Extract the data if any was provided.
440 if cdata != _ffi.NULL:
441 data = _ffi.from_handle(cdata)
442 else:
443 data = None
444
445 # Call the callback.
446 ocsp_data = callback(conn, data)
447
Alex Gaynor12576002019-11-18 00:18:50 -0500448 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000449 raise TypeError("OCSP callback must return a bytestring.")
450
451 # If the OCSP data was provided, we will pass it to OpenSSL.
452 # However, we have an early exit here: if no OCSP data was
453 # provided we will just exit out and tell OpenSSL that there
454 # is nothing to do.
455 if not ocsp_data:
456 return 3 # SSL_TLSEXT_ERR_NOACK
457
David Benjamin7ac5f272018-05-21 21:24:04 -0400458 # OpenSSL takes ownership of this data and expects it to have
459 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000460 ocsp_data_length = len(ocsp_data)
461 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
462 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
463
464 _lib.SSL_set_tlsext_status_ocsp_resp(
465 ssl, data_ptr, ocsp_data_length
466 )
467
468 return 0
469 except Exception as e:
470 self._problems.append(e)
471 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
472
473 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
474
475
476class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
477 """
478 Wrap a callback such that it can be used as an OCSP callback for the client
479 side.
480
481 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
482 ways. For servers, that callback is expected to retrieve some OCSP data and
483 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
484 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
485 is expected to check the OCSP data, and returns a negative value on error,
486 0 if the response is not acceptable, or positive if it is. These are
487 mutually exclusive return code behaviours, and they mean that we need two
488 helpers so that we always return an appropriate error code if the user's
489 code throws an exception.
490
491 Given that we have to have two helpers anyway, these helpers are a bit more
492 helpery than most: specifically, they hide a few more of the OpenSSL
493 functions so that the user has an easier time writing these callbacks.
494
495 This helper implements the client side.
496 """
497
498 def __init__(self, callback):
499 _CallbackExceptionHelper.__init__(self)
500
501 @wraps(callback)
502 def wrapper(ssl, cdata):
503 try:
504 conn = Connection._reverse_mapping[ssl]
505
506 # Extract the data if any was provided.
507 if cdata != _ffi.NULL:
508 data = _ffi.from_handle(cdata)
509 else:
510 data = None
511
512 # Get the OCSP data.
513 ocsp_ptr = _ffi.new("unsigned char **")
514 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
515 if ocsp_len < 0:
516 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400517 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000518 else:
519 # Copy the OCSP data, then pass it to the callback.
520 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
521
522 valid = callback(conn, ocsp_data, data)
523
524 # Return 1 on success or 0 on error.
525 return int(bool(valid))
526
527 except Exception as e:
528 self._problems.append(e)
529 # Return negative value if an exception is hit.
530 return -1
531
532 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
533
534
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800535def _asFileDescriptor(obj):
536 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800537 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800538 meth = getattr(obj, "fileno", None)
539 if meth is not None:
540 obj = meth()
541
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800542 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800543 fd = obj
544
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800545 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800546 raise TypeError("argument must be an int, or have a fileno() method.")
547 elif fd < 0:
548 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400549 "file descriptor cannot be a negative integer (%i)" % (fd,)
550 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800551
552 return fd
553
554
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800555def SSLeay_version(type):
556 """
557 Return a string describing the version of OpenSSL in use.
558
Alex Chand072cae2018-02-15 09:57:59 +0000559 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800560 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500561 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800562
563
Cory Benfieldef404df2016-03-29 15:32:48 +0100564def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400565 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100566 Builds a decorator that ensures that functions that rely on OpenSSL
567 functions that are not present in this build raise NotImplementedError,
568 rather than AttributeError coming out of cryptography.
569
570 :param flag: A cryptography flag that guards the functions, e.g.
571 ``Cryptography_HAS_NEXTPROTONEG``.
572 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400573 """
Alex Gaynor03737182020-07-23 20:40:46 -0400574
Cory Benfieldef404df2016-03-29 15:32:48 +0100575 def _requires_decorator(func):
576 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400577
Cory Benfieldef404df2016-03-29 15:32:48 +0100578 @wraps(func)
579 def explode(*args, **kwargs):
580 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400581
Cory Benfieldef404df2016-03-29 15:32:48 +0100582 return explode
583 else:
584 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400585
Cory Benfieldef404df2016-03-29 15:32:48 +0100586 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400587
588
Cory Benfieldef404df2016-03-29 15:32:48 +0100589_requires_alpn = _make_requires(
590 _lib.Cryptography_HAS_ALPN, "ALPN not available"
591)
Cory Benfielde6f35882016-03-29 11:21:04 +0100592
Cory Benfielde6f35882016-03-29 11:21:04 +0100593
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200594_requires_keylog = _make_requires(
595 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
596)
597
598
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800599class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000600 """
601 A class representing an SSL session. A session defines certain connection
602 parameters which may be re-used to speed up the setup of subsequent
603 connections.
604
605 .. versionadded:: 0.14
606 """
Alex Gaynor03737182020-07-23 20:40:46 -0400607
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800608 pass
609
610
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800611class Context(object):
612 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100613 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400614 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000615
616 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
617 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800618 """
Alex Gaynor03737182020-07-23 20:40:46 -0400619
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800620 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800621 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500622 SSLv3_METHOD: "SSLv3_method",
623 SSLv23_METHOD: "SSLv23_method",
624 TLSv1_METHOD: "TLSv1_method",
625 TLSv1_1_METHOD: "TLSv1_1_method",
626 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400627 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500628 _methods = dict(
629 (identifier, getattr(_lib, name))
630 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400631 if getattr(_lib, name, None) is not None
632 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800633
634 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500635 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800636 raise TypeError("method must be an integer")
637
638 try:
639 method_func = self._methods[method]
640 except KeyError:
641 raise ValueError("No such protocol")
642
643 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700644 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500646 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700647 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500648 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800649
Alex Gaynor77debda2020-04-07 13:40:59 -0400650 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
651 # auto-selected. This function was added in 1.0.2 and made a noop in
652 # 1.1.0+ (where it is set automatically).
653 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
654 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600655
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800657 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800659 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800660 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661 self._verify_callback = None
662 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200663 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800665 self._app_data = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400666 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100667 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000668 self._ocsp_helper = None
669 self._ocsp_callback = None
670 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800671
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500672 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800674 def load_verify_locations(self, cafile, capath=None):
675 """
676 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000677 chain. Note that the certificates have to be in PEM format.
678
679 If capath is passed, it must be a directory prepared using the
680 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
681 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400683 :param cafile: In which file we can find the certificates (``bytes`` or
684 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800685 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400686 (``bytes`` or ``unicode``).
687
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800688 :return: None
689 """
690 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500691 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400692 else:
693 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694
695 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500696 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400697 else:
698 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800699
Alex Gaynor62da94d2015-09-05 14:37:34 -0400700 load_result = _lib.SSL_CTX_load_verify_locations(
701 self._context, cafile, capath
702 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800703 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500704 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800706 def _wrap_callback(self, callback):
707 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800708 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800709 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400710
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800711 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400712 FILETYPE_PEM, wrapper, more_args=True, truncate=True
713 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800715 def set_passwd_cb(self, callback, userdata=None):
716 """
Alex Chand072cae2018-02-15 09:57:59 +0000717 Set the passphrase callback. This function will be called
718 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800719
Alex Chand072cae2018-02-15 09:57:59 +0000720 :param callback: The Python callback to use. This must accept three
721 positional arguments. First, an integer giving the maximum length
722 of the passphrase it may return. If the returned passphrase is
723 longer than this, it will be truncated. Second, a boolean value
724 which will be true if the user should be prompted for the
725 passphrase twice and the callback should verify that the two values
726 supplied are equal. Third, the value given as the *userdata*
727 parameter to :meth:`set_passwd_cb`. The *callback* must return
728 a byte string. If an error occurs, *callback* should return a false
729 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 :param userdata: (optional) A Python object which will be given as
731 argument to the callback
732 :return: None
733 """
734 if not callable(callback):
735 raise TypeError("callback must be callable")
736
737 self._passphrase_helper = self._wrap_callback(callback)
738 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500739 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400740 self._context, self._passphrase_callback
741 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800742 self._passphrase_userdata = userdata
743
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744 def set_default_verify_paths(self):
745 """
Alex Chand072cae2018-02-15 09:57:59 +0000746 Specify that the platform provided CA certificates are to be used for
747 verification purposes. This method has some caveats related to the
748 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
749
750 * macOS will only load certificates using this method if the user has
751 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
752 in the default location.
753 * Windows will not work.
754 * manylinux1 cryptography wheels will work on most common Linux
755 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
756 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757
758 :return: None
759 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500760 # SSL_CTX_set_default_verify_paths will attempt to load certs from
761 # both a cafile and capath that are set at compile time. However,
762 # it will first check environment variables and, if present, load
763 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500764 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400765 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500766 # After attempting to set default_verify_paths we need to know whether
767 # to go down the fallback path.
768 # First we'll check to see if any env vars have been set. If so,
769 # we won't try to do anything else because the user has set the path
770 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400771 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
772 "ascii"
773 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500774 file_env_var = _ffi.string(
775 _lib.X509_get_default_cert_file_env()
776 ).decode("ascii")
777 if not self._check_env_vars_set(dir_env_var, file_env_var):
778 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
779 default_file = _ffi.string(_lib.X509_get_default_cert_file())
780 # Now we check to see if the default_dir and default_file are set
781 # to the exact values we use in our manylinux1 builds. If they are
782 # then we know to load the fallbacks
783 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400784 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
785 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500786 ):
787 # This is manylinux1, let's load our fallback paths
788 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400789 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500790 )
791
792 def _check_env_vars_set(self, dir_env_var, file_env_var):
793 """
794 Check to see if the default cert dir/file environment vars are present.
795
796 :return: bool
797 """
798 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400799 os.environ.get(file_env_var) is not None
800 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500801 )
802
803 def _fallback_default_verify_paths(self, file_path, dir_path):
804 """
805 Default verify paths are based on the compiled version of OpenSSL.
806 However, when pyca/cryptography is compiled as a manylinux1 wheel
807 that compiled location can potentially be wrong. So, like Go, we
808 will try a predefined set of paths and attempt to load roots
809 from there.
810
811 :return: None
812 """
813 for cafile in file_path:
814 if os.path.isfile(cafile):
815 self.load_verify_locations(cafile)
816 break
817
818 for capath in dir_path:
819 if os.path.isdir(capath):
820 self.load_verify_locations(None, capath)
821 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800822
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800823 def use_certificate_chain_file(self, certfile):
824 """
Alex Chand072cae2018-02-15 09:57:59 +0000825 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800826
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400827 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000828 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400829
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800830 :return: None
831 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400832 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800833
Alex Gaynor62da94d2015-09-05 14:37:34 -0400834 result = _lib.SSL_CTX_use_certificate_chain_file(
835 self._context, certfile
836 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800837 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500838 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800839
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800840 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800841 """
842 Load a certificate from a file
843
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400844 :param certfile: The name of the certificate file (``bytes`` or
845 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000846 :param filetype: (optional) The encoding of the file, which is either
847 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
848 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400849
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800850 :return: None
851 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400852 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500853 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800854 raise TypeError("filetype must be an integer")
855
Alex Gaynor62da94d2015-09-05 14:37:34 -0400856 use_result = _lib.SSL_CTX_use_certificate_file(
857 self._context, certfile, filetype
858 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800859 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500860 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800861
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800862 def use_certificate(self, cert):
863 """
864 Load a certificate from a X509 object
865
866 :param cert: The X509 object
867 :return: None
868 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800869 if not isinstance(cert, X509):
870 raise TypeError("cert must be an X509 instance")
871
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800873 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500874 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800875
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800876 def add_extra_chain_cert(self, certobj):
877 """
878 Add certificate to chain
879
880 :param certobj: The X509 certificate object to add to the chain
881 :return: None
882 """
883 if not isinstance(certobj, X509):
884 raise TypeError("certobj must be an X509 instance")
885
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500886 copy = _lib.X509_dup(certobj._x509)
887 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800888 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500889 # TODO: This is untested.
890 _lib.X509_free(copy)
891 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800892
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800893 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500894 if self._passphrase_helper is not None:
895 self._passphrase_helper.raise_if_problem(Error)
896
897 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800898
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400899 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900 """
901 Load a private key from a file
902
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400903 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000904 :param filetype: (optional) The encoding of the file, which is either
905 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
906 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400907
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908 :return: None
909 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400910 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400912 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800913 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500914 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800915 raise TypeError("filetype must be an integer")
916
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500917 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -0400918 self._context, keyfile, filetype
919 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800921 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800923 def use_privatekey(self, pkey):
924 """
925 Load a private key from a PKey object
926
927 :param pkey: The PKey object
928 :return: None
929 """
930 if not isinstance(pkey, PKey):
931 raise TypeError("pkey must be a PKey instance")
932
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500933 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800935 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800937 def check_privatekey(self):
938 """
Alex Chand072cae2018-02-15 09:57:59 +0000939 Check if the private key (loaded with :meth:`use_privatekey`) matches
940 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800941
Alex Chand072cae2018-02-15 09:57:59 +0000942 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500944 if not _lib.SSL_CTX_check_private_key(self._context):
945 _raise_current_error()
946
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800947 def load_client_ca(self, cafile):
948 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100949 Load the trusted certificates that will be sent to the client. Does
950 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400951 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100953 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800954 :return: None
955 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100956 ca_list = _lib.SSL_load_client_CA_file(
957 _text_to_bytes_and_warn("cafile", cafile)
958 )
959 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100960 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800961
962 def set_session_id(self, buf):
963 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100964 Set the session id to *buf* within which a session can be reused for
965 this Context object. This is needed when doing session resumption,
966 because there is no way for a stored session to know which Context
967 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800968
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100969 :param bytes buf: The session id.
970
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800971 :returns: None
972 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100973 buf = _text_to_bytes_and_warn("buf", buf)
974 _openssl_assert(
Alex Gaynor03737182020-07-23 20:40:46 -0400975 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf),)
976 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100977 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978
979 def set_session_cache_mode(self, mode):
980 """
Alex Chand072cae2018-02-15 09:57:59 +0000981 Set the behavior of the session cache used by all connections using
982 this Context. The previously set mode is returned. See
983 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984
985 :param mode: One or more of the SESS_CACHE_* flags (combine using
986 bitwise or)
987 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000988
989 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500991 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992 raise TypeError("mode must be an integer")
993
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500994 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996 def get_session_cache_mode(self):
997 """
Alex Chand072cae2018-02-15 09:57:59 +0000998 Get the current session cache mode.
999
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001000 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001001
1002 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001005
Maximilian Hils79b9c792020-08-08 03:08:17 +02001006 def set_verify(self, mode, callback=None):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001007 """
Alex Chand072cae2018-02-15 09:57:59 +00001008 et the verification flags for this Context object to *mode* and specify
1009 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010
Alex Chand072cae2018-02-15 09:57:59 +00001011 :param mode: The verify mode, this should be one of
1012 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1013 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1014 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1015 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
Maximilian Hils79b9c792020-08-08 03:08:17 +02001016 :param callback: The optional Python verification callback to use.
1017 This should take five arguments: A Connection object, an X509
1018 object, and three integer variables, which are in turn potential
1019 error number, error depth and return code. *callback* should
1020 return True if verification passes and False otherwise.
1021 If omitted, OpenSSL's default verification is used.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001022 :return: None
1023
1024 See SSL_CTX_set_verify(3SSL) for further details.
1025 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001026 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001027 raise TypeError("mode must be an integer")
1028
Maximilian Hils79b9c792020-08-08 03:08:17 +02001029 if callback is None:
1030 self._verify_helper = None
1031 self._verify_callback = None
1032 _lib.SSL_CTX_set_verify(self._context, mode, _ffi.NULL)
1033 else:
1034 if not callable(callback):
1035 raise TypeError("callback must be callable")
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001036
Maximilian Hils79b9c792020-08-08 03:08:17 +02001037 self._verify_helper = _VerifyHelper(callback)
1038 self._verify_callback = self._verify_helper.callback
1039 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001040
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041 def set_verify_depth(self, depth):
1042 """
Alex Chand072cae2018-02-15 09:57:59 +00001043 Set the maximum depth for the certificate chain verification that shall
1044 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045
1046 :param depth: An integer specifying the verify depth
1047 :return: None
1048 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001049 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001050 raise TypeError("depth must be an integer")
1051
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001052 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001053
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054 def get_verify_mode(self):
1055 """
Alex Chand072cae2018-02-15 09:57:59 +00001056 Retrieve the Context object's verify mode, as set by
1057 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001058
1059 :return: The verify mode
1060 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001061 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001062
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001063 def get_verify_depth(self):
1064 """
Alex Chand072cae2018-02-15 09:57:59 +00001065 Retrieve the Context object's verify depth, as set by
1066 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067
1068 :return: The verify depth
1069 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001070 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001071
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072 def load_tmp_dh(self, dhfile):
1073 """
1074 Load parameters for Ephemeral Diffie-Hellman
1075
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001076 :param dhfile: The file to load EDH parameters from (``bytes`` or
1077 ``unicode``).
1078
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001079 :return: None
1080 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001081 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001083 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001084 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001085 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001086 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1089 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001090 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1091 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001092
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001093 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001094 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001095 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001096
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001097 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001098 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1099 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001100
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001101 :return: None
1102 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001103 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001104
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 def set_cipher_list(self, cipher_list):
1106 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001107 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001108
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001109 See the OpenSSL manual for more information (e.g.
1110 :manpage:`ciphers(1)`).
1111
1112 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001113 :return: None
1114 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001115 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001116
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001118 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001119
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001120 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001121 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001122 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001123 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1124 # ciphers even if you pass an invalid cipher. Applications (like
1125 # Twisted) have tests that depend on an error being raised if an
1126 # invalid cipher string is passed, but without the following check
1127 # for the TLS 1.3 specific cipher suites it would never error.
1128 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001129 if tmpconn.get_cipher_list() == [
1130 "TLS_AES_256_GCM_SHA384",
1131 "TLS_CHACHA20_POLY1305_SHA256",
1132 "TLS_AES_128_GCM_SHA256",
1133 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001134 raise Error(
1135 [
1136 (
Alex Gaynor03737182020-07-23 20:40:46 -04001137 "SSL routines",
1138 "SSL_CTX_set_cipher_list",
1139 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001140 ),
1141 ],
1142 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001143
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144 def set_client_ca_list(self, certificate_authorities):
1145 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001146 Set the list of preferred client certificate signers for this server
1147 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001148
Alex Gaynor62da94d2015-09-05 14:37:34 -04001149 This list of certificate authorities will be sent to the client when
1150 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001151
1152 :param certificate_authorities: a sequence of X509Names.
1153 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001154
1155 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001156 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001158 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001159
1160 try:
1161 for ca_name in certificate_authorities:
1162 if not isinstance(ca_name, X509Name):
1163 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001164 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001165 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001166 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001168 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001172 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001173 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001174 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001175 raise
1176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001177 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001178
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001179 def add_client_ca(self, certificate_authority):
1180 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001181 Add the CA certificate to the list of preferred signers for this
1182 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183
1184 The list of certificate authorities will be sent to the client when the
1185 server requests a client certificate.
1186
1187 :param certificate_authority: certificate authority's X509 certificate.
1188 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001189
1190 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001191 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001192 if not isinstance(certificate_authority, X509):
1193 raise TypeError("certificate_authority must be an X509 instance")
1194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001195 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001196 self._context, certificate_authority._x509
1197 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001198 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001199
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001200 def set_timeout(self, timeout):
1201 """
Alex Chand072cae2018-02-15 09:57:59 +00001202 Set the timeout for newly created sessions for this Context object to
1203 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1204 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001205
Alex Chand072cae2018-02-15 09:57:59 +00001206 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207 :return: The previous session timeout
1208 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001209 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001210 raise TypeError("timeout must be an integer")
1211
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001212 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001213
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001214 def get_timeout(self):
1215 """
Alex Chand072cae2018-02-15 09:57:59 +00001216 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1217 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001218
1219 :return: The session timeout
1220 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001221 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001222
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001223 def set_info_callback(self, callback):
1224 """
Alex Chand072cae2018-02-15 09:57:59 +00001225 Set the information callback to *callback*. This function will be
1226 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001227
Alex Chand072cae2018-02-15 09:57:59 +00001228 :param callback: The Python callback to use. This should take three
1229 arguments: a Connection object and two integers. The first integer
1230 specifies where in the SSL handshake the function was called, and
1231 the other the return code from a (possibly failed) internal
1232 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001233 :return: None
1234 """
Alex Gaynor03737182020-07-23 20:40:46 -04001235
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001236 @wraps(callback)
1237 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001238 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001239
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001241 "void (*)(const SSL *, int, int)", wrapper
1242 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001244
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001245 @_requires_keylog
1246 def set_keylog_callback(self, callback):
1247 """
1248 Set the TLS key logging callback to *callback*. This function will be
1249 called whenever TLS key material is generated or received, in order
1250 to allow applications to store this keying material for debugging
1251 purposes.
1252
1253 :param callback: The Python callback to use. This should take two
1254 arguments: a Connection object and a bytestring that contains
1255 the key material in the format used by NSS for its SSLKEYLOGFILE
1256 debugging output.
1257 :return: None
1258 """
1259
1260 @wraps(callback)
1261 def wrapper(ssl, line):
1262 line = _ffi.string(line)
1263 callback(Connection._reverse_mapping[ssl], line)
1264
1265 self._keylog_callback = _ffi.callback(
1266 "void (*)(const SSL *, const char *)", wrapper
1267 )
1268 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1269
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001270 def get_app_data(self):
1271 """
Alex Chand072cae2018-02-15 09:57:59 +00001272 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273
1274 :return: The application data
1275 """
1276 return self._app_data
1277
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001278 def set_app_data(self, data):
1279 """
1280 Set the application data (will be returned from get_app_data())
1281
1282 :param data: Any Python object
1283 :return: None
1284 """
1285 self._app_data = data
1286
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287 def get_cert_store(self):
1288 """
Alex Chand072cae2018-02-15 09:57:59 +00001289 Get the certificate store for the context. This can be used to add
1290 "trusted" certificates without using the
1291 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001292
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001293 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001294 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001295 store = _lib.SSL_CTX_get_cert_store(self._context)
1296 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001297 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001298 return None
1299
1300 pystore = X509Store.__new__(X509Store)
1301 pystore._store = store
1302 return pystore
1303
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001304 def set_options(self, options):
1305 """
1306 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001307 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001308
1309 :param options: The options to add.
1310 :return: The new option bitmask.
1311 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001312 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001313 raise TypeError("options must be an integer")
1314
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001315 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001316
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317 def set_mode(self, mode):
1318 """
Alex Chand072cae2018-02-15 09:57:59 +00001319 Add modes via bitmask. Modes set before are not cleared! This method
1320 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321
1322 :param mode: The mode to add.
1323 :return: The new mode bitmask.
1324 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001325 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001326 raise TypeError("mode must be an integer")
1327
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001328 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001329
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001330 def set_tlsext_servername_callback(self, callback):
1331 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001332 Specify a callback function to be called when clients specify a server
1333 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001334
1335 :param callback: The callback function. It will be invoked with one
1336 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001337
1338 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001339 """
Alex Gaynor03737182020-07-23 20:40:46 -04001340
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001341 @wraps(callback)
1342 def wrapper(ssl, alert, arg):
1343 callback(Connection._reverse_mapping[ssl])
1344 return 0
1345
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001346 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001347 "int (*)(SSL *, int *, void *)", wrapper
1348 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001349 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001350 self._context, self._tlsext_servername_callback
1351 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001352
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001353 def set_tlsext_use_srtp(self, profiles):
1354 """
1355 Enable support for negotiating SRTP keying material.
1356
1357 :param bytes profiles: A colon delimited list of protection profile
1358 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1359 :return: None
1360 """
1361 if not isinstance(profiles, bytes):
1362 raise TypeError("profiles must be a byte string.")
1363
1364 _openssl_assert(
1365 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1366 )
1367
Cory Benfield7907e332015-04-13 17:18:25 -04001368 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001369 def set_alpn_protos(self, protos):
1370 """
Alex Chand072cae2018-02-15 09:57:59 +00001371 Specify the protocols that the client is prepared to speak after the
1372 TLS connection has been negotiated using Application Layer Protocol
1373 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001374
1375 :param protos: A list of the protocols to be offered to the server.
1376 This list should be a Python list of bytestrings representing the
1377 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1378 """
1379 # Take the list of protocols and join them together, prefixing them
1380 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001381 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001382 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1383 )
1384
1385 # Build a C string from the list. We don't need to save this off
1386 # because OpenSSL immediately copies the data out.
1387 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001388 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001389
Cory Benfield7907e332015-04-13 17:18:25 -04001390 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001391 def set_alpn_select_callback(self, callback):
1392 """
Alex Chand072cae2018-02-15 09:57:59 +00001393 Specify a callback function that will be called on the server when a
1394 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001395
1396 :param callback: The callback function. It will be invoked with two
1397 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001398 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1399 one of those bytestrings to indicate the chosen protocol, the
1400 empty bytestring to terminate the TLS connection, or the
1401 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1402 protocol was selected, but that the connection should not be
1403 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001404 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001405 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001406 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001407 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001408 self._context, self._alpn_select_callback, _ffi.NULL
1409 )
Cory Benfield12eae892014-06-07 15:42:56 +01001410
Cory Benfield496652a2017-01-24 11:42:56 +00001411 def _set_ocsp_callback(self, helper, data):
1412 """
1413 This internal helper does the common work for
1414 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1415 almost all of it.
1416 """
1417 self._ocsp_helper = helper
1418 self._ocsp_callback = helper.callback
1419 if data is None:
1420 self._ocsp_data = _ffi.NULL
1421 else:
1422 self._ocsp_data = _ffi.new_handle(data)
1423
1424 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1425 self._context, self._ocsp_callback
1426 )
1427 _openssl_assert(rc == 1)
1428 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1429 _openssl_assert(rc == 1)
1430
1431 def set_ocsp_server_callback(self, callback, data=None):
1432 """
1433 Set a callback to provide OCSP data to be stapled to the TLS handshake
1434 on the server side.
1435
1436 :param callback: The callback function. It will be invoked with two
1437 arguments: the Connection, and the optional arbitrary data you have
1438 provided. The callback must return a bytestring that contains the
1439 OCSP data to staple to the handshake. If no OCSP data is available
1440 for this connection, return the empty bytestring.
1441 :param data: Some opaque data that will be passed into the callback
1442 function when called. This can be used to avoid needing to do
1443 complex data lookups or to keep track of what context is being
1444 used. This parameter is optional.
1445 """
1446 helper = _OCSPServerCallbackHelper(callback)
1447 self._set_ocsp_callback(helper, data)
1448
1449 def set_ocsp_client_callback(self, callback, data=None):
1450 """
1451 Set a callback to validate OCSP data stapled to the TLS handshake on
1452 the client side.
1453
1454 :param callback: The callback function. It will be invoked with three
1455 arguments: the Connection, a bytestring containing the stapled OCSP
1456 assertion, and the optional arbitrary data you have provided. The
1457 callback must return a boolean that indicates the result of
1458 validating the OCSP data: ``True`` if the OCSP data is valid and
1459 the certificate can be trusted, or ``False`` if either the OCSP
1460 data is invalid or the certificate has been revoked.
1461 :param data: Some opaque data that will be passed into the callback
1462 function when called. This can be used to avoid needing to do
1463 complex data lookups or to keep track of what context is being
1464 used. This parameter is optional.
1465 """
1466 helper = _OCSPClientCallbackHelper(callback)
1467 self._set_ocsp_callback(helper, data)
1468
Alex Chanc6077062016-11-18 13:53:39 +00001469
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470class Connection(object):
1471 """
1472 """
Alex Gaynor03737182020-07-23 20:40:46 -04001473
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001474 _reverse_mapping = WeakValueDictionary()
1475
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001476 def __init__(self, context, socket=None):
1477 """
1478 Create a new Connection object, using the given OpenSSL.SSL.Context
1479 instance and socket.
1480
1481 :param context: An SSL Context to use for this connection
1482 :param socket: The socket to use for transport layer
1483 """
1484 if not isinstance(context, Context):
1485 raise TypeError("context must be a Context instance")
1486
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001487 ssl = _lib.SSL_new(context._context)
1488 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001489 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1490 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1491 # even though there is still data on the underlying transport.
1492 # See https://github.com/openssl/openssl/issues/6234 for more details.
1493 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001495 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001496
Cory Benfield12eae892014-06-07 15:42:56 +01001497 # References to strings used for Application Layer Protocol
1498 # Negotiation. These strings get copied at some point but it's well
1499 # after the callback returns, so we have to hang them somewhere to
1500 # avoid them getting freed.
1501 self._alpn_select_callback_args = None
1502
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504
1505 if socket is None:
1506 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001507 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001508 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001509 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510
Alex Gaynora829e902016-06-04 18:16:01 -07001511 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1512 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001514 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001515 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001516 self._into_ssl = None
1517 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001518 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001519 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001520 self._ssl, _asFileDescriptor(self._socket)
1521 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001522 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001524 def __getattr__(self, name):
1525 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001526 Look up attributes on the wrapped socket object if they are not found
1527 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001528 """
kjav0b66fa12015-09-02 11:51:26 +01001529 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001530 raise AttributeError(
1531 "'%s' object has no attribute '%s'"
1532 % (self.__class__.__name__, name)
1533 )
kjav0b66fa12015-09-02 11:51:26 +01001534 else:
1535 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001536
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001537 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001538 if self._context._verify_helper is not None:
1539 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001540 if self._context._alpn_select_helper is not None:
1541 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001542 if self._context._ocsp_helper is not None:
1543 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001544
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001545 error = _lib.SSL_get_error(ssl, result)
1546 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001547 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001548 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001549 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001550 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001552 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001553 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001554 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001555 elif error == _lib.SSL_ERROR_SYSCALL:
1556 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001557 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001558 if platform == "win32":
1559 errno = _ffi.getwinerror()[0]
1560 else:
1561 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001562
1563 if errno != 0:
1564 raise SysCallError(errno, errorcode.get(errno))
1565 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001567 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001568 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001569 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001570 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001571 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001572 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001573
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574 def get_context(self):
1575 """
Alex Chand072cae2018-02-15 09:57:59 +00001576 Retrieve the :class:`Context` object associated with this
1577 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001579 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001580
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001582 """
Alex Chand072cae2018-02-15 09:57:59 +00001583 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001584
Alex Chand072cae2018-02-15 09:57:59 +00001585 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001588 if not isinstance(context, Context):
1589 raise TypeError("context must be a Context instance")
1590
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001591 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 self._context = context
1593
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 def get_servername(self):
1595 """
1596 Retrieve the servername extension value if provided in the client hello
1597 message, or None if there wasn't one.
1598
Alex Chand072cae2018-02-15 09:57:59 +00001599 :return: A byte string giving the server name or :data:`None`.
1600
1601 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001602 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001603 name = _lib.SSL_get_servername(
1604 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1605 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001606 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001609 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001610
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001611 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 """
1613 Set the value of the servername extension to send in the client hello.
1614
1615 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001616
1617 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001618 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619 if not isinstance(name, bytes):
1620 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001621 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001622 raise TypeError("name must not contain NUL byte")
1623
1624 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001625 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001626
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001627 def pending(self):
1628 """
Alex Chand072cae2018-02-15 09:57:59 +00001629 Get the number of bytes that can be safely read from the SSL buffer
1630 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
1632 :return: The number of bytes available in the receive buffer.
1633 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001634 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001636 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637 """
1638 Send data on the connection. NOTE: If you get one of the WantRead,
1639 WantWrite or WantX509Lookup exceptions on this, you have to call the
1640 method again with the SAME buffer.
1641
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001642 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001643 :param flags: (optional) Included for compatibility with the socket
1644 API, the value is ignored
1645 :return: The number of bytes written
1646 """
Abraham Martine82326c2015-02-04 10:18:10 +00001647 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001648 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001649
Daniel Holth079c9632019-11-17 22:45:52 -05001650 with _from_buffer(buf) as data:
1651 # check len(buf) instead of len(data) for testability
1652 if len(buf) > 2147483647:
1653 raise ValueError(
1654 "Cannot send more than 2**31-1 bytes at once."
1655 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656
Daniel Holth079c9632019-11-17 22:45:52 -05001657 result = _lib.SSL_write(self._ssl, data, len(data))
1658 self._raise_ssl_error(self._ssl, result)
1659
1660 return result
1661
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662 write = send
1663
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666 Send "all" data on the connection. This calls send() repeatedly until
1667 all data is sent. If an error occurs, it's impossible to tell how much
1668 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001669
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001670 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671 :param flags: (optional) Included for compatibility with the socket
1672 API, the value is ignored
1673 :return: The number of bytes written
1674 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001675 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001676
Daniel Holth079c9632019-11-17 22:45:52 -05001677 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678
Daniel Holth079c9632019-11-17 22:45:52 -05001679 left_to_send = len(buf)
1680 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681
Daniel Holth079c9632019-11-17 22:45:52 -05001682 while left_to_send:
1683 # SSL_write's num arg is an int,
1684 # so we cannot send more than 2**31-1 bytes at once.
1685 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001686 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001687 )
1688 self._raise_ssl_error(self._ssl, result)
1689 total_sent += result
1690 left_to_send -= result
1691
1692 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001694 def recv(self, bufsiz, flags=None):
1695 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001696 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697
1698 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001699 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1700 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 :return: The string read from the Connection
1702 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001703 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001704 if flags is not None and flags & socket.MSG_PEEK:
1705 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1706 else:
1707 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001708 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001710
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 read = recv
1712
Cory Benfield62d10332014-06-15 10:03:41 +01001713 def recv_into(self, buffer, nbytes=None, flags=None):
1714 """
Alex Chand072cae2018-02-15 09:57:59 +00001715 Receive data on the connection and copy it directly into the provided
1716 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001717
1718 :param buffer: The buffer to copy into.
1719 :param nbytes: (optional) The maximum number of bytes to read into the
1720 buffer. If not present, defaults to the size of the buffer. If
1721 larger than the size of the buffer, is reduced to the size of the
1722 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001723 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1724 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001725 :return: The number of bytes read into the buffer.
1726 """
1727 if nbytes is None:
1728 nbytes = len(buffer)
1729 else:
1730 nbytes = min(nbytes, len(buffer))
1731
1732 # We need to create a temporary buffer. This is annoying, it would be
1733 # better if we could pass memoryviews straight into the SSL_read call,
1734 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001735 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001736 if flags is not None and flags & socket.MSG_PEEK:
1737 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1738 else:
1739 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001740 self._raise_ssl_error(self._ssl, result)
1741
1742 # This strange line is all to avoid a memory copy. The buffer protocol
1743 # should allow us to assign a CFFI buffer to the LHS of this line, but
1744 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001745 # wrap it in a memoryview.
1746 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001747
1748 return result
1749
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001750 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001751 if _lib.BIO_should_retry(bio):
1752 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001753 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001755 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001756 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001757 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001758 # TODO: This is untested. I think io_special means the socket
1759 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001760 raise ValueError("BIO_should_io_special")
1761 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001762 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001763 raise ValueError("unknown bio failure")
1764 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001765 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001766 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001767
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001768 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001769 """
Alex Chand072cae2018-02-15 09:57:59 +00001770 If the Connection was created with a memory BIO, this method can be
1771 used to read bytes from the write end of that memory BIO. Many
1772 Connection methods will add bytes which must be read in this manner or
1773 the buffer will eventually fill up and the Connection will be able to
1774 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001775
1776 :param bufsiz: The maximum number of bytes to read
1777 :return: The string read.
1778 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001779 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001781
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001782 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001783 raise TypeError("bufsiz must be an integer")
1784
Cory Benfielde62840e2016-11-28 12:17:08 +00001785 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001786 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001787 if result <= 0:
1788 self._handle_bio_errors(self._from_ssl, result)
1789
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001790 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001791
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001792 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001793 """
Alex Chand072cae2018-02-15 09:57:59 +00001794 If the Connection was created with a memory BIO, this method can be
1795 used to add bytes to the read end of that memory BIO. The Connection
1796 can then read the bytes (for example, in response to a call to
1797 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001798
1799 :param buf: The string to put into the memory BIO.
1800 :return: The number of bytes written
1801 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001802 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001803
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001804 if self._into_ssl is None:
1805 raise TypeError("Connection sock was not None")
1806
Daniel Holth079c9632019-11-17 22:45:52 -05001807 with _from_buffer(buf) as data:
1808 result = _lib.BIO_write(self._into_ssl, data, len(data))
1809 if result <= 0:
1810 self._handle_bio_errors(self._into_ssl, result)
1811 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001812
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001813 def renegotiate(self):
1814 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001815 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001817 :return: True if the renegotiation can be started, False otherwise
1818 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001819 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001820 if not self.renegotiate_pending():
1821 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1822 return True
1823 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001824
1825 def do_handshake(self):
1826 """
Alex Chand072cae2018-02-15 09:57:59 +00001827 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001828 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001829 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001830
1831 :return: None.
1832 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001833 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001834 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001835
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001836 def renegotiate_pending(self):
1837 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001838 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839 a renegotiation is finished.
1840
1841 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001842 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001843 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001844 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001845
1846 def total_renegotiations(self):
1847 """
1848 Find out the total number of renegotiations.
1849
1850 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001851 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001852 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001853 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001854
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001855 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001856 """
Alex Chand072cae2018-02-15 09:57:59 +00001857 Call the :meth:`connect` method of the underlying socket and set up SSL
1858 on the socket, using the :class:`Context` object supplied to this
1859 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860
1861 :param addr: A remote address
1862 :return: What the socket's connect method returns
1863 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001864 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001865 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001867 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001868 """
Alex Chand072cae2018-02-15 09:57:59 +00001869 Call the :meth:`connect_ex` method of the underlying socket and set up
1870 SSL on the socket, using the Context object supplied to this Connection
1871 object at creation. Note that if the :meth:`connect_ex` method of the
1872 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001873
1874 :param addr: A remove address
1875 :return: What the socket's connect_ex method returns
1876 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001877 connect_ex = self._socket.connect_ex
1878 self.set_connect_state()
1879 return connect_ex(addr)
1880
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881 def accept(self):
1882 """
Alex Chand072cae2018-02-15 09:57:59 +00001883 Call the :meth:`accept` method of the underlying socket and set up SSL
1884 on the returned socket, using the Context object supplied to this
1885 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001886
Alex Chand072cae2018-02-15 09:57:59 +00001887 :return: A *(conn, addr)* pair where *conn* is the new
1888 :class:`Connection` object created, and *address* is as returned by
1889 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001890 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891 client, addr = self._socket.accept()
1892 conn = Connection(self._context, client)
1893 conn.set_accept_state()
1894 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001895
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896 def bio_shutdown(self):
1897 """
Alex Chand072cae2018-02-15 09:57:59 +00001898 If the Connection was created with a memory BIO, this method can be
1899 used to indicate that *end of file* has been reached on the read end of
1900 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001901
1902 :return: None
1903 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001904 if self._from_ssl is None:
1905 raise TypeError("Connection sock was not None")
1906
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001907 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001908
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001909 def shutdown(self):
1910 """
Alex Chand072cae2018-02-15 09:57:59 +00001911 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912
1913 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001914 have sent closure alerts), False otherwise (in which case you
1915 call :meth:`recv` or :meth:`send` when the connection becomes
1916 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001918 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001919 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001920 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001922 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923 else:
1924 return False
1925
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926 def get_cipher_list(self):
1927 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001928 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001930 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001931 """
1932 ciphers = []
1933 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001934 result = _lib.SSL_get_cipher_list(self._ssl, i)
1935 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001937 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001938 return ciphers
1939
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001940 def get_client_ca_list(self):
1941 """
1942 Get CAs whose certificates are suggested for client authentication.
1943
Alex Chand072cae2018-02-15 09:57:59 +00001944 :return: If this is a server connection, the list of certificate
1945 authorities that will be sent or has been sent to the client, as
1946 controlled by this :class:`Connection`'s :class:`Context`.
1947
1948 If this is a client connection, the list will be empty until the
1949 connection with the server is established.
1950
1951 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1954 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001955 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001956 return []
1957
1958 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001959 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1960 name = _lib.sk_X509_NAME_value(ca_names, i)
1961 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001962 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001963
1964 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001965 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001966 result.append(pyname)
1967 return result
1968
Aykee7f33452018-05-16 19:18:16 +02001969 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001970 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001971 The makefile() method is not implemented, since there is no dup
1972 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001974 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001975 """
Alex Gaynor83284952015-09-05 10:43:30 -04001976 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001977 "Cannot make file object of OpenSSL.SSL.Connection"
1978 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001979
1980 def get_app_data(self):
1981 """
Alex Chand072cae2018-02-15 09:57:59 +00001982 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983
1984 :return: The application data
1985 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001986 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001987
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001988 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989 """
1990 Set application data
1991
Alex Chand072cae2018-02-15 09:57:59 +00001992 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993 :return: None
1994 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001995 self._app_data = data
1996
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997 def get_shutdown(self):
1998 """
Alex Chand072cae2018-02-15 09:57:59 +00001999 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002000
Alex Gaynor62da94d2015-09-05 14:37:34 -04002001 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2002 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002004 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002007 """
Alex Chand072cae2018-02-15 09:57:59 +00002008 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002009
Alex Chand072cae2018-02-15 09:57:59 +00002010 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011 :return: None
2012 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002013 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002014 raise TypeError("state must be an integer")
2015
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002016 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002017
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002018 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002020 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021
2022 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002023 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024 """
kjavc704a2e2015-09-07 12:12:27 +01002025 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002026
2027 def server_random(self):
2028 """
Alex Chand072cae2018-02-15 09:57:59 +00002029 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002030
2031 :return: A string representing the state
2032 """
Alex Gaynor93603062016-06-01 20:13:09 -07002033 session = _lib.SSL_get_session(self._ssl)
2034 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002035 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002036 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002037 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002038 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002039 _lib.SSL_get_server_random(self._ssl, outp, length)
2040 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002041
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002042 def client_random(self):
2043 """
Alex Chand072cae2018-02-15 09:57:59 +00002044 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002045
2046 :return: A string representing the state
2047 """
Alex Gaynor93603062016-06-01 20:13:09 -07002048 session = _lib.SSL_get_session(self._ssl)
2049 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002050 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002051
2052 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002053 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002054 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002055 _lib.SSL_get_client_random(self._ssl, outp, length)
2056 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002057
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002058 def master_key(self):
2059 """
Alex Chand072cae2018-02-15 09:57:59 +00002060 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002061
2062 :return: A string representing the state
2063 """
Alex Gaynor93603062016-06-01 20:13:09 -07002064 session = _lib.SSL_get_session(self._ssl)
2065 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002066 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002067
2068 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002069 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002070 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002071 _lib.SSL_SESSION_get_master_key(session, outp, length)
2072 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073
Paul Kehrerbdb76392017-12-01 04:54:32 +08002074 def export_keying_material(self, label, olen, context=None):
2075 """
2076 Obtain keying material for application use.
2077
Alex Chand072cae2018-02-15 09:57:59 +00002078 :param: label - a disambiguating label string as described in RFC 5705
2079 :param: olen - the length of the exported key material in bytes
2080 :param: context - a per-association context value
2081 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002082 """
2083 outp = _no_zero_allocator("unsigned char[]", olen)
2084 context_buf = _ffi.NULL
2085 context_len = 0
2086 use_context = 0
2087 if context is not None:
2088 context_buf = context
2089 context_len = len(context)
2090 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002091 success = _lib.SSL_export_keying_material(
2092 self._ssl,
2093 outp,
2094 olen,
2095 label,
2096 len(label),
2097 context_buf,
2098 context_len,
2099 use_context,
2100 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002101 _openssl_assert(success == 1)
2102 return _ffi.buffer(outp, olen)[:]
2103
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002104 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002105 """
Alex Chand072cae2018-02-15 09:57:59 +00002106 Call the :meth:`shutdown` method of the underlying socket.
2107 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002108
2109 :return: What the socket's shutdown() method returns
2110 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002111 return self._socket.shutdown(*args, **kwargs)
2112
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002113 def get_certificate(self):
2114 """
2115 Retrieve the local certificate (if any)
2116
2117 :return: The local certificate
2118 """
2119 cert = _lib.SSL_get_certificate(self._ssl)
2120 if cert != _ffi.NULL:
2121 _lib.X509_up_ref(cert)
2122 return X509._from_raw_x509_ptr(cert)
2123 return None
2124
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002125 def get_peer_certificate(self):
2126 """
2127 Retrieve the other side's certificate (if any)
2128
2129 :return: The peer's certificate
2130 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002131 cert = _lib.SSL_get_peer_certificate(self._ssl)
2132 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002133 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002134 return None
2135
Shane Harvey33c54992020-08-05 16:48:51 -07002136 @staticmethod
2137 def _cert_stack_to_list(cert_stack):
2138 """
2139 Internal helper to convert a STACK_OF(X509) to a list of X509
2140 instances.
2141 """
2142 result = []
2143 for i in range(_lib.sk_X509_num(cert_stack)):
2144 cert = _lib.sk_X509_value(cert_stack, i)
2145 _openssl_assert(cert != _ffi.NULL)
2146 res = _lib.X509_up_ref(cert)
2147 _openssl_assert(res >= 1)
2148 pycert = X509._from_raw_x509_ptr(cert)
2149 result.append(pycert)
2150 return result
2151
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002152 def get_peer_cert_chain(self):
2153 """
2154 Retrieve the other side's certificate (if any)
2155
2156 :return: A list of X509 instances giving the peer's certificate chain,
2157 or None if it does not have one.
2158 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002159 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2160 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002161 return None
2162
Shane Harvey33c54992020-08-05 16:48:51 -07002163 return self._cert_stack_to_list(cert_stack)
2164
2165 def get_verified_chain(self):
2166 """
2167 Retrieve the verified certificate chain of the peer including the
2168 peer's end entity certificate. It must be called after a session has
2169 been successfully established. If peer verification was not successful
2170 the chain may be incomplete, invalid, or None.
2171
2172 :return: A list of X509 instances giving the peer's verified
2173 certificate chain, or None if it does not have one.
2174
2175 .. versionadded:: 20.0
2176 """
2177 if hasattr(_lib, "SSL_get0_verified_chain"):
2178 # OpenSSL 1.1+
2179 cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2180 if cert_stack == _ffi.NULL:
2181 return None
2182
2183 return self._cert_stack_to_list(cert_stack)
2184
2185 pycert = self.get_peer_certificate()
2186 if pycert is None:
2187 return None
2188
2189 # Should never be NULL because the peer presented a certificate.
2190 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2191 _openssl_assert(cert_stack != _ffi.NULL)
2192
2193 pystore = self._context.get_cert_store()
2194 if pystore is None:
2195 return None
2196
2197 pystorectx = X509StoreContext(pystore, pycert)
2198 pystorectx._chain = cert_stack
2199 return pystorectx.get_verified_chain()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002200
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002201 def want_read(self):
2202 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002203 Checks if more data has to be read from the transport layer to complete
2204 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002205
2206 :return: True iff more data has to be read
2207 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002208 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002209
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002210 def want_write(self):
2211 """
2212 Checks if there is data to write to the transport layer to complete an
2213 operation.
2214
2215 :return: True iff there is data to write
2216 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002217 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002218
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002219 def set_accept_state(self):
2220 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002221 Set the connection to work in server mode. The handshake will be
2222 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002223
2224 :return: None
2225 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002226 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002227
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002228 def set_connect_state(self):
2229 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002230 Set the connection to work in client mode. The handshake will be
2231 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002232
2233 :return: None
2234 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002235 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002236
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002237 def get_session(self):
2238 """
2239 Returns the Session currently used.
2240
Alex Chand072cae2018-02-15 09:57:59 +00002241 :return: An instance of :class:`OpenSSL.SSL.Session` or
2242 :obj:`None` if no session exists.
2243
2244 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002245 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002246 session = _lib.SSL_get1_session(self._ssl)
2247 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002248 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002249
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002250 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002251 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002252 return pysession
2253
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002254 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002255 """
2256 Set the session to be used when the TLS/SSL connection is established.
2257
2258 :param session: A Session instance representing the session to use.
2259 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002260
2261 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002262 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002263 if not isinstance(session, Session):
2264 raise TypeError("session must be a Session instance")
2265
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002266 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002267 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002268
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002269 def _get_finished_message(self, function):
2270 """
Alex Chand072cae2018-02-15 09:57:59 +00002271 Helper to implement :meth:`get_finished` and
2272 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002273
Alex Chand072cae2018-02-15 09:57:59 +00002274 :param function: Either :data:`SSL_get_finished`: or
2275 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002276
Alex Chand072cae2018-02-15 09:57:59 +00002277 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002278 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002279 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002280 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002281 # The OpenSSL documentation says nothing about what might happen if the
2282 # count argument given is zero. Specifically, it doesn't say whether
2283 # the output buffer may be NULL in that case or not. Inspection of the
2284 # implementation reveals that it calls memcpy() unconditionally.
2285 # Section 7.1.4, paragraph 1 of the C standard suggests that
2286 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2287 # alone desirable) behavior (though it probably does on just about
2288 # every implementation...)
2289 #
2290 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2291 # one might expect) for the initial call so as to be safe against this
2292 # potentially undefined behavior.
2293 empty = _ffi.new("char[]", 0)
2294 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002295 if size == 0:
2296 # No Finished message so far.
2297 return None
2298
Cory Benfielde62840e2016-11-28 12:17:08 +00002299 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002300 function(self._ssl, buf, size)
2301 return _ffi.buffer(buf, size)[:]
2302
Fedor Brunner5747b932014-03-05 14:22:34 +01002303 def get_finished(self):
2304 """
Alex Chand072cae2018-02-15 09:57:59 +00002305 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002306
Alex Chand072cae2018-02-15 09:57:59 +00002307 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002308 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002309 :rtype: :class:`bytes` or :class:`NoneType`
2310
2311 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002312 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002313 return self._get_finished_message(_lib.SSL_get_finished)
2314
Fedor Brunner5747b932014-03-05 14:22:34 +01002315 def get_peer_finished(self):
2316 """
Alex Chand072cae2018-02-15 09:57:59 +00002317 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002318
Alex Chand072cae2018-02-15 09:57:59 +00002319 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002320 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002321 :rtype: :class:`bytes` or :class:`NoneType`
2322
2323 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002324 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002325 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002326
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002327 def get_cipher_name(self):
2328 """
2329 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002330
Alex Chand072cae2018-02-15 09:57:59 +00002331 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002332 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002333 :rtype: :class:`unicode` or :class:`NoneType`
2334
2335 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002336 """
2337 cipher = _lib.SSL_get_current_cipher(self._ssl)
2338 if cipher == _ffi.NULL:
2339 return None
2340 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002341 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2342 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002343
2344 def get_cipher_bits(self):
2345 """
2346 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002347
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002348 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002349 or :obj:`None` if no connection has been established.
2350 :rtype: :class:`int` or :class:`NoneType`
2351
2352 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002353 """
2354 cipher = _lib.SSL_get_current_cipher(self._ssl)
2355 if cipher == _ffi.NULL:
2356 return None
2357 else:
2358 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2359
2360 def get_cipher_version(self):
2361 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002362 Obtain the protocol version of the currently used cipher.
2363
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002364 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002365 or :obj:`None` if no connection has been established.
2366 :rtype: :class:`unicode` or :class:`NoneType`
2367
2368 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002369 """
2370 cipher = _lib.SSL_get_current_cipher(self._ssl)
2371 if cipher == _ffi.NULL:
2372 return None
2373 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002374 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002375 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002376
Jim Shaverabff1882015-05-27 09:15:55 -04002377 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002378 """
Alex Chand072cae2018-02-15 09:57:59 +00002379 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002380
2381 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002382 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002383 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002384 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002385 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002386 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002387 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002388
Jim Shaver208438c2015-05-28 09:52:38 -04002389 def get_protocol_version(self):
2390 """
Alex Chand072cae2018-02-15 09:57:59 +00002391 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002392
Alex Chand072cae2018-02-15 09:57:59 +00002393 :returns: The TLS version of the current connection. For example,
2394 it will return ``0x769`` for connections made over TLS version 1.
2395 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002396 """
2397 version = _lib.SSL_version(self._ssl)
2398 return version
2399
Cory Benfield7907e332015-04-13 17:18:25 -04002400 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002401 def set_alpn_protos(self, protos):
2402 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002403 Specify the client's ALPN protocol list.
2404
2405 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002406
2407 :param protos: A list of the protocols to be offered to the server.
2408 This list should be a Python list of bytestrings representing the
2409 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2410 """
2411 # Take the list of protocols and join them together, prefixing them
2412 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002413 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002414 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2415 )
2416
2417 # Build a C string from the list. We don't need to save this off
2418 # because OpenSSL immediately copies the data out.
2419 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002420 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002421
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002422 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002423 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002424 """
2425 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002426
2427 :returns: A bytestring of the protocol name. If no protocol has been
2428 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002429 """
Cory Benfield12eae892014-06-07 15:42:56 +01002430 data = _ffi.new("unsigned char **")
2431 data_len = _ffi.new("unsigned int *")
2432
2433 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2434
Cory Benfielde8e9c382015-04-11 17:33:48 -04002435 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002436 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002437
Cory Benfield12eae892014-06-07 15:42:56 +01002438 return _ffi.buffer(data[0], data_len[0])[:]
2439
Cory Benfield496652a2017-01-24 11:42:56 +00002440 def request_ocsp(self):
2441 """
2442 Called to request that the server sends stapled OCSP data, if
2443 available. If this is not called on the client side then the server
2444 will not send OCSP data. Should be used in conjunction with
2445 :meth:`Context.set_ocsp_client_callback`.
2446 """
2447 rc = _lib.SSL_set_tlsext_status_type(
2448 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2449 )
2450 _openssl_assert(rc == 1)
2451
Cory Benfield12eae892014-06-07 15:42:56 +01002452
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002453# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2454# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002455_lib.SSL_library_init()