blob: bbb721c036e9a985db32d62dbcd791f73d446863 [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 Gaynor04882142020-08-26 22:50:40 -0400975 _lib.SSL_CTX_set_session_id_context(
976 self._context,
977 buf,
978 len(buf),
979 )
Alex Gaynor03737182020-07-23 20:40:46 -0400980 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100981 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800982
983 def set_session_cache_mode(self, mode):
984 """
Alex Chand072cae2018-02-15 09:57:59 +0000985 Set the behavior of the session cache used by all connections using
986 this Context. The previously set mode is returned. See
987 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800988
989 :param mode: One or more of the SESS_CACHE_* flags (combine using
990 bitwise or)
991 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000992
993 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500995 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996 raise TypeError("mode must be an integer")
997
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500998 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001000 def get_session_cache_mode(self):
1001 """
Alex Chand072cae2018-02-15 09:57:59 +00001002 Get the current session cache mode.
1003
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001004 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001005
1006 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001007 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001008 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009
Maximilian Hils79b9c792020-08-08 03:08:17 +02001010 def set_verify(self, mode, callback=None):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011 """
Alex Chand072cae2018-02-15 09:57:59 +00001012 et the verification flags for this Context object to *mode* and specify
1013 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014
Alex Chand072cae2018-02-15 09:57:59 +00001015 :param mode: The verify mode, this should be one of
1016 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1017 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1018 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1019 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
Maximilian Hils79b9c792020-08-08 03:08:17 +02001020 :param callback: The optional Python verification callback to use.
1021 This should take five arguments: A Connection object, an X509
1022 object, and three integer variables, which are in turn potential
1023 error number, error depth and return code. *callback* should
1024 return True if verification passes and False otherwise.
1025 If omitted, OpenSSL's default verification is used.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026 :return: None
1027
1028 See SSL_CTX_set_verify(3SSL) for further details.
1029 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001030 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001031 raise TypeError("mode must be an integer")
1032
Maximilian Hils79b9c792020-08-08 03:08:17 +02001033 if callback is None:
1034 self._verify_helper = None
1035 self._verify_callback = None
1036 _lib.SSL_CTX_set_verify(self._context, mode, _ffi.NULL)
1037 else:
1038 if not callable(callback):
1039 raise TypeError("callback must be callable")
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001040
Maximilian Hils79b9c792020-08-08 03:08:17 +02001041 self._verify_helper = _VerifyHelper(callback)
1042 self._verify_callback = self._verify_helper.callback
1043 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045 def set_verify_depth(self, depth):
1046 """
Alex Chand072cae2018-02-15 09:57:59 +00001047 Set the maximum depth for the certificate chain verification that shall
1048 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001049
1050 :param depth: An integer specifying the verify depth
1051 :return: None
1052 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001053 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054 raise TypeError("depth must be an integer")
1055
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001056 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001057
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001058 def get_verify_mode(self):
1059 """
Alex Chand072cae2018-02-15 09:57:59 +00001060 Retrieve the Context object's verify mode, as set by
1061 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001062
1063 :return: The verify mode
1064 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001065 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067 def get_verify_depth(self):
1068 """
Alex Chand072cae2018-02-15 09:57:59 +00001069 Retrieve the Context object's verify depth, as set by
1070 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001071
1072 :return: The verify depth
1073 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076 def load_tmp_dh(self, dhfile):
1077 """
1078 Load parameters for Ephemeral Diffie-Hellman
1079
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001080 :param dhfile: The file to load EDH parameters from (``bytes`` or
1081 ``unicode``).
1082
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083 :return: None
1084 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001085 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001087 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001089 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001092 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1093 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001094 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1095 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001097 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001098 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001099 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001100
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001101 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001102 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1103 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001104
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001105 :return: None
1106 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001107 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001108
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 def set_cipher_list(self, cipher_list):
1110 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001111 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001112
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001113 See the OpenSSL manual for more information (e.g.
1114 :manpage:`ciphers(1)`).
1115
1116 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001117 :return: None
1118 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001119 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001120
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001121 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001122 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001124 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001125 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001126 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001127 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1128 # ciphers even if you pass an invalid cipher. Applications (like
1129 # Twisted) have tests that depend on an error being raised if an
1130 # invalid cipher string is passed, but without the following check
1131 # for the TLS 1.3 specific cipher suites it would never error.
1132 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001133 if tmpconn.get_cipher_list() == [
1134 "TLS_AES_256_GCM_SHA384",
1135 "TLS_CHACHA20_POLY1305_SHA256",
1136 "TLS_AES_128_GCM_SHA256",
1137 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001138 raise Error(
1139 [
1140 (
Alex Gaynor03737182020-07-23 20:40:46 -04001141 "SSL routines",
1142 "SSL_CTX_set_cipher_list",
1143 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001144 ),
1145 ],
1146 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001147
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001148 def set_client_ca_list(self, certificate_authorities):
1149 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001150 Set the list of preferred client certificate signers for this server
1151 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001152
Alex Gaynor62da94d2015-09-05 14:37:34 -04001153 This list of certificate authorities will be sent to the client when
1154 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001155
1156 :param certificate_authorities: a sequence of X509Names.
1157 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001158
1159 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001160 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001162 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001163
1164 try:
1165 for ca_name in certificate_authorities:
1166 if not isinstance(ca_name, X509Name):
1167 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001168 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001169 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001170 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001172 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001174 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001175 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001176 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001177 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001178 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001179 raise
1180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001182
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183 def add_client_ca(self, certificate_authority):
1184 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001185 Add the CA certificate to the list of preferred signers for this
1186 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001187
1188 The list of certificate authorities will be sent to the client when the
1189 server requests a client certificate.
1190
1191 :param certificate_authority: certificate authority's X509 certificate.
1192 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001193
1194 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001195 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001196 if not isinstance(certificate_authority, X509):
1197 raise TypeError("certificate_authority must be an X509 instance")
1198
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001199 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001200 self._context, certificate_authority._x509
1201 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001202 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001203
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204 def set_timeout(self, timeout):
1205 """
Alex Chand072cae2018-02-15 09:57:59 +00001206 Set the timeout for newly created sessions for this Context object to
1207 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1208 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001209
Alex Chand072cae2018-02-15 09:57:59 +00001210 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001211 :return: The previous session timeout
1212 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001213 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001214 raise TypeError("timeout must be an integer")
1215
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001216 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001217
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001218 def get_timeout(self):
1219 """
Alex Chand072cae2018-02-15 09:57:59 +00001220 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1221 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001222
1223 :return: The session timeout
1224 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001225 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001226
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001227 def set_info_callback(self, callback):
1228 """
Alex Chand072cae2018-02-15 09:57:59 +00001229 Set the information callback to *callback*. This function will be
1230 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001231
Alex Chand072cae2018-02-15 09:57:59 +00001232 :param callback: The Python callback to use. This should take three
1233 arguments: a Connection object and two integers. The first integer
1234 specifies where in the SSL handshake the function was called, and
1235 the other the return code from a (possibly failed) internal
1236 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001237 :return: None
1238 """
Alex Gaynor03737182020-07-23 20:40:46 -04001239
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001240 @wraps(callback)
1241 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001242 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001243
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001244 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001245 "void (*)(const SSL *, int, int)", wrapper
1246 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001247 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001248
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001249 @_requires_keylog
1250 def set_keylog_callback(self, callback):
1251 """
1252 Set the TLS key logging callback to *callback*. This function will be
1253 called whenever TLS key material is generated or received, in order
1254 to allow applications to store this keying material for debugging
1255 purposes.
1256
1257 :param callback: The Python callback to use. This should take two
1258 arguments: a Connection object and a bytestring that contains
1259 the key material in the format used by NSS for its SSLKEYLOGFILE
1260 debugging output.
1261 :return: None
1262 """
1263
1264 @wraps(callback)
1265 def wrapper(ssl, line):
1266 line = _ffi.string(line)
1267 callback(Connection._reverse_mapping[ssl], line)
1268
1269 self._keylog_callback = _ffi.callback(
1270 "void (*)(const SSL *, const char *)", wrapper
1271 )
1272 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1273
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001274 def get_app_data(self):
1275 """
Alex Chand072cae2018-02-15 09:57:59 +00001276 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001277
1278 :return: The application data
1279 """
1280 return self._app_data
1281
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282 def set_app_data(self, data):
1283 """
1284 Set the application data (will be returned from get_app_data())
1285
1286 :param data: Any Python object
1287 :return: None
1288 """
1289 self._app_data = data
1290
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001291 def get_cert_store(self):
1292 """
Alex Chand072cae2018-02-15 09:57:59 +00001293 Get the certificate store for the context. This can be used to add
1294 "trusted" certificates without using the
1295 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001297 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001298 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001299 store = _lib.SSL_CTX_get_cert_store(self._context)
1300 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001301 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001302 return None
1303
1304 pystore = X509Store.__new__(X509Store)
1305 pystore._store = store
1306 return pystore
1307
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001308 def set_options(self, options):
1309 """
1310 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001311 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001312
1313 :param options: The options to add.
1314 :return: The new option bitmask.
1315 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001316 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317 raise TypeError("options must be an integer")
1318
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001319 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001320
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321 def set_mode(self, mode):
1322 """
Alex Chand072cae2018-02-15 09:57:59 +00001323 Add modes via bitmask. Modes set before are not cleared! This method
1324 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001325
1326 :param mode: The mode to add.
1327 :return: The new mode bitmask.
1328 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001329 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001330 raise TypeError("mode must be an integer")
1331
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001332 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001333
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001334 def set_tlsext_servername_callback(self, callback):
1335 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001336 Specify a callback function to be called when clients specify a server
1337 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001338
1339 :param callback: The callback function. It will be invoked with one
1340 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001341
1342 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001343 """
Alex Gaynor03737182020-07-23 20:40:46 -04001344
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001345 @wraps(callback)
1346 def wrapper(ssl, alert, arg):
1347 callback(Connection._reverse_mapping[ssl])
1348 return 0
1349
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001350 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001351 "int (*)(SSL *, int *, void *)", wrapper
1352 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001353 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001354 self._context, self._tlsext_servername_callback
1355 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001356
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001357 def set_tlsext_use_srtp(self, profiles):
1358 """
1359 Enable support for negotiating SRTP keying material.
1360
1361 :param bytes profiles: A colon delimited list of protection profile
1362 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1363 :return: None
1364 """
1365 if not isinstance(profiles, bytes):
1366 raise TypeError("profiles must be a byte string.")
1367
1368 _openssl_assert(
1369 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1370 )
1371
Cory Benfield7907e332015-04-13 17:18:25 -04001372 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001373 def set_alpn_protos(self, protos):
1374 """
Alex Chand072cae2018-02-15 09:57:59 +00001375 Specify the protocols that the client is prepared to speak after the
1376 TLS connection has been negotiated using Application Layer Protocol
1377 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001378
1379 :param protos: A list of the protocols to be offered to the server.
1380 This list should be a Python list of bytestrings representing the
1381 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1382 """
1383 # Take the list of protocols and join them together, prefixing them
1384 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001385 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001386 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1387 )
1388
1389 # Build a C string from the list. We don't need to save this off
1390 # because OpenSSL immediately copies the data out.
1391 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001392 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001393
Cory Benfield7907e332015-04-13 17:18:25 -04001394 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001395 def set_alpn_select_callback(self, callback):
1396 """
Alex Chand072cae2018-02-15 09:57:59 +00001397 Specify a callback function that will be called on the server when a
1398 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001399
1400 :param callback: The callback function. It will be invoked with two
1401 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001402 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1403 one of those bytestrings to indicate the chosen protocol, the
1404 empty bytestring to terminate the TLS connection, or the
1405 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1406 protocol was selected, but that the connection should not be
1407 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001408 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001409 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001410 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001411 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001412 self._context, self._alpn_select_callback, _ffi.NULL
1413 )
Cory Benfield12eae892014-06-07 15:42:56 +01001414
Cory Benfield496652a2017-01-24 11:42:56 +00001415 def _set_ocsp_callback(self, helper, data):
1416 """
1417 This internal helper does the common work for
1418 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1419 almost all of it.
1420 """
1421 self._ocsp_helper = helper
1422 self._ocsp_callback = helper.callback
1423 if data is None:
1424 self._ocsp_data = _ffi.NULL
1425 else:
1426 self._ocsp_data = _ffi.new_handle(data)
1427
1428 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1429 self._context, self._ocsp_callback
1430 )
1431 _openssl_assert(rc == 1)
1432 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1433 _openssl_assert(rc == 1)
1434
1435 def set_ocsp_server_callback(self, callback, data=None):
1436 """
1437 Set a callback to provide OCSP data to be stapled to the TLS handshake
1438 on the server side.
1439
1440 :param callback: The callback function. It will be invoked with two
1441 arguments: the Connection, and the optional arbitrary data you have
1442 provided. The callback must return a bytestring that contains the
1443 OCSP data to staple to the handshake. If no OCSP data is available
1444 for this connection, return the empty bytestring.
1445 :param data: Some opaque data that will be passed into the callback
1446 function when called. This can be used to avoid needing to do
1447 complex data lookups or to keep track of what context is being
1448 used. This parameter is optional.
1449 """
1450 helper = _OCSPServerCallbackHelper(callback)
1451 self._set_ocsp_callback(helper, data)
1452
1453 def set_ocsp_client_callback(self, callback, data=None):
1454 """
1455 Set a callback to validate OCSP data stapled to the TLS handshake on
1456 the client side.
1457
1458 :param callback: The callback function. It will be invoked with three
1459 arguments: the Connection, a bytestring containing the stapled OCSP
1460 assertion, and the optional arbitrary data you have provided. The
1461 callback must return a boolean that indicates the result of
1462 validating the OCSP data: ``True`` if the OCSP data is valid and
1463 the certificate can be trusted, or ``False`` if either the OCSP
1464 data is invalid or the certificate has been revoked.
1465 :param data: Some opaque data that will be passed into the callback
1466 function when called. This can be used to avoid needing to do
1467 complex data lookups or to keep track of what context is being
1468 used. This parameter is optional.
1469 """
1470 helper = _OCSPClientCallbackHelper(callback)
1471 self._set_ocsp_callback(helper, data)
1472
Alex Chanc6077062016-11-18 13:53:39 +00001473
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001474class Connection(object):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001475 _reverse_mapping = WeakValueDictionary()
1476
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001477 def __init__(self, context, socket=None):
1478 """
1479 Create a new Connection object, using the given OpenSSL.SSL.Context
1480 instance and socket.
1481
1482 :param context: An SSL Context to use for this connection
1483 :param socket: The socket to use for transport layer
1484 """
1485 if not isinstance(context, Context):
1486 raise TypeError("context must be a Context instance")
1487
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001488 ssl = _lib.SSL_new(context._context)
1489 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001490 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1491 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1492 # even though there is still data on the underlying transport.
1493 # See https://github.com/openssl/openssl/issues/6234 for more details.
1494 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001495 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001496 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001497
Cory Benfield12eae892014-06-07 15:42:56 +01001498 # References to strings used for Application Layer Protocol
1499 # Negotiation. These strings get copied at some point but it's well
1500 # after the callback returns, so we have to hang them somewhere to
1501 # avoid them getting freed.
1502 self._alpn_select_callback_args = None
1503
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001504 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001505
1506 if socket is None:
1507 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001508 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001509 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001510 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001511
Alex Gaynora829e902016-06-04 18:16:01 -07001512 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1513 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001515 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001517 self._into_ssl = None
1518 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001519 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001520 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001521 self._ssl, _asFileDescriptor(self._socket)
1522 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001523 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001524
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001525 def __getattr__(self, name):
1526 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001527 Look up attributes on the wrapped socket object if they are not found
1528 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001529 """
kjav0b66fa12015-09-02 11:51:26 +01001530 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001531 raise AttributeError(
1532 "'%s' object has no attribute '%s'"
1533 % (self.__class__.__name__, name)
1534 )
kjav0b66fa12015-09-02 11:51:26 +01001535 else:
1536 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001537
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001539 if self._context._verify_helper is not None:
1540 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001541 if self._context._alpn_select_helper is not None:
1542 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001543 if self._context._ocsp_helper is not None:
1544 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001545
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001546 error = _lib.SSL_get_error(ssl, result)
1547 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001548 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001549 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001550 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001551 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001552 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001553 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001554 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001555 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001556 elif error == _lib.SSL_ERROR_SYSCALL:
1557 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001558 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001559 if platform == "win32":
1560 errno = _ffi.getwinerror()[0]
1561 else:
1562 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001563
1564 if errno != 0:
1565 raise SysCallError(errno, errorcode.get(errno))
1566 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001568 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001569 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001570 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001571 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001573 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001575 def get_context(self):
1576 """
Alex Chand072cae2018-02-15 09:57:59 +00001577 Retrieve the :class:`Context` object associated with this
1578 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001583 """
Alex Chand072cae2018-02-15 09:57:59 +00001584 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585
Alex Chand072cae2018-02-15 09:57:59 +00001586 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001587 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001589 if not isinstance(context, Context):
1590 raise TypeError("context must be a Context instance")
1591
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001592 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001593 self._context = context
1594
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001595 def get_servername(self):
1596 """
1597 Retrieve the servername extension value if provided in the client hello
1598 message, or None if there wasn't one.
1599
Alex Chand072cae2018-02-15 09:57:59 +00001600 :return: A byte string giving the server name or :data:`None`.
1601
1602 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001603 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001604 name = _lib.SSL_get_servername(
1605 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1606 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001607 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001608 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001609
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001610 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001611
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001612 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001613 """
1614 Set the value of the servername extension to send in the client hello.
1615
1616 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001617
1618 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001619 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001620 if not isinstance(name, bytes):
1621 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001622 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001623 raise TypeError("name must not contain NUL byte")
1624
1625 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001626 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001627
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001628 def pending(self):
1629 """
Alex Chand072cae2018-02-15 09:57:59 +00001630 Get the number of bytes that can be safely read from the SSL buffer
1631 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001632
1633 :return: The number of bytes available in the receive buffer.
1634 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001635 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001636
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001637 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001638 """
1639 Send data on the connection. NOTE: If you get one of the WantRead,
1640 WantWrite or WantX509Lookup exceptions on this, you have to call the
1641 method again with the SAME buffer.
1642
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001643 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001644 :param flags: (optional) Included for compatibility with the socket
1645 API, the value is ignored
1646 :return: The number of bytes written
1647 """
Abraham Martine82326c2015-02-04 10:18:10 +00001648 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001649 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001650
Daniel Holth079c9632019-11-17 22:45:52 -05001651 with _from_buffer(buf) as data:
1652 # check len(buf) instead of len(data) for testability
1653 if len(buf) > 2147483647:
1654 raise ValueError(
1655 "Cannot send more than 2**31-1 bytes at once."
1656 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657
Daniel Holth079c9632019-11-17 22:45:52 -05001658 result = _lib.SSL_write(self._ssl, data, len(data))
1659 self._raise_ssl_error(self._ssl, result)
1660
1661 return result
1662
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663 write = send
1664
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001665 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001666 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001667 Send "all" data on the connection. This calls send() repeatedly until
1668 all data is sent. If an error occurs, it's impossible to tell how much
1669 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001671 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001672 :param flags: (optional) Included for compatibility with the socket
1673 API, the value is ignored
1674 :return: The number of bytes written
1675 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001676 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001677
Daniel Holth079c9632019-11-17 22:45:52 -05001678 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001679
Daniel Holth079c9632019-11-17 22:45:52 -05001680 left_to_send = len(buf)
1681 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001682
Daniel Holth079c9632019-11-17 22:45:52 -05001683 while left_to_send:
1684 # SSL_write's num arg is an int,
1685 # so we cannot send more than 2**31-1 bytes at once.
1686 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001687 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001688 )
1689 self._raise_ssl_error(self._ssl, result)
1690 total_sent += result
1691 left_to_send -= result
1692
1693 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001694
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001695 def recv(self, bufsiz, flags=None):
1696 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001697 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001698
1699 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001700 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1701 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 :return: The string read from the Connection
1703 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001704 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001705 if flags is not None and flags & socket.MSG_PEEK:
1706 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1707 else:
1708 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001710 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001711
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001712 read = recv
1713
Cory Benfield62d10332014-06-15 10:03:41 +01001714 def recv_into(self, buffer, nbytes=None, flags=None):
1715 """
Alex Chand072cae2018-02-15 09:57:59 +00001716 Receive data on the connection and copy it directly into the provided
1717 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001718
1719 :param buffer: The buffer to copy into.
1720 :param nbytes: (optional) The maximum number of bytes to read into the
1721 buffer. If not present, defaults to the size of the buffer. If
1722 larger than the size of the buffer, is reduced to the size of the
1723 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001724 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1725 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001726 :return: The number of bytes read into the buffer.
1727 """
1728 if nbytes is None:
1729 nbytes = len(buffer)
1730 else:
1731 nbytes = min(nbytes, len(buffer))
1732
1733 # We need to create a temporary buffer. This is annoying, it would be
1734 # better if we could pass memoryviews straight into the SSL_read call,
1735 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001736 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001737 if flags is not None and flags & socket.MSG_PEEK:
1738 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1739 else:
1740 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001741 self._raise_ssl_error(self._ssl, result)
1742
1743 # This strange line is all to avoid a memory copy. The buffer protocol
1744 # should allow us to assign a CFFI buffer to the LHS of this line, but
1745 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001746 # wrap it in a memoryview.
1747 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001748
1749 return result
1750
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001752 if _lib.BIO_should_retry(bio):
1753 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001754 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001755 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001756 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001757 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001758 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001759 # TODO: This is untested. I think io_special means the socket
1760 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001761 raise ValueError("BIO_should_io_special")
1762 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001763 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001764 raise ValueError("unknown bio failure")
1765 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001766 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001767 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001768
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001769 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001770 """
Alex Chand072cae2018-02-15 09:57:59 +00001771 If the Connection was created with a memory BIO, this method can be
1772 used to read bytes from the write end of that memory BIO. Many
1773 Connection methods will add bytes which must be read in this manner or
1774 the buffer will eventually fill up and the Connection will be able to
1775 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001776
1777 :param bufsiz: The maximum number of bytes to read
1778 :return: The string read.
1779 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001780 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001781 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001782
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001783 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001784 raise TypeError("bufsiz must be an integer")
1785
Cory Benfielde62840e2016-11-28 12:17:08 +00001786 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001787 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001788 if result <= 0:
1789 self._handle_bio_errors(self._from_ssl, result)
1790
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001791 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001792
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001793 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 """
Alex Chand072cae2018-02-15 09:57:59 +00001795 If the Connection was created with a memory BIO, this method can be
1796 used to add bytes to the read end of that memory BIO. The Connection
1797 can then read the bytes (for example, in response to a call to
1798 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001799
1800 :param buf: The string to put into the memory BIO.
1801 :return: The number of bytes written
1802 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001803 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001804
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001805 if self._into_ssl is None:
1806 raise TypeError("Connection sock was not None")
1807
Daniel Holth079c9632019-11-17 22:45:52 -05001808 with _from_buffer(buf) as data:
1809 result = _lib.BIO_write(self._into_ssl, data, len(data))
1810 if result <= 0:
1811 self._handle_bio_errors(self._into_ssl, result)
1812 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001813
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001814 def renegotiate(self):
1815 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001816 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001817
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001818 :return: True if the renegotiation can be started, False otherwise
1819 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001820 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001821 if not self.renegotiate_pending():
1822 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1823 return True
1824 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001825
1826 def do_handshake(self):
1827 """
Alex Chand072cae2018-02-15 09:57:59 +00001828 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001829 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001830 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001831
1832 :return: None.
1833 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001834 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001835 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001836
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837 def renegotiate_pending(self):
1838 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001839 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001840 a renegotiation is finished.
1841
1842 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001843 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001844 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001845 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001846
1847 def total_renegotiations(self):
1848 """
1849 Find out the total number of renegotiations.
1850
1851 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001852 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001853 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001855
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001856 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857 """
Alex Chand072cae2018-02-15 09:57:59 +00001858 Call the :meth:`connect` method of the underlying socket and set up SSL
1859 on the socket, using the :class:`Context` object supplied to this
1860 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001861
1862 :param addr: A remote address
1863 :return: What the socket's connect method returns
1864 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001865 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001866 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001868 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001869 """
Alex Chand072cae2018-02-15 09:57:59 +00001870 Call the :meth:`connect_ex` method of the underlying socket and set up
1871 SSL on the socket, using the Context object supplied to this Connection
1872 object at creation. Note that if the :meth:`connect_ex` method of the
1873 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001874
1875 :param addr: A remove address
1876 :return: What the socket's connect_ex method returns
1877 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001878 connect_ex = self._socket.connect_ex
1879 self.set_connect_state()
1880 return connect_ex(addr)
1881
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001882 def accept(self):
1883 """
Alex Chand072cae2018-02-15 09:57:59 +00001884 Call the :meth:`accept` method of the underlying socket and set up SSL
1885 on the returned socket, using the Context object supplied to this
1886 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001887
Alex Chand072cae2018-02-15 09:57:59 +00001888 :return: A *(conn, addr)* pair where *conn* is the new
1889 :class:`Connection` object created, and *address* is as returned by
1890 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001891 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001892 client, addr = self._socket.accept()
1893 conn = Connection(self._context, client)
1894 conn.set_accept_state()
1895 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001897 def bio_shutdown(self):
1898 """
Alex Chand072cae2018-02-15 09:57:59 +00001899 If the Connection was created with a memory BIO, this method can be
1900 used to indicate that *end of file* has been reached on the read end of
1901 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001902
1903 :return: None
1904 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001905 if self._from_ssl is None:
1906 raise TypeError("Connection sock was not None")
1907
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001908 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001909
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001910 def shutdown(self):
1911 """
Alex Chand072cae2018-02-15 09:57:59 +00001912 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913
1914 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001915 have sent closure alerts), False otherwise (in which case you
1916 call :meth:`recv` or :meth:`send` when the connection becomes
1917 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001918 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001919 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001920 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001921 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001922 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001923 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001924 else:
1925 return False
1926
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001927 def get_cipher_list(self):
1928 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001929 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001931 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932 """
1933 ciphers = []
1934 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001935 result = _lib.SSL_get_cipher_list(self._ssl, i)
1936 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001937 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001938 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939 return ciphers
1940
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941 def get_client_ca_list(self):
1942 """
1943 Get CAs whose certificates are suggested for client authentication.
1944
Alex Chand072cae2018-02-15 09:57:59 +00001945 :return: If this is a server connection, the list of certificate
1946 authorities that will be sent or has been sent to the client, as
1947 controlled by this :class:`Connection`'s :class:`Context`.
1948
1949 If this is a client connection, the list will be empty until the
1950 connection with the server is established.
1951
1952 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001953 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001954 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1955 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001956 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957 return []
1958
1959 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1961 name = _lib.sk_X509_NAME_value(ca_names, i)
1962 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001963 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001964
1965 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001966 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001967 result.append(pyname)
1968 return result
1969
Aykee7f33452018-05-16 19:18:16 +02001970 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001971 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001972 The makefile() method is not implemented, since there is no dup
1973 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001974
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001975 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001976 """
Alex Gaynor83284952015-09-05 10:43:30 -04001977 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001978 "Cannot make file object of OpenSSL.SSL.Connection"
1979 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980
1981 def get_app_data(self):
1982 """
Alex Chand072cae2018-02-15 09:57:59 +00001983 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984
1985 :return: The application data
1986 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001987 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001988
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001989 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990 """
1991 Set application data
1992
Alex Chand072cae2018-02-15 09:57:59 +00001993 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994 :return: None
1995 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001996 self._app_data = data
1997
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001998 def get_shutdown(self):
1999 """
Alex Chand072cae2018-02-15 09:57:59 +00002000 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001
Alex Gaynor62da94d2015-09-05 14:37:34 -04002002 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2003 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002005 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002006
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002007 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008 """
Alex Chand072cae2018-02-15 09:57:59 +00002009 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002010
Alex Chand072cae2018-02-15 09:57:59 +00002011 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002012 :return: None
2013 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002014 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002015 raise TypeError("state must be an integer")
2016
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002017 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002018
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002019 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002021 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002022
2023 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002024 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025 """
kjavc704a2e2015-09-07 12:12:27 +01002026 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027
2028 def server_random(self):
2029 """
Alex Chand072cae2018-02-15 09:57:59 +00002030 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002031
2032 :return: A string representing the state
2033 """
Alex Gaynor93603062016-06-01 20:13:09 -07002034 session = _lib.SSL_get_session(self._ssl)
2035 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002036 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002037 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002038 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002039 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002040 _lib.SSL_get_server_random(self._ssl, outp, length)
2041 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002042
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002043 def client_random(self):
2044 """
Alex Chand072cae2018-02-15 09:57:59 +00002045 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002046
2047 :return: A string representing the state
2048 """
Alex Gaynor93603062016-06-01 20:13:09 -07002049 session = _lib.SSL_get_session(self._ssl)
2050 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002052
2053 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002054 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002055 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002056 _lib.SSL_get_client_random(self._ssl, outp, length)
2057 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002058
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002059 def master_key(self):
2060 """
Alex Chand072cae2018-02-15 09:57:59 +00002061 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002062
2063 :return: A string representing the state
2064 """
Alex Gaynor93603062016-06-01 20:13:09 -07002065 session = _lib.SSL_get_session(self._ssl)
2066 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002067 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002068
2069 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002070 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002071 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002072 _lib.SSL_SESSION_get_master_key(session, outp, length)
2073 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002074
Paul Kehrerbdb76392017-12-01 04:54:32 +08002075 def export_keying_material(self, label, olen, context=None):
2076 """
2077 Obtain keying material for application use.
2078
Alex Chand072cae2018-02-15 09:57:59 +00002079 :param: label - a disambiguating label string as described in RFC 5705
2080 :param: olen - the length of the exported key material in bytes
2081 :param: context - a per-association context value
2082 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002083 """
2084 outp = _no_zero_allocator("unsigned char[]", olen)
2085 context_buf = _ffi.NULL
2086 context_len = 0
2087 use_context = 0
2088 if context is not None:
2089 context_buf = context
2090 context_len = len(context)
2091 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002092 success = _lib.SSL_export_keying_material(
2093 self._ssl,
2094 outp,
2095 olen,
2096 label,
2097 len(label),
2098 context_buf,
2099 context_len,
2100 use_context,
2101 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002102 _openssl_assert(success == 1)
2103 return _ffi.buffer(outp, olen)[:]
2104
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002105 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106 """
Alex Chand072cae2018-02-15 09:57:59 +00002107 Call the :meth:`shutdown` method of the underlying socket.
2108 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002109
2110 :return: What the socket's shutdown() method returns
2111 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002112 return self._socket.shutdown(*args, **kwargs)
2113
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002114 def get_certificate(self):
2115 """
2116 Retrieve the local certificate (if any)
2117
2118 :return: The local certificate
2119 """
2120 cert = _lib.SSL_get_certificate(self._ssl)
2121 if cert != _ffi.NULL:
2122 _lib.X509_up_ref(cert)
2123 return X509._from_raw_x509_ptr(cert)
2124 return None
2125
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002126 def get_peer_certificate(self):
2127 """
2128 Retrieve the other side's certificate (if any)
2129
2130 :return: The peer's certificate
2131 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002132 cert = _lib.SSL_get_peer_certificate(self._ssl)
2133 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002134 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002135 return None
2136
Shane Harvey33c54992020-08-05 16:48:51 -07002137 @staticmethod
2138 def _cert_stack_to_list(cert_stack):
2139 """
2140 Internal helper to convert a STACK_OF(X509) to a list of X509
2141 instances.
2142 """
2143 result = []
2144 for i in range(_lib.sk_X509_num(cert_stack)):
2145 cert = _lib.sk_X509_value(cert_stack, i)
2146 _openssl_assert(cert != _ffi.NULL)
2147 res = _lib.X509_up_ref(cert)
2148 _openssl_assert(res >= 1)
2149 pycert = X509._from_raw_x509_ptr(cert)
2150 result.append(pycert)
2151 return result
2152
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002153 def get_peer_cert_chain(self):
2154 """
2155 Retrieve the other side's certificate (if any)
2156
2157 :return: A list of X509 instances giving the peer's certificate chain,
2158 or None if it does not have one.
2159 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002160 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2161 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002162 return None
2163
Shane Harvey33c54992020-08-05 16:48:51 -07002164 return self._cert_stack_to_list(cert_stack)
2165
2166 def get_verified_chain(self):
2167 """
2168 Retrieve the verified certificate chain of the peer including the
2169 peer's end entity certificate. It must be called after a session has
2170 been successfully established. If peer verification was not successful
2171 the chain may be incomplete, invalid, or None.
2172
2173 :return: A list of X509 instances giving the peer's verified
2174 certificate chain, or None if it does not have one.
2175
2176 .. versionadded:: 20.0
2177 """
2178 if hasattr(_lib, "SSL_get0_verified_chain"):
2179 # OpenSSL 1.1+
2180 cert_stack = _lib.SSL_get0_verified_chain(self._ssl)
2181 if cert_stack == _ffi.NULL:
2182 return None
2183
2184 return self._cert_stack_to_list(cert_stack)
2185
2186 pycert = self.get_peer_certificate()
2187 if pycert is None:
2188 return None
2189
2190 # Should never be NULL because the peer presented a certificate.
2191 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2192 _openssl_assert(cert_stack != _ffi.NULL)
2193
2194 pystore = self._context.get_cert_store()
2195 if pystore is None:
2196 return None
2197
2198 pystorectx = X509StoreContext(pystore, pycert)
2199 pystorectx._chain = cert_stack
2200 return pystorectx.get_verified_chain()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002201
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002202 def want_read(self):
2203 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002204 Checks if more data has to be read from the transport layer to complete
2205 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002206
2207 :return: True iff more data has to be read
2208 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002209 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002210
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002211 def want_write(self):
2212 """
2213 Checks if there is data to write to the transport layer to complete an
2214 operation.
2215
2216 :return: True iff there is data to write
2217 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002218 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002219
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002220 def set_accept_state(self):
2221 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002222 Set the connection to work in server mode. The handshake will be
2223 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002224
2225 :return: None
2226 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002227 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002228
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002229 def set_connect_state(self):
2230 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002231 Set the connection to work in client mode. The handshake will be
2232 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002233
2234 :return: None
2235 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002236 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002237
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002238 def get_session(self):
2239 """
2240 Returns the Session currently used.
2241
Alex Chand072cae2018-02-15 09:57:59 +00002242 :return: An instance of :class:`OpenSSL.SSL.Session` or
2243 :obj:`None` if no session exists.
2244
2245 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002246 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002247 session = _lib.SSL_get1_session(self._ssl)
2248 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002249 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002250
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002251 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002252 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002253 return pysession
2254
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002255 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002256 """
2257 Set the session to be used when the TLS/SSL connection is established.
2258
2259 :param session: A Session instance representing the session to use.
2260 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002261
2262 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002263 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002264 if not isinstance(session, Session):
2265 raise TypeError("session must be a Session instance")
2266
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002267 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002268 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002269
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002270 def _get_finished_message(self, function):
2271 """
Alex Chand072cae2018-02-15 09:57:59 +00002272 Helper to implement :meth:`get_finished` and
2273 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002274
Alex Chand072cae2018-02-15 09:57:59 +00002275 :param function: Either :data:`SSL_get_finished`: or
2276 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002277
Alex Chand072cae2018-02-15 09:57:59 +00002278 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002279 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002280 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002281 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002282 # The OpenSSL documentation says nothing about what might happen if the
2283 # count argument given is zero. Specifically, it doesn't say whether
2284 # the output buffer may be NULL in that case or not. Inspection of the
2285 # implementation reveals that it calls memcpy() unconditionally.
2286 # Section 7.1.4, paragraph 1 of the C standard suggests that
2287 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2288 # alone desirable) behavior (though it probably does on just about
2289 # every implementation...)
2290 #
2291 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2292 # one might expect) for the initial call so as to be safe against this
2293 # potentially undefined behavior.
2294 empty = _ffi.new("char[]", 0)
2295 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002296 if size == 0:
2297 # No Finished message so far.
2298 return None
2299
Cory Benfielde62840e2016-11-28 12:17:08 +00002300 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002301 function(self._ssl, buf, size)
2302 return _ffi.buffer(buf, size)[:]
2303
Fedor Brunner5747b932014-03-05 14:22:34 +01002304 def get_finished(self):
2305 """
Alex Chand072cae2018-02-15 09:57:59 +00002306 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002307
Alex Chand072cae2018-02-15 09:57:59 +00002308 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002309 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002310 :rtype: :class:`bytes` or :class:`NoneType`
2311
2312 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002313 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002314 return self._get_finished_message(_lib.SSL_get_finished)
2315
Fedor Brunner5747b932014-03-05 14:22:34 +01002316 def get_peer_finished(self):
2317 """
Alex Chand072cae2018-02-15 09:57:59 +00002318 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002319
Alex Chand072cae2018-02-15 09:57:59 +00002320 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002321 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002322 :rtype: :class:`bytes` or :class:`NoneType`
2323
2324 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002325 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002326 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002327
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002328 def get_cipher_name(self):
2329 """
2330 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002331
Alex Chand072cae2018-02-15 09:57:59 +00002332 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002333 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002334 :rtype: :class:`unicode` or :class:`NoneType`
2335
2336 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002337 """
2338 cipher = _lib.SSL_get_current_cipher(self._ssl)
2339 if cipher == _ffi.NULL:
2340 return None
2341 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002342 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2343 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002344
2345 def get_cipher_bits(self):
2346 """
2347 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002348
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002349 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002350 or :obj:`None` if no connection has been established.
2351 :rtype: :class:`int` or :class:`NoneType`
2352
2353 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002354 """
2355 cipher = _lib.SSL_get_current_cipher(self._ssl)
2356 if cipher == _ffi.NULL:
2357 return None
2358 else:
2359 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2360
2361 def get_cipher_version(self):
2362 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002363 Obtain the protocol version of the currently used cipher.
2364
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002365 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002366 or :obj:`None` if no connection has been established.
2367 :rtype: :class:`unicode` or :class:`NoneType`
2368
2369 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002370 """
2371 cipher = _lib.SSL_get_current_cipher(self._ssl)
2372 if cipher == _ffi.NULL:
2373 return None
2374 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002375 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002376 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002377
Jim Shaverabff1882015-05-27 09:15:55 -04002378 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002379 """
Alex Chand072cae2018-02-15 09:57:59 +00002380 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002381
2382 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002383 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002384 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002385 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002386 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002387 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002388 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002389
Jim Shaver208438c2015-05-28 09:52:38 -04002390 def get_protocol_version(self):
2391 """
Alex Chand072cae2018-02-15 09:57:59 +00002392 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002393
Alex Chand072cae2018-02-15 09:57:59 +00002394 :returns: The TLS version of the current connection. For example,
2395 it will return ``0x769`` for connections made over TLS version 1.
2396 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002397 """
2398 version = _lib.SSL_version(self._ssl)
2399 return version
2400
Cory Benfield7907e332015-04-13 17:18:25 -04002401 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002402 def set_alpn_protos(self, protos):
2403 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002404 Specify the client's ALPN protocol list.
2405
2406 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002407
2408 :param protos: A list of the protocols to be offered to the server.
2409 This list should be a Python list of bytestrings representing the
2410 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2411 """
2412 # Take the list of protocols and join them together, prefixing them
2413 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002414 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002415 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2416 )
2417
2418 # Build a C string from the list. We don't need to save this off
2419 # because OpenSSL immediately copies the data out.
2420 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002421 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002422
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002423 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002424 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002425 """
2426 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002427
2428 :returns: A bytestring of the protocol name. If no protocol has been
2429 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002430 """
Cory Benfield12eae892014-06-07 15:42:56 +01002431 data = _ffi.new("unsigned char **")
2432 data_len = _ffi.new("unsigned int *")
2433
2434 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2435
Cory Benfielde8e9c382015-04-11 17:33:48 -04002436 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002437 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002438
Cory Benfield12eae892014-06-07 15:42:56 +01002439 return _ffi.buffer(data[0], data_len[0])[:]
2440
Cory Benfield496652a2017-01-24 11:42:56 +00002441 def request_ocsp(self):
2442 """
2443 Called to request that the server sends stapled OCSP data, if
2444 available. If this is not called on the client side then the server
2445 will not send OCSP data. Should be used in conjunction with
2446 :meth:`Context.set_ocsp_client_callback`.
2447 """
2448 rc = _lib.SSL_set_tlsext_status_type(
2449 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2450 )
2451 _openssl_assert(rc == 1)
2452
Cory Benfield12eae892014-06-07 15:42:56 +01002453
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002454# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2455# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002456_lib.SSL_library_init()