blob: 29e489a551cc078beb17de60fb9417b4aad97c80 [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
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006 def set_verify(self, mode, callback):
1007 """
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.
1016 :param callback: The Python callback to use. This should take five
1017 arguments: A Connection object, an X509 object, and three integer
1018 variables, which are in turn potential error number, error depth
1019 and return code. *callback* should return True if verification
1020 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021 :return: None
1022
1023 See SSL_CTX_set_verify(3SSL) for further details.
1024 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001025 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026 raise TypeError("mode must be an integer")
1027
1028 if not callable(callback):
1029 raise TypeError("callback must be callable")
1030
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001031 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001032 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001033 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001034
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035 def set_verify_depth(self, depth):
1036 """
Alex Chand072cae2018-02-15 09:57:59 +00001037 Set the maximum depth for the certificate chain verification that shall
1038 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039
1040 :param depth: An integer specifying the verify depth
1041 :return: None
1042 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001043 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044 raise TypeError("depth must be an integer")
1045
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001046 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001047
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001048 def get_verify_mode(self):
1049 """
Alex Chand072cae2018-02-15 09:57:59 +00001050 Retrieve the Context object's verify mode, as set by
1051 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001052
1053 :return: The verify mode
1054 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001055 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001057 def get_verify_depth(self):
1058 """
Alex Chand072cae2018-02-15 09:57:59 +00001059 Retrieve the Context object's verify depth, as set by
1060 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
1062 :return: The verify depth
1063 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001064 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066 def load_tmp_dh(self, dhfile):
1067 """
1068 Load parameters for Ephemeral Diffie-Hellman
1069
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001070 :param dhfile: The file to load EDH parameters from (``bytes`` or
1071 ``unicode``).
1072
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 :return: None
1074 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001075 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001077 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001078 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001079 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001080 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001081
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1083 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001084 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1085 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001087 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001088 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001089 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001090
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001091 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001092 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1093 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001094
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001095 :return: None
1096 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001097 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001098
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099 def set_cipher_list(self, cipher_list):
1100 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001101 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001102
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001103 See the OpenSSL manual for more information (e.g.
1104 :manpage:`ciphers(1)`).
1105
1106 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107 :return: None
1108 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001109 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001110
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001111 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001112 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001113
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001114 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001115 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001116 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001117 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1118 # ciphers even if you pass an invalid cipher. Applications (like
1119 # Twisted) have tests that depend on an error being raised if an
1120 # invalid cipher string is passed, but without the following check
1121 # for the TLS 1.3 specific cipher suites it would never error.
1122 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001123 if tmpconn.get_cipher_list() == [
1124 "TLS_AES_256_GCM_SHA384",
1125 "TLS_CHACHA20_POLY1305_SHA256",
1126 "TLS_AES_128_GCM_SHA256",
1127 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001128 raise Error(
1129 [
1130 (
Alex Gaynor03737182020-07-23 20:40:46 -04001131 "SSL routines",
1132 "SSL_CTX_set_cipher_list",
1133 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001134 ),
1135 ],
1136 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001137
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138 def set_client_ca_list(self, certificate_authorities):
1139 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001140 Set the list of preferred client certificate signers for this server
1141 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
Alex Gaynor62da94d2015-09-05 14:37:34 -04001143 This list of certificate authorities will be sent to the client when
1144 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001145
1146 :param certificate_authorities: a sequence of X509Names.
1147 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001148
1149 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001150 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001151 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001152 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001153
1154 try:
1155 for ca_name in certificate_authorities:
1156 if not isinstance(ca_name, X509Name):
1157 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001158 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001159 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001160 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001162 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001164 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001166 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001167 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001169 raise
1170
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001172
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001173 def add_client_ca(self, certificate_authority):
1174 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001175 Add the CA certificate to the list of preferred signers for this
1176 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001177
1178 The list of certificate authorities will be sent to the client when the
1179 server requests a client certificate.
1180
1181 :param certificate_authority: certificate authority's X509 certificate.
1182 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001183
1184 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001185 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001186 if not isinstance(certificate_authority, X509):
1187 raise TypeError("certificate_authority must be an X509 instance")
1188
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001189 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001190 self._context, certificate_authority._x509
1191 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001192 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001193
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001194 def set_timeout(self, timeout):
1195 """
Alex Chand072cae2018-02-15 09:57:59 +00001196 Set the timeout for newly created sessions for this Context object to
1197 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1198 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001199
Alex Chand072cae2018-02-15 09:57:59 +00001200 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201 :return: The previous session timeout
1202 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001203 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204 raise TypeError("timeout must be an integer")
1205
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001206 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001208 def get_timeout(self):
1209 """
Alex Chand072cae2018-02-15 09:57:59 +00001210 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1211 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001212
1213 :return: The session timeout
1214 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001215 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001216
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001217 def set_info_callback(self, callback):
1218 """
Alex Chand072cae2018-02-15 09:57:59 +00001219 Set the information callback to *callback*. This function will be
1220 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001221
Alex Chand072cae2018-02-15 09:57:59 +00001222 :param callback: The Python callback to use. This should take three
1223 arguments: a Connection object and two integers. The first integer
1224 specifies where in the SSL handshake the function was called, and
1225 the other the return code from a (possibly failed) internal
1226 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001227 :return: None
1228 """
Alex Gaynor03737182020-07-23 20:40:46 -04001229
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001230 @wraps(callback)
1231 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001232 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001233
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001234 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001235 "void (*)(const SSL *, int, int)", wrapper
1236 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001237 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001238
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001239 @_requires_keylog
1240 def set_keylog_callback(self, callback):
1241 """
1242 Set the TLS key logging callback to *callback*. This function will be
1243 called whenever TLS key material is generated or received, in order
1244 to allow applications to store this keying material for debugging
1245 purposes.
1246
1247 :param callback: The Python callback to use. This should take two
1248 arguments: a Connection object and a bytestring that contains
1249 the key material in the format used by NSS for its SSLKEYLOGFILE
1250 debugging output.
1251 :return: None
1252 """
1253
1254 @wraps(callback)
1255 def wrapper(ssl, line):
1256 line = _ffi.string(line)
1257 callback(Connection._reverse_mapping[ssl], line)
1258
1259 self._keylog_callback = _ffi.callback(
1260 "void (*)(const SSL *, const char *)", wrapper
1261 )
1262 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1263
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264 def get_app_data(self):
1265 """
Alex Chand072cae2018-02-15 09:57:59 +00001266 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001267
1268 :return: The application data
1269 """
1270 return self._app_data
1271
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001272 def set_app_data(self, data):
1273 """
1274 Set the application data (will be returned from get_app_data())
1275
1276 :param data: Any Python object
1277 :return: None
1278 """
1279 self._app_data = data
1280
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001281 def get_cert_store(self):
1282 """
Alex Chand072cae2018-02-15 09:57:59 +00001283 Get the certificate store for the context. This can be used to add
1284 "trusted" certificates without using the
1285 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001286
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001287 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001288 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001289 store = _lib.SSL_CTX_get_cert_store(self._context)
1290 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001291 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001292 return None
1293
1294 pystore = X509Store.__new__(X509Store)
1295 pystore._store = store
1296 return pystore
1297
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001298 def set_options(self, options):
1299 """
1300 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001301 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001302
1303 :param options: The options to add.
1304 :return: The new option bitmask.
1305 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001306 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001307 raise TypeError("options must be an integer")
1308
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001309 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001310
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001311 def set_mode(self, mode):
1312 """
Alex Chand072cae2018-02-15 09:57:59 +00001313 Add modes via bitmask. Modes set before are not cleared! This method
1314 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001315
1316 :param mode: The mode to add.
1317 :return: The new mode bitmask.
1318 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001319 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001320 raise TypeError("mode must be an integer")
1321
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001322 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001323
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001324 def set_tlsext_servername_callback(self, callback):
1325 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001326 Specify a callback function to be called when clients specify a server
1327 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001328
1329 :param callback: The callback function. It will be invoked with one
1330 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001331
1332 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001333 """
Alex Gaynor03737182020-07-23 20:40:46 -04001334
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001335 @wraps(callback)
1336 def wrapper(ssl, alert, arg):
1337 callback(Connection._reverse_mapping[ssl])
1338 return 0
1339
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001340 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001341 "int (*)(SSL *, int *, void *)", wrapper
1342 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001343 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001344 self._context, self._tlsext_servername_callback
1345 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001346
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001347 def set_tlsext_use_srtp(self, profiles):
1348 """
1349 Enable support for negotiating SRTP keying material.
1350
1351 :param bytes profiles: A colon delimited list of protection profile
1352 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1353 :return: None
1354 """
1355 if not isinstance(profiles, bytes):
1356 raise TypeError("profiles must be a byte string.")
1357
1358 _openssl_assert(
1359 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1360 )
1361
Cory Benfield7907e332015-04-13 17:18:25 -04001362 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001363 def set_alpn_protos(self, protos):
1364 """
Alex Chand072cae2018-02-15 09:57:59 +00001365 Specify the protocols that the client is prepared to speak after the
1366 TLS connection has been negotiated using Application Layer Protocol
1367 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001368
1369 :param protos: A list of the protocols to be offered to the server.
1370 This list should be a Python list of bytestrings representing the
1371 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1372 """
1373 # Take the list of protocols and join them together, prefixing them
1374 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001375 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001376 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1377 )
1378
1379 # Build a C string from the list. We don't need to save this off
1380 # because OpenSSL immediately copies the data out.
1381 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001382 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001383
Cory Benfield7907e332015-04-13 17:18:25 -04001384 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001385 def set_alpn_select_callback(self, callback):
1386 """
Alex Chand072cae2018-02-15 09:57:59 +00001387 Specify a callback function that will be called on the server when a
1388 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001389
1390 :param callback: The callback function. It will be invoked with two
1391 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001392 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1393 one of those bytestrings to indicate the chosen protocol, the
1394 empty bytestring to terminate the TLS connection, or the
1395 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1396 protocol was selected, but that the connection should not be
1397 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001398 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001399 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001400 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001401 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001402 self._context, self._alpn_select_callback, _ffi.NULL
1403 )
Cory Benfield12eae892014-06-07 15:42:56 +01001404
Cory Benfield496652a2017-01-24 11:42:56 +00001405 def _set_ocsp_callback(self, helper, data):
1406 """
1407 This internal helper does the common work for
1408 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1409 almost all of it.
1410 """
1411 self._ocsp_helper = helper
1412 self._ocsp_callback = helper.callback
1413 if data is None:
1414 self._ocsp_data = _ffi.NULL
1415 else:
1416 self._ocsp_data = _ffi.new_handle(data)
1417
1418 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1419 self._context, self._ocsp_callback
1420 )
1421 _openssl_assert(rc == 1)
1422 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1423 _openssl_assert(rc == 1)
1424
1425 def set_ocsp_server_callback(self, callback, data=None):
1426 """
1427 Set a callback to provide OCSP data to be stapled to the TLS handshake
1428 on the server side.
1429
1430 :param callback: The callback function. It will be invoked with two
1431 arguments: the Connection, and the optional arbitrary data you have
1432 provided. The callback must return a bytestring that contains the
1433 OCSP data to staple to the handshake. If no OCSP data is available
1434 for this connection, return the empty bytestring.
1435 :param data: Some opaque data that will be passed into the callback
1436 function when called. This can be used to avoid needing to do
1437 complex data lookups or to keep track of what context is being
1438 used. This parameter is optional.
1439 """
1440 helper = _OCSPServerCallbackHelper(callback)
1441 self._set_ocsp_callback(helper, data)
1442
1443 def set_ocsp_client_callback(self, callback, data=None):
1444 """
1445 Set a callback to validate OCSP data stapled to the TLS handshake on
1446 the client side.
1447
1448 :param callback: The callback function. It will be invoked with three
1449 arguments: the Connection, a bytestring containing the stapled OCSP
1450 assertion, and the optional arbitrary data you have provided. The
1451 callback must return a boolean that indicates the result of
1452 validating the OCSP data: ``True`` if the OCSP data is valid and
1453 the certificate can be trusted, or ``False`` if either the OCSP
1454 data is invalid or the certificate has been revoked.
1455 :param data: Some opaque data that will be passed into the callback
1456 function when called. This can be used to avoid needing to do
1457 complex data lookups or to keep track of what context is being
1458 used. This parameter is optional.
1459 """
1460 helper = _OCSPClientCallbackHelper(callback)
1461 self._set_ocsp_callback(helper, data)
1462
Alex Chanc6077062016-11-18 13:53:39 +00001463
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001464class Connection(object):
1465 """
1466 """
Alex Gaynor03737182020-07-23 20:40:46 -04001467
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001468 _reverse_mapping = WeakValueDictionary()
1469
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470 def __init__(self, context, socket=None):
1471 """
1472 Create a new Connection object, using the given OpenSSL.SSL.Context
1473 instance and socket.
1474
1475 :param context: An SSL Context to use for this connection
1476 :param socket: The socket to use for transport layer
1477 """
1478 if not isinstance(context, Context):
1479 raise TypeError("context must be a Context instance")
1480
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001481 ssl = _lib.SSL_new(context._context)
1482 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001483 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1484 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1485 # even though there is still data on the underlying transport.
1486 # See https://github.com/openssl/openssl/issues/6234 for more details.
1487 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001488 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001489 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490
Cory Benfield12eae892014-06-07 15:42:56 +01001491 # References to strings used for Application Layer Protocol
1492 # Negotiation. These strings get copied at some point but it's well
1493 # after the callback returns, so we have to hang them somewhere to
1494 # avoid them getting freed.
1495 self._alpn_select_callback_args = None
1496
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001497 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498
1499 if socket is None:
1500 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001501 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001502 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001503 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504
Alex Gaynora829e902016-06-04 18:16:01 -07001505 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1506 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001508 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001509 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001510 self._into_ssl = None
1511 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001513 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001514 self._ssl, _asFileDescriptor(self._socket)
1515 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001516 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001518 def __getattr__(self, name):
1519 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001520 Look up attributes on the wrapped socket object if they are not found
1521 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001522 """
kjav0b66fa12015-09-02 11:51:26 +01001523 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001524 raise AttributeError(
1525 "'%s' object has no attribute '%s'"
1526 % (self.__class__.__name__, name)
1527 )
kjav0b66fa12015-09-02 11:51:26 +01001528 else:
1529 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001530
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001531 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001532 if self._context._verify_helper is not None:
1533 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001534 if self._context._alpn_select_helper is not None:
1535 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001536 if self._context._ocsp_helper is not None:
1537 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001538
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001539 error = _lib.SSL_get_error(ssl, result)
1540 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001541 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001543 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001544 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001545 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001546 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001547 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001548 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001549 elif error == _lib.SSL_ERROR_SYSCALL:
1550 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001552 if platform == "win32":
1553 errno = _ffi.getwinerror()[0]
1554 else:
1555 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001556
1557 if errno != 0:
1558 raise SysCallError(errno, errorcode.get(errno))
1559 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001560 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001561 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001562 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001563 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001564 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001566 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001568 def get_context(self):
1569 """
Alex Chand072cae2018-02-15 09:57:59 +00001570 Retrieve the :class:`Context` object associated with this
1571 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001575 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576 """
Alex Chand072cae2018-02-15 09:57:59 +00001577 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578
Alex Chand072cae2018-02-15 09:57:59 +00001579 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582 if not isinstance(context, Context):
1583 raise TypeError("context must be a Context instance")
1584
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001585 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 self._context = context
1587
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 def get_servername(self):
1589 """
1590 Retrieve the servername extension value if provided in the client hello
1591 message, or None if there wasn't one.
1592
Alex Chand072cae2018-02-15 09:57:59 +00001593 :return: A byte string giving the server name or :data:`None`.
1594
1595 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001597 name = _lib.SSL_get_servername(
1598 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1599 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001600 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001601 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001602
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001606 """
1607 Set the value of the servername extension to send in the client hello.
1608
1609 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001610
1611 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 if not isinstance(name, bytes):
1614 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001615 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001616 raise TypeError("name must not contain NUL byte")
1617
1618 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001619 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001620
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001621 def pending(self):
1622 """
Alex Chand072cae2018-02-15 09:57:59 +00001623 Get the number of bytes that can be safely read from the SSL buffer
1624 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625
1626 :return: The number of bytes available in the receive buffer.
1627 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001630 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631 """
1632 Send data on the connection. NOTE: If you get one of the WantRead,
1633 WantWrite or WantX509Lookup exceptions on this, you have to call the
1634 method again with the SAME buffer.
1635
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001636 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637 :param flags: (optional) Included for compatibility with the socket
1638 API, the value is ignored
1639 :return: The number of bytes written
1640 """
Abraham Martine82326c2015-02-04 10:18:10 +00001641 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001642 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001643
Daniel Holth079c9632019-11-17 22:45:52 -05001644 with _from_buffer(buf) as data:
1645 # check len(buf) instead of len(data) for testability
1646 if len(buf) > 2147483647:
1647 raise ValueError(
1648 "Cannot send more than 2**31-1 bytes at once."
1649 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001650
Daniel Holth079c9632019-11-17 22:45:52 -05001651 result = _lib.SSL_write(self._ssl, data, len(data))
1652 self._raise_ssl_error(self._ssl, result)
1653
1654 return result
1655
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656 write = send
1657
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001659 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001660 Send "all" data on the connection. This calls send() repeatedly until
1661 all data is sent. If an error occurs, it's impossible to tell how much
1662 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001664 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 :param flags: (optional) Included for compatibility with the socket
1666 API, the value is ignored
1667 :return: The number of bytes written
1668 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001669 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001670
Daniel Holth079c9632019-11-17 22:45:52 -05001671 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672
Daniel Holth079c9632019-11-17 22:45:52 -05001673 left_to_send = len(buf)
1674 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675
Daniel Holth079c9632019-11-17 22:45:52 -05001676 while left_to_send:
1677 # SSL_write's num arg is an int,
1678 # so we cannot send more than 2**31-1 bytes at once.
1679 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001680 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001681 )
1682 self._raise_ssl_error(self._ssl, result)
1683 total_sent += result
1684 left_to_send -= result
1685
1686 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001688 def recv(self, bufsiz, flags=None):
1689 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001690 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001691
1692 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001693 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1694 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001695 :return: The string read from the Connection
1696 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001697 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001698 if flags is not None and flags & socket.MSG_PEEK:
1699 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1700 else:
1701 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001702 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001704
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705 read = recv
1706
Cory Benfield62d10332014-06-15 10:03:41 +01001707 def recv_into(self, buffer, nbytes=None, flags=None):
1708 """
Alex Chand072cae2018-02-15 09:57:59 +00001709 Receive data on the connection and copy it directly into the provided
1710 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001711
1712 :param buffer: The buffer to copy into.
1713 :param nbytes: (optional) The maximum number of bytes to read into the
1714 buffer. If not present, defaults to the size of the buffer. If
1715 larger than the size of the buffer, is reduced to the size of the
1716 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001717 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1718 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001719 :return: The number of bytes read into the buffer.
1720 """
1721 if nbytes is None:
1722 nbytes = len(buffer)
1723 else:
1724 nbytes = min(nbytes, len(buffer))
1725
1726 # We need to create a temporary buffer. This is annoying, it would be
1727 # better if we could pass memoryviews straight into the SSL_read call,
1728 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001729 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001730 if flags is not None and flags & socket.MSG_PEEK:
1731 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1732 else:
1733 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001734 self._raise_ssl_error(self._ssl, result)
1735
1736 # This strange line is all to avoid a memory copy. The buffer protocol
1737 # should allow us to assign a CFFI buffer to the LHS of this line, but
1738 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001739 # wrap it in a memoryview.
1740 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001741
1742 return result
1743
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001744 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 if _lib.BIO_should_retry(bio):
1746 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001747 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001749 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001750 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001751 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001752 # TODO: This is untested. I think io_special means the socket
1753 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001754 raise ValueError("BIO_should_io_special")
1755 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001756 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001757 raise ValueError("unknown bio failure")
1758 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001759 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001760 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001762 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001763 """
Alex Chand072cae2018-02-15 09:57:59 +00001764 If the Connection was created with a memory BIO, this method can be
1765 used to read bytes from the write end of that memory BIO. Many
1766 Connection methods will add bytes which must be read in this manner or
1767 the buffer will eventually fill up and the Connection will be able to
1768 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001769
1770 :param bufsiz: The maximum number of bytes to read
1771 :return: The string read.
1772 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001773 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001774 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001775
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001776 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001777 raise TypeError("bufsiz must be an integer")
1778
Cory Benfielde62840e2016-11-28 12:17:08 +00001779 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001780 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001781 if result <= 0:
1782 self._handle_bio_errors(self._from_ssl, result)
1783
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001784 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001785
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001786 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001787 """
Alex Chand072cae2018-02-15 09:57:59 +00001788 If the Connection was created with a memory BIO, this method can be
1789 used to add bytes to the read end of that memory BIO. The Connection
1790 can then read the bytes (for example, in response to a call to
1791 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792
1793 :param buf: The string to put into the memory BIO.
1794 :return: The number of bytes written
1795 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001796 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001797
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001798 if self._into_ssl is None:
1799 raise TypeError("Connection sock was not None")
1800
Daniel Holth079c9632019-11-17 22:45:52 -05001801 with _from_buffer(buf) as data:
1802 result = _lib.BIO_write(self._into_ssl, data, len(data))
1803 if result <= 0:
1804 self._handle_bio_errors(self._into_ssl, result)
1805 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001806
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001807 def renegotiate(self):
1808 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001809 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001810
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001811 :return: True if the renegotiation can be started, False otherwise
1812 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001813 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001814 if not self.renegotiate_pending():
1815 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1816 return True
1817 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001818
1819 def do_handshake(self):
1820 """
Alex Chand072cae2018-02-15 09:57:59 +00001821 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001822 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001823 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001824
1825 :return: None.
1826 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001827 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001828 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001829
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001830 def renegotiate_pending(self):
1831 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001832 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001833 a renegotiation is finished.
1834
1835 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001836 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001838 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839
1840 def total_renegotiations(self):
1841 """
1842 Find out the total number of renegotiations.
1843
1844 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001845 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001846 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001847 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001849 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001850 """
Alex Chand072cae2018-02-15 09:57:59 +00001851 Call the :meth:`connect` method of the underlying socket and set up SSL
1852 on the socket, using the :class:`Context` object supplied to this
1853 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001854
1855 :param addr: A remote address
1856 :return: What the socket's connect method returns
1857 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001858 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001859 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001861 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001862 """
Alex Chand072cae2018-02-15 09:57:59 +00001863 Call the :meth:`connect_ex` method of the underlying socket and set up
1864 SSL on the socket, using the Context object supplied to this Connection
1865 object at creation. Note that if the :meth:`connect_ex` method of the
1866 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867
1868 :param addr: A remove address
1869 :return: What the socket's connect_ex method returns
1870 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001871 connect_ex = self._socket.connect_ex
1872 self.set_connect_state()
1873 return connect_ex(addr)
1874
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875 def accept(self):
1876 """
Alex Chand072cae2018-02-15 09:57:59 +00001877 Call the :meth:`accept` method of the underlying socket and set up SSL
1878 on the returned socket, using the Context object supplied to this
1879 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880
Alex Chand072cae2018-02-15 09:57:59 +00001881 :return: A *(conn, addr)* pair where *conn* is the new
1882 :class:`Connection` object created, and *address* is as returned by
1883 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001884 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001885 client, addr = self._socket.accept()
1886 conn = Connection(self._context, client)
1887 conn.set_accept_state()
1888 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001890 def bio_shutdown(self):
1891 """
Alex Chand072cae2018-02-15 09:57:59 +00001892 If the Connection was created with a memory BIO, this method can be
1893 used to indicate that *end of file* has been reached on the read end of
1894 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001895
1896 :return: None
1897 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001898 if self._from_ssl is None:
1899 raise TypeError("Connection sock was not None")
1900
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001901 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001902
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001903 def shutdown(self):
1904 """
Alex Chand072cae2018-02-15 09:57:59 +00001905 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906
1907 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001908 have sent closure alerts), False otherwise (in which case you
1909 call :meth:`recv` or :meth:`send` when the connection becomes
1910 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001912 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001914 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 else:
1918 return False
1919
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001920 def get_cipher_list(self):
1921 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001922 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001924 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001925 """
1926 ciphers = []
1927 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001928 result = _lib.SSL_get_cipher_list(self._ssl, i)
1929 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001931 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932 return ciphers
1933
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934 def get_client_ca_list(self):
1935 """
1936 Get CAs whose certificates are suggested for client authentication.
1937
Alex Chand072cae2018-02-15 09:57:59 +00001938 :return: If this is a server connection, the list of certificate
1939 authorities that will be sent or has been sent to the client, as
1940 controlled by this :class:`Connection`'s :class:`Context`.
1941
1942 If this is a client connection, the list will be empty until the
1943 connection with the server is established.
1944
1945 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001946 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001947 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1948 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001949 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 return []
1951
1952 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1954 name = _lib.sk_X509_NAME_value(ca_names, i)
1955 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001956 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957
1958 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001959 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001960 result.append(pyname)
1961 return result
1962
Aykee7f33452018-05-16 19:18:16 +02001963 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001965 The makefile() method is not implemented, since there is no dup
1966 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001967
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001968 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001969 """
Alex Gaynor83284952015-09-05 10:43:30 -04001970 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001971 "Cannot make file object of OpenSSL.SSL.Connection"
1972 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
1974 def get_app_data(self):
1975 """
Alex Chand072cae2018-02-15 09:57:59 +00001976 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001977
1978 :return: The application data
1979 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001981
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001982 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983 """
1984 Set application data
1985
Alex Chand072cae2018-02-15 09:57:59 +00001986 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001987 :return: None
1988 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 self._app_data = data
1990
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001991 def get_shutdown(self):
1992 """
Alex Chand072cae2018-02-15 09:57:59 +00001993 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994
Alex Gaynor62da94d2015-09-05 14:37:34 -04001995 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1996 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001998 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 """
Alex Chand072cae2018-02-15 09:57:59 +00002002 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003
Alex Chand072cae2018-02-15 09:57:59 +00002004 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005 :return: None
2006 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002007 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002008 raise TypeError("state must be an integer")
2009
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002010 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002011
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002012 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002014 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015
2016 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002017 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018 """
kjavc704a2e2015-09-07 12:12:27 +01002019 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020
2021 def server_random(self):
2022 """
Alex Chand072cae2018-02-15 09:57:59 +00002023 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024
2025 :return: A string representing the state
2026 """
Alex Gaynor93603062016-06-01 20:13:09 -07002027 session = _lib.SSL_get_session(self._ssl)
2028 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002029 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002030 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002031 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002032 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002033 _lib.SSL_get_server_random(self._ssl, outp, length)
2034 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002035
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036 def client_random(self):
2037 """
Alex Chand072cae2018-02-15 09:57:59 +00002038 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002039
2040 :return: A string representing the state
2041 """
Alex Gaynor93603062016-06-01 20:13:09 -07002042 session = _lib.SSL_get_session(self._ssl)
2043 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002044 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002045
2046 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002047 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002048 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002049 _lib.SSL_get_client_random(self._ssl, outp, length)
2050 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052 def master_key(self):
2053 """
Alex Chand072cae2018-02-15 09:57:59 +00002054 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055
2056 :return: A string representing the state
2057 """
Alex Gaynor93603062016-06-01 20:13:09 -07002058 session = _lib.SSL_get_session(self._ssl)
2059 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002060 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002061
2062 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002063 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002064 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002065 _lib.SSL_SESSION_get_master_key(session, outp, length)
2066 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002067
Paul Kehrerbdb76392017-12-01 04:54:32 +08002068 def export_keying_material(self, label, olen, context=None):
2069 """
2070 Obtain keying material for application use.
2071
Alex Chand072cae2018-02-15 09:57:59 +00002072 :param: label - a disambiguating label string as described in RFC 5705
2073 :param: olen - the length of the exported key material in bytes
2074 :param: context - a per-association context value
2075 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002076 """
2077 outp = _no_zero_allocator("unsigned char[]", olen)
2078 context_buf = _ffi.NULL
2079 context_len = 0
2080 use_context = 0
2081 if context is not None:
2082 context_buf = context
2083 context_len = len(context)
2084 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002085 success = _lib.SSL_export_keying_material(
2086 self._ssl,
2087 outp,
2088 olen,
2089 label,
2090 len(label),
2091 context_buf,
2092 context_len,
2093 use_context,
2094 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002095 _openssl_assert(success == 1)
2096 return _ffi.buffer(outp, olen)[:]
2097
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002098 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002099 """
Alex Chand072cae2018-02-15 09:57:59 +00002100 Call the :meth:`shutdown` method of the underlying socket.
2101 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
2103 :return: What the socket's shutdown() method returns
2104 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002105 return self._socket.shutdown(*args, **kwargs)
2106
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002107 def get_certificate(self):
2108 """
2109 Retrieve the local certificate (if any)
2110
2111 :return: The local certificate
2112 """
2113 cert = _lib.SSL_get_certificate(self._ssl)
2114 if cert != _ffi.NULL:
2115 _lib.X509_up_ref(cert)
2116 return X509._from_raw_x509_ptr(cert)
2117 return None
2118
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002119 def get_peer_certificate(self):
2120 """
2121 Retrieve the other side's certificate (if any)
2122
2123 :return: The peer's certificate
2124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002125 cert = _lib.SSL_get_peer_certificate(self._ssl)
2126 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002127 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002128 return None
2129
Shane Harvey33c54992020-08-05 16:48:51 -07002130 @staticmethod
2131 def _cert_stack_to_list(cert_stack):
2132 """
2133 Internal helper to convert a STACK_OF(X509) to a list of X509
2134 instances.
2135 """
2136 result = []
2137 for i in range(_lib.sk_X509_num(cert_stack)):
2138 cert = _lib.sk_X509_value(cert_stack, i)
2139 _openssl_assert(cert != _ffi.NULL)
2140 res = _lib.X509_up_ref(cert)
2141 _openssl_assert(res >= 1)
2142 pycert = X509._from_raw_x509_ptr(cert)
2143 result.append(pycert)
2144 return result
2145
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002146 def get_peer_cert_chain(self):
2147 """
2148 Retrieve the other side's certificate (if any)
2149
2150 :return: A list of X509 instances giving the peer's certificate chain,
2151 or None if it does not have one.
2152 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002153 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2154 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002155 return None
2156
Shane Harvey33c54992020-08-05 16:48:51 -07002157 return self._cert_stack_to_list(cert_stack)
2158
2159 def get_verified_chain(self):
2160 """
2161 Retrieve the verified certificate chain of the peer including the
2162 peer's end entity certificate. It must be called after a session has
2163 been successfully established. If peer verification was not successful
2164 the chain may be incomplete, invalid, or None.
2165
2166 :return: A list of X509 instances giving the peer's verified
2167 certificate chain, or None if it does not have one.
2168
2169 .. versionadded:: 20.0
2170 """
2171 if hasattr(_lib, "SSL_get0_verified_chain"):
2172 # OpenSSL 1.1+
2173 cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2174 if cert_stack == _ffi.NULL:
2175 return None
2176
2177 return self._cert_stack_to_list(cert_stack)
2178
2179 pycert = self.get_peer_certificate()
2180 if pycert is None:
2181 return None
2182
2183 # Should never be NULL because the peer presented a certificate.
2184 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2185 _openssl_assert(cert_stack != _ffi.NULL)
2186
2187 pystore = self._context.get_cert_store()
2188 if pystore is None:
2189 return None
2190
2191 pystorectx = X509StoreContext(pystore, pycert)
2192 pystorectx._chain = cert_stack
2193 return pystorectx.get_verified_chain()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002194
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002195 def want_read(self):
2196 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002197 Checks if more data has to be read from the transport layer to complete
2198 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002199
2200 :return: True iff more data has to be read
2201 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002202 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002203
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002204 def want_write(self):
2205 """
2206 Checks if there is data to write to the transport layer to complete an
2207 operation.
2208
2209 :return: True iff there is data to write
2210 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002211 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002212
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002213 def set_accept_state(self):
2214 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002215 Set the connection to work in server mode. The handshake will be
2216 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002217
2218 :return: None
2219 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002220 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002221
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002222 def set_connect_state(self):
2223 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002224 Set the connection to work in client mode. The handshake will be
2225 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002226
2227 :return: None
2228 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002229 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002230
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002231 def get_session(self):
2232 """
2233 Returns the Session currently used.
2234
Alex Chand072cae2018-02-15 09:57:59 +00002235 :return: An instance of :class:`OpenSSL.SSL.Session` or
2236 :obj:`None` if no session exists.
2237
2238 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002239 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002240 session = _lib.SSL_get1_session(self._ssl)
2241 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002242 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002243
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002244 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002245 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002246 return pysession
2247
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002248 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002249 """
2250 Set the session to be used when the TLS/SSL connection is established.
2251
2252 :param session: A Session instance representing the session to use.
2253 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002254
2255 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002256 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002257 if not isinstance(session, Session):
2258 raise TypeError("session must be a Session instance")
2259
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002260 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002261 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002262
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002263 def _get_finished_message(self, function):
2264 """
Alex Chand072cae2018-02-15 09:57:59 +00002265 Helper to implement :meth:`get_finished` and
2266 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002267
Alex Chand072cae2018-02-15 09:57:59 +00002268 :param function: Either :data:`SSL_get_finished`: or
2269 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002270
Alex Chand072cae2018-02-15 09:57:59 +00002271 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002272 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002273 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002274 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002275 # The OpenSSL documentation says nothing about what might happen if the
2276 # count argument given is zero. Specifically, it doesn't say whether
2277 # the output buffer may be NULL in that case or not. Inspection of the
2278 # implementation reveals that it calls memcpy() unconditionally.
2279 # Section 7.1.4, paragraph 1 of the C standard suggests that
2280 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2281 # alone desirable) behavior (though it probably does on just about
2282 # every implementation...)
2283 #
2284 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2285 # one might expect) for the initial call so as to be safe against this
2286 # potentially undefined behavior.
2287 empty = _ffi.new("char[]", 0)
2288 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002289 if size == 0:
2290 # No Finished message so far.
2291 return None
2292
Cory Benfielde62840e2016-11-28 12:17:08 +00002293 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002294 function(self._ssl, buf, size)
2295 return _ffi.buffer(buf, size)[:]
2296
Fedor Brunner5747b932014-03-05 14:22:34 +01002297 def get_finished(self):
2298 """
Alex Chand072cae2018-02-15 09:57:59 +00002299 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002300
Alex Chand072cae2018-02-15 09:57:59 +00002301 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002302 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002303 :rtype: :class:`bytes` or :class:`NoneType`
2304
2305 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002306 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002307 return self._get_finished_message(_lib.SSL_get_finished)
2308
Fedor Brunner5747b932014-03-05 14:22:34 +01002309 def get_peer_finished(self):
2310 """
Alex Chand072cae2018-02-15 09:57:59 +00002311 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002312
Alex Chand072cae2018-02-15 09:57:59 +00002313 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002314 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002315 :rtype: :class:`bytes` or :class:`NoneType`
2316
2317 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002318 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002319 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002320
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002321 def get_cipher_name(self):
2322 """
2323 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002324
Alex Chand072cae2018-02-15 09:57:59 +00002325 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002326 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002327 :rtype: :class:`unicode` or :class:`NoneType`
2328
2329 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002330 """
2331 cipher = _lib.SSL_get_current_cipher(self._ssl)
2332 if cipher == _ffi.NULL:
2333 return None
2334 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002335 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2336 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002337
2338 def get_cipher_bits(self):
2339 """
2340 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002341
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002342 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002343 or :obj:`None` if no connection has been established.
2344 :rtype: :class:`int` or :class:`NoneType`
2345
2346 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002347 """
2348 cipher = _lib.SSL_get_current_cipher(self._ssl)
2349 if cipher == _ffi.NULL:
2350 return None
2351 else:
2352 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2353
2354 def get_cipher_version(self):
2355 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002356 Obtain the protocol version of the currently used cipher.
2357
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002358 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002359 or :obj:`None` if no connection has been established.
2360 :rtype: :class:`unicode` or :class:`NoneType`
2361
2362 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002363 """
2364 cipher = _lib.SSL_get_current_cipher(self._ssl)
2365 if cipher == _ffi.NULL:
2366 return None
2367 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002368 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002369 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002370
Jim Shaverabff1882015-05-27 09:15:55 -04002371 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002372 """
Alex Chand072cae2018-02-15 09:57:59 +00002373 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002374
2375 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002376 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002377 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002378 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002379 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002380 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002381 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002382
Jim Shaver208438c2015-05-28 09:52:38 -04002383 def get_protocol_version(self):
2384 """
Alex Chand072cae2018-02-15 09:57:59 +00002385 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002386
Alex Chand072cae2018-02-15 09:57:59 +00002387 :returns: The TLS version of the current connection. For example,
2388 it will return ``0x769`` for connections made over TLS version 1.
2389 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002390 """
2391 version = _lib.SSL_version(self._ssl)
2392 return version
2393
Cory Benfield7907e332015-04-13 17:18:25 -04002394 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002395 def set_alpn_protos(self, protos):
2396 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002397 Specify the client's ALPN protocol list.
2398
2399 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002400
2401 :param protos: A list of the protocols to be offered to the server.
2402 This list should be a Python list of bytestrings representing the
2403 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2404 """
2405 # Take the list of protocols and join them together, prefixing them
2406 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002407 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002408 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2409 )
2410
2411 # Build a C string from the list. We don't need to save this off
2412 # because OpenSSL immediately copies the data out.
2413 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002414 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002415
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002416 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002417 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002418 """
2419 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002420
2421 :returns: A bytestring of the protocol name. If no protocol has been
2422 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002423 """
Cory Benfield12eae892014-06-07 15:42:56 +01002424 data = _ffi.new("unsigned char **")
2425 data_len = _ffi.new("unsigned int *")
2426
2427 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2428
Cory Benfielde8e9c382015-04-11 17:33:48 -04002429 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002430 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002431
Cory Benfield12eae892014-06-07 15:42:56 +01002432 return _ffi.buffer(data[0], data_len[0])[:]
2433
Cory Benfield496652a2017-01-24 11:42:56 +00002434 def request_ocsp(self):
2435 """
2436 Called to request that the server sends stapled OCSP data, if
2437 available. If this is not called on the client side then the server
2438 will not send OCSP data. Should be used in conjunction with
2439 :meth:`Context.set_ocsp_client_callback`.
2440 """
2441 rc = _lib.SSL_set_tlsext_status_type(
2442 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2443 )
2444 _openssl_assert(rc == 1)
2445
Cory Benfield12eae892014-06-07 15:42:56 +01002446
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002447# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2448# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002449_lib.SSL_library_init()