blob: 8a54994b2868d708c1cb89bdbb3cab720e0551af [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor12576002019-11-18 00:18:50 -05009from six import integer_types, int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050010
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050011from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010012 UNSPECIFIED as _UNSPECIFIED,
13 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014 ffi as _ffi,
Daniel Holth079c9632019-11-17 22:45:52 -050015 from_buffer as _from_buffer,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050016 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000021 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080023
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080024from OpenSSL.crypto import (
Alex Gaynor03737182020-07-23 20:40:46 -040025 FILETYPE_PEM,
26 _PassphraseHelper,
27 PKey,
28 X509Name,
29 X509,
30 X509Store,
31)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080032
Nicolas Karolak736c6212017-11-26 14:40:28 +010033__all__ = [
Alex Gaynor03737182020-07-23 20:40:46 -040034 "OPENSSL_VERSION_NUMBER",
35 "SSLEAY_VERSION",
36 "SSLEAY_CFLAGS",
37 "SSLEAY_PLATFORM",
38 "SSLEAY_DIR",
39 "SSLEAY_BUILT_ON",
40 "SENT_SHUTDOWN",
41 "RECEIVED_SHUTDOWN",
42 "SSLv2_METHOD",
43 "SSLv3_METHOD",
44 "SSLv23_METHOD",
45 "TLSv1_METHOD",
46 "TLSv1_1_METHOD",
47 "TLSv1_2_METHOD",
48 "OP_NO_SSLv2",
49 "OP_NO_SSLv3",
50 "OP_NO_TLSv1",
51 "OP_NO_TLSv1_1",
52 "OP_NO_TLSv1_2",
53 "OP_NO_TLSv1_3",
54 "MODE_RELEASE_BUFFERS",
55 "OP_SINGLE_DH_USE",
56 "OP_SINGLE_ECDH_USE",
57 "OP_EPHEMERAL_RSA",
58 "OP_MICROSOFT_SESS_ID_BUG",
59 "OP_NETSCAPE_CHALLENGE_BUG",
60 "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
61 "OP_SSLREF2_REUSE_CERT_TYPE_BUG",
62 "OP_MICROSOFT_BIG_SSLV3_BUFFER",
63 "OP_MSIE_SSLV2_RSA_PADDING",
64 "OP_SSLEAY_080_CLIENT_DH_BUG",
65 "OP_TLS_D5_BUG",
66 "OP_TLS_BLOCK_PADDING_BUG",
67 "OP_DONT_INSERT_EMPTY_FRAGMENTS",
68 "OP_CIPHER_SERVER_PREFERENCE",
69 "OP_TLS_ROLLBACK_BUG",
70 "OP_PKCS1_CHECK_1",
71 "OP_PKCS1_CHECK_2",
72 "OP_NETSCAPE_CA_DN_BUG",
73 "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
74 "OP_NO_COMPRESSION",
75 "OP_NO_QUERY_MTU",
76 "OP_COOKIE_EXCHANGE",
77 "OP_NO_TICKET",
78 "OP_ALL",
79 "VERIFY_PEER",
80 "VERIFY_FAIL_IF_NO_PEER_CERT",
81 "VERIFY_CLIENT_ONCE",
82 "VERIFY_NONE",
83 "SESS_CACHE_OFF",
84 "SESS_CACHE_CLIENT",
85 "SESS_CACHE_SERVER",
86 "SESS_CACHE_BOTH",
87 "SESS_CACHE_NO_AUTO_CLEAR",
88 "SESS_CACHE_NO_INTERNAL_LOOKUP",
89 "SESS_CACHE_NO_INTERNAL_STORE",
90 "SESS_CACHE_NO_INTERNAL",
91 "SSL_ST_CONNECT",
92 "SSL_ST_ACCEPT",
93 "SSL_ST_MASK",
94 "SSL_CB_LOOP",
95 "SSL_CB_EXIT",
96 "SSL_CB_READ",
97 "SSL_CB_WRITE",
98 "SSL_CB_ALERT",
99 "SSL_CB_READ_ALERT",
100 "SSL_CB_WRITE_ALERT",
101 "SSL_CB_ACCEPT_LOOP",
102 "SSL_CB_ACCEPT_EXIT",
103 "SSL_CB_CONNECT_LOOP",
104 "SSL_CB_CONNECT_EXIT",
105 "SSL_CB_HANDSHAKE_START",
106 "SSL_CB_HANDSHAKE_DONE",
107 "Error",
108 "WantReadError",
109 "WantWriteError",
110 "WantX509LookupError",
111 "ZeroReturnError",
112 "SysCallError",
113 "SSLeay_version",
114 "Session",
115 "Context",
116 "Connection",
Nicolas Karolak736c6212017-11-26 14:40:28 +0100117]
118
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500119try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200120 _buffer = buffer
121except NameError:
Alex Gaynor03737182020-07-23 20:40:46 -0400122
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200123 class _buffer(object):
124 pass
125
Alex Gaynor03737182020-07-23 20:40:46 -0400126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500127OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
128SSLEAY_VERSION = _lib.SSLEAY_VERSION
129SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
130SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
131SSLEAY_DIR = _lib.SSLEAY_DIR
132SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
135RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800136
137SSLv2_METHOD = 1
138SSLv3_METHOD = 2
139SSLv23_METHOD = 3
140TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500141TLSv1_1_METHOD = 5
142TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800143
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500144OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
145OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
146OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700147OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
148OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700149try:
150 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
151except AttributeError:
152 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800153
Alex Gaynorbf012872016-06-04 13:18:39 -0700154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
Alex Gaynorbf012872016-06-04 13:18:39 -0700179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800184
Alex Gaynorc4889812015-09-04 08:43:17 -0400185OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400204if _lib.Cryptography_HAS_SSL_ST:
205 SSL_ST_INIT = _lib.SSL_ST_INIT
206 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
207 SSL_ST_OK = _lib.SSL_ST_OK
208 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Alex Gaynor03737182020-07-23 20:40:46 -0400209 __all__.extend(
210 ["SSL_ST_INIT", "SSL_ST_BEFORE", "SSL_ST_OK", "SSL_ST_RENEGOTIATE"]
211 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800212
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500213SSL_CB_LOOP = _lib.SSL_CB_LOOP
214SSL_CB_EXIT = _lib.SSL_CB_EXIT
215SSL_CB_READ = _lib.SSL_CB_READ
216SSL_CB_WRITE = _lib.SSL_CB_WRITE
217SSL_CB_ALERT = _lib.SSL_CB_ALERT
218SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
219SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
220SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
221SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
222SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
223SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
224SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
225SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800226
Paul Kehrer55fb3412017-06-29 18:44:08 -0500227# Taken from https://golang.org/src/crypto/x509/root_linux.go
228_CERTIFICATE_FILE_LOCATIONS = [
229 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
230 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
231 "/etc/ssl/ca-bundle.pem", # OpenSUSE
232 "/etc/pki/tls/cacert.pem", # OpenELEC
233 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
234]
235
236_CERTIFICATE_PATH_LOCATIONS = [
237 "/etc/ssl/certs", # SLES10/SLES11
238]
239
Paul Kehrera92a1a72017-07-19 15:53:23 +0200240# These values are compared to output from cffi's ffi.string so they must be
241# byte strings.
242_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
243_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500244
Alex Gaynor83284952015-09-05 10:43:30 -0400245
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500246class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500247 """
248 An error occurred in an `OpenSSL.SSL` API.
249 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500250
251
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500252_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100253_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500254
255
256class WantReadError(Error):
257 pass
258
259
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500260class WantWriteError(Error):
261 pass
262
263
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500264class WantX509LookupError(Error):
265 pass
266
267
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500268class ZeroReturnError(Error):
269 pass
270
271
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500272class SysCallError(Error):
273 pass
274
275
Cory Benfield0ea76e72015-03-22 09:05:28 +0000276class _CallbackExceptionHelper(object):
277 """
278 A base class for wrapper classes that allow for intelligent exception
279 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500280
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400281 :ivar list _problems: Any exceptions that occurred while executing in a
282 context where they could not be raised in the normal way. Typically
283 this is because OpenSSL has called into some Python code and requires a
284 return value. The exceptions are saved to be raised later when it is
285 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000286 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400287
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400288 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800289 self._problems = []
290
Cory Benfield0ea76e72015-03-22 09:05:28 +0000291 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400292 """
293 Raise an exception from the OpenSSL error queue or that was previously
294 captured whe running a callback.
295 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000296 if self._problems:
297 try:
298 _raise_current_error()
299 except Error:
300 pass
301 raise self._problems.pop(0)
302
303
304class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400305 """
306 Wrap a callback such that it can be used as a certificate verification
307 callback.
308 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400309
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800310 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400311 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800312
313 @wraps(callback)
314 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800315 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
316 _lib.X509_up_ref(x509)
317 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500318 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
319 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800320
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400321 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
322 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
323 connection = Connection._reverse_mapping[ssl]
324
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400326 result = callback(
327 connection, cert, error_number, error_depth, ok
328 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800329 except Exception as e:
330 self._problems.append(e)
331 return 0
332 else:
333 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500334 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800335 return 1
336 else:
337 return 0
338
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500339 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400340 "int (*)(int, X509_STORE_CTX *)", wrapper
341 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800342
343
Mark Williams5d890a02019-11-17 19:56:26 -0800344NO_OVERLAPPING_PROTOCOLS = object()
345
346
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400347class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400348 """
349 Wrap a callback such that it can be used as an ALPN selection callback.
350 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400351
Cory Benfieldf1177e72015-04-12 09:11:49 -0400352 def __init__(self, callback):
353 _CallbackExceptionHelper.__init__(self)
354
355 @wraps(callback)
356 def wrapper(ssl, out, outlen, in_, inlen, arg):
357 try:
358 conn = Connection._reverse_mapping[ssl]
359
360 # The string passed to us is made up of multiple
361 # length-prefixed bytestrings. We need to split that into a
362 # list.
363 instr = _ffi.buffer(in_, inlen)[:]
364 protolist = []
365 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400366 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400367 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400368 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400369 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400370
371 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800372 outbytes = callback(conn, protolist)
373 any_accepted = True
374 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400375 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800376 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500377 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800378 raise TypeError(
379 "ALPN callback must return a bytestring or the "
380 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
381 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400382
383 # Save our callback arguments on the connection object to make
384 # sure that they don't get freed before OpenSSL can use them.
385 # Then, return them in the appropriate output parameters.
386 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800387 _ffi.new("unsigned char *", len(outbytes)),
388 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400389 ]
390 outlen[0] = conn._alpn_select_callback_args[0][0]
391 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800392 if not any_accepted:
393 return _lib.SSL_TLSEXT_ERR_NOACK
394 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400395 except Exception as e:
396 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800397 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400398
399 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400400 (
401 "int (*)(SSL *, unsigned char **, unsigned char *, "
402 "const unsigned char *, unsigned int, void *)"
403 ),
404 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400405 )
406
407
Cory Benfield496652a2017-01-24 11:42:56 +0000408class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
409 """
410 Wrap a callback such that it can be used as an OCSP callback for the server
411 side.
412
413 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
414 ways. For servers, that callback is expected to retrieve some OCSP data and
415 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
416 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
417 is expected to check the OCSP data, and returns a negative value on error,
418 0 if the response is not acceptable, or positive if it is. These are
419 mutually exclusive return code behaviours, and they mean that we need two
420 helpers so that we always return an appropriate error code if the user's
421 code throws an exception.
422
423 Given that we have to have two helpers anyway, these helpers are a bit more
424 helpery than most: specifically, they hide a few more of the OpenSSL
425 functions so that the user has an easier time writing these callbacks.
426
427 This helper implements the server side.
428 """
429
430 def __init__(self, callback):
431 _CallbackExceptionHelper.__init__(self)
432
433 @wraps(callback)
434 def wrapper(ssl, cdata):
435 try:
436 conn = Connection._reverse_mapping[ssl]
437
438 # Extract the data if any was provided.
439 if cdata != _ffi.NULL:
440 data = _ffi.from_handle(cdata)
441 else:
442 data = None
443
444 # Call the callback.
445 ocsp_data = callback(conn, data)
446
Alex Gaynor12576002019-11-18 00:18:50 -0500447 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000448 raise TypeError("OCSP callback must return a bytestring.")
449
450 # If the OCSP data was provided, we will pass it to OpenSSL.
451 # However, we have an early exit here: if no OCSP data was
452 # provided we will just exit out and tell OpenSSL that there
453 # is nothing to do.
454 if not ocsp_data:
455 return 3 # SSL_TLSEXT_ERR_NOACK
456
David Benjamin7ac5f272018-05-21 21:24:04 -0400457 # OpenSSL takes ownership of this data and expects it to have
458 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000459 ocsp_data_length = len(ocsp_data)
460 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
461 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
462
463 _lib.SSL_set_tlsext_status_ocsp_resp(
464 ssl, data_ptr, ocsp_data_length
465 )
466
467 return 0
468 except Exception as e:
469 self._problems.append(e)
470 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
471
472 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
473
474
475class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
476 """
477 Wrap a callback such that it can be used as an OCSP callback for the client
478 side.
479
480 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
481 ways. For servers, that callback is expected to retrieve some OCSP data and
482 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
483 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
484 is expected to check the OCSP data, and returns a negative value on error,
485 0 if the response is not acceptable, or positive if it is. These are
486 mutually exclusive return code behaviours, and they mean that we need two
487 helpers so that we always return an appropriate error code if the user's
488 code throws an exception.
489
490 Given that we have to have two helpers anyway, these helpers are a bit more
491 helpery than most: specifically, they hide a few more of the OpenSSL
492 functions so that the user has an easier time writing these callbacks.
493
494 This helper implements the client side.
495 """
496
497 def __init__(self, callback):
498 _CallbackExceptionHelper.__init__(self)
499
500 @wraps(callback)
501 def wrapper(ssl, cdata):
502 try:
503 conn = Connection._reverse_mapping[ssl]
504
505 # Extract the data if any was provided.
506 if cdata != _ffi.NULL:
507 data = _ffi.from_handle(cdata)
508 else:
509 data = None
510
511 # Get the OCSP data.
512 ocsp_ptr = _ffi.new("unsigned char **")
513 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
514 if ocsp_len < 0:
515 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400516 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000517 else:
518 # Copy the OCSP data, then pass it to the callback.
519 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
520
521 valid = callback(conn, ocsp_data, data)
522
523 # Return 1 on success or 0 on error.
524 return int(bool(valid))
525
526 except Exception as e:
527 self._problems.append(e)
528 # Return negative value if an exception is hit.
529 return -1
530
531 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
532
533
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800534def _asFileDescriptor(obj):
535 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800536 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800537 meth = getattr(obj, "fileno", None)
538 if meth is not None:
539 obj = meth()
540
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800541 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800542 fd = obj
543
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800544 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800545 raise TypeError("argument must be an int, or have a fileno() method.")
546 elif fd < 0:
547 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400548 "file descriptor cannot be a negative integer (%i)" % (fd,)
549 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800550
551 return fd
552
553
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800554def SSLeay_version(type):
555 """
556 Return a string describing the version of OpenSSL in use.
557
Alex Chand072cae2018-02-15 09:57:59 +0000558 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800559 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500560 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800561
562
Cory Benfieldef404df2016-03-29 15:32:48 +0100563def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400564 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100565 Builds a decorator that ensures that functions that rely on OpenSSL
566 functions that are not present in this build raise NotImplementedError,
567 rather than AttributeError coming out of cryptography.
568
569 :param flag: A cryptography flag that guards the functions, e.g.
570 ``Cryptography_HAS_NEXTPROTONEG``.
571 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400572 """
Alex Gaynor03737182020-07-23 20:40:46 -0400573
Cory Benfieldef404df2016-03-29 15:32:48 +0100574 def _requires_decorator(func):
575 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400576
Cory Benfieldef404df2016-03-29 15:32:48 +0100577 @wraps(func)
578 def explode(*args, **kwargs):
579 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400580
Cory Benfieldef404df2016-03-29 15:32:48 +0100581 return explode
582 else:
583 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400584
Cory Benfieldef404df2016-03-29 15:32:48 +0100585 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400586
587
Cory Benfieldef404df2016-03-29 15:32:48 +0100588_requires_alpn = _make_requires(
589 _lib.Cryptography_HAS_ALPN, "ALPN not available"
590)
Cory Benfielde6f35882016-03-29 11:21:04 +0100591
Cory Benfielde6f35882016-03-29 11:21:04 +0100592
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200593_requires_keylog = _make_requires(
594 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
595)
596
597
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800598class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000599 """
600 A class representing an SSL session. A session defines certain connection
601 parameters which may be re-used to speed up the setup of subsequent
602 connections.
603
604 .. versionadded:: 0.14
605 """
Alex Gaynor03737182020-07-23 20:40:46 -0400606
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800607 pass
608
609
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800610class Context(object):
611 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100612 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400613 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000614
615 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
616 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800617 """
Alex Gaynor03737182020-07-23 20:40:46 -0400618
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800619 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800620 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500621 SSLv3_METHOD: "SSLv3_method",
622 SSLv23_METHOD: "SSLv23_method",
623 TLSv1_METHOD: "TLSv1_method",
624 TLSv1_1_METHOD: "TLSv1_1_method",
625 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400626 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500627 _methods = dict(
628 (identifier, getattr(_lib, name))
629 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400630 if getattr(_lib, name, None) is not None
631 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800632
633 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500634 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800635 raise TypeError("method must be an integer")
636
637 try:
638 method_func = self._methods[method]
639 except KeyError:
640 raise ValueError("No such protocol")
641
642 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700643 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500645 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700646 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500647 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800648
Alex Gaynor77debda2020-04-07 13:40:59 -0400649 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
650 # auto-selected. This function was added in 1.0.2 and made a noop in
651 # 1.1.0+ (where it is set automatically).
652 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
653 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600654
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800656 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800658 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800659 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800660 self._verify_callback = None
661 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200662 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800663 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664 self._app_data = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400665 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100666 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000667 self._ocsp_helper = None
668 self._ocsp_callback = None
669 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500671 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673 def load_verify_locations(self, cafile, capath=None):
674 """
675 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000676 chain. Note that the certificates have to be in PEM format.
677
678 If capath is passed, it must be a directory prepared using the
679 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
680 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800681
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400682 :param cafile: In which file we can find the certificates (``bytes`` or
683 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400685 (``bytes`` or ``unicode``).
686
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800687 :return: None
688 """
689 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500690 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400691 else:
692 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693
694 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500695 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400696 else:
697 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800698
Alex Gaynor62da94d2015-09-05 14:37:34 -0400699 load_result = _lib.SSL_CTX_load_verify_locations(
700 self._context, cafile, capath
701 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800702 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500703 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705 def _wrap_callback(self, callback):
706 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800707 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800708 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400709
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800710 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400711 FILETYPE_PEM, wrapper, more_args=True, truncate=True
712 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714 def set_passwd_cb(self, callback, userdata=None):
715 """
Alex Chand072cae2018-02-15 09:57:59 +0000716 Set the passphrase callback. This function will be called
717 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718
Alex Chand072cae2018-02-15 09:57:59 +0000719 :param callback: The Python callback to use. This must accept three
720 positional arguments. First, an integer giving the maximum length
721 of the passphrase it may return. If the returned passphrase is
722 longer than this, it will be truncated. Second, a boolean value
723 which will be true if the user should be prompted for the
724 passphrase twice and the callback should verify that the two values
725 supplied are equal. Third, the value given as the *userdata*
726 parameter to :meth:`set_passwd_cb`. The *callback* must return
727 a byte string. If an error occurs, *callback* should return a false
728 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729 :param userdata: (optional) A Python object which will be given as
730 argument to the callback
731 :return: None
732 """
733 if not callable(callback):
734 raise TypeError("callback must be callable")
735
736 self._passphrase_helper = self._wrap_callback(callback)
737 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500738 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400739 self._context, self._passphrase_callback
740 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 self._passphrase_userdata = userdata
742
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800743 def set_default_verify_paths(self):
744 """
Alex Chand072cae2018-02-15 09:57:59 +0000745 Specify that the platform provided CA certificates are to be used for
746 verification purposes. This method has some caveats related to the
747 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
748
749 * macOS will only load certificates using this method if the user has
750 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
751 in the default location.
752 * Windows will not work.
753 * manylinux1 cryptography wheels will work on most common Linux
754 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
755 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756
757 :return: None
758 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500759 # SSL_CTX_set_default_verify_paths will attempt to load certs from
760 # both a cafile and capath that are set at compile time. However,
761 # it will first check environment variables and, if present, load
762 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500763 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400764 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500765 # After attempting to set default_verify_paths we need to know whether
766 # to go down the fallback path.
767 # First we'll check to see if any env vars have been set. If so,
768 # we won't try to do anything else because the user has set the path
769 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400770 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
771 "ascii"
772 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500773 file_env_var = _ffi.string(
774 _lib.X509_get_default_cert_file_env()
775 ).decode("ascii")
776 if not self._check_env_vars_set(dir_env_var, file_env_var):
777 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
778 default_file = _ffi.string(_lib.X509_get_default_cert_file())
779 # Now we check to see if the default_dir and default_file are set
780 # to the exact values we use in our manylinux1 builds. If they are
781 # then we know to load the fallbacks
782 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400783 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
784 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500785 ):
786 # This is manylinux1, let's load our fallback paths
787 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400788 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500789 )
790
791 def _check_env_vars_set(self, dir_env_var, file_env_var):
792 """
793 Check to see if the default cert dir/file environment vars are present.
794
795 :return: bool
796 """
797 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400798 os.environ.get(file_env_var) is not None
799 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500800 )
801
802 def _fallback_default_verify_paths(self, file_path, dir_path):
803 """
804 Default verify paths are based on the compiled version of OpenSSL.
805 However, when pyca/cryptography is compiled as a manylinux1 wheel
806 that compiled location can potentially be wrong. So, like Go, we
807 will try a predefined set of paths and attempt to load roots
808 from there.
809
810 :return: None
811 """
812 for cafile in file_path:
813 if os.path.isfile(cafile):
814 self.load_verify_locations(cafile)
815 break
816
817 for capath in dir_path:
818 if os.path.isdir(capath):
819 self.load_verify_locations(None, capath)
820 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800821
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800822 def use_certificate_chain_file(self, certfile):
823 """
Alex Chand072cae2018-02-15 09:57:59 +0000824 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400826 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000827 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400828
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829 :return: None
830 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400831 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800832
Alex Gaynor62da94d2015-09-05 14:37:34 -0400833 result = _lib.SSL_CTX_use_certificate_chain_file(
834 self._context, certfile
835 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800836 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500837 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800838
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800839 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800840 """
841 Load a certificate from a file
842
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400843 :param certfile: The name of the certificate file (``bytes`` or
844 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000845 :param filetype: (optional) The encoding of the file, which is either
846 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
847 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400848
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800849 :return: None
850 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400851 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500852 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800853 raise TypeError("filetype must be an integer")
854
Alex Gaynor62da94d2015-09-05 14:37:34 -0400855 use_result = _lib.SSL_CTX_use_certificate_file(
856 self._context, certfile, filetype
857 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800858 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500859 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800860
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800861 def use_certificate(self, cert):
862 """
863 Load a certificate from a X509 object
864
865 :param cert: The X509 object
866 :return: None
867 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800868 if not isinstance(cert, X509):
869 raise TypeError("cert must be an X509 instance")
870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500871 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800872 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500873 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800874
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800875 def add_extra_chain_cert(self, certobj):
876 """
877 Add certificate to chain
878
879 :param certobj: The X509 certificate object to add to the chain
880 :return: None
881 """
882 if not isinstance(certobj, X509):
883 raise TypeError("certobj must be an X509 instance")
884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500885 copy = _lib.X509_dup(certobj._x509)
886 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800887 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500888 # TODO: This is untested.
889 _lib.X509_free(copy)
890 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800892 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500893 if self._passphrase_helper is not None:
894 self._passphrase_helper.raise_if_problem(Error)
895
896 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800897
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400898 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899 """
900 Load a private key from a file
901
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400902 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000903 :param filetype: (optional) The encoding of the file, which is either
904 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
905 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400906
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 :return: None
908 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400909 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400911 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500913 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800914 raise TypeError("filetype must be an integer")
915
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500916 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -0400917 self._context, keyfile, filetype
918 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800920 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800921
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 def use_privatekey(self, pkey):
923 """
924 Load a private key from a PKey object
925
926 :param pkey: The PKey object
927 :return: None
928 """
929 if not isinstance(pkey, PKey):
930 raise TypeError("pkey must be a PKey instance")
931
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500932 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800933 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800934 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 def check_privatekey(self):
937 """
Alex Chand072cae2018-02-15 09:57:59 +0000938 Check if the private key (loaded with :meth:`use_privatekey`) matches
939 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940
Alex Chand072cae2018-02-15 09:57:59 +0000941 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500943 if not _lib.SSL_CTX_check_private_key(self._context):
944 _raise_current_error()
945
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946 def load_client_ca(self, cafile):
947 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100948 Load the trusted certificates that will be sent to the client. Does
949 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400950 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100952 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800953 :return: None
954 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100955 ca_list = _lib.SSL_load_client_CA_file(
956 _text_to_bytes_and_warn("cafile", cafile)
957 )
958 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100959 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960
961 def set_session_id(self, buf):
962 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100963 Set the session id to *buf* within which a session can be reused for
964 this Context object. This is needed when doing session resumption,
965 because there is no way for a stored session to know which Context
966 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100968 :param bytes buf: The session id.
969
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800970 :returns: None
971 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100972 buf = _text_to_bytes_and_warn("buf", buf)
973 _openssl_assert(
Alex Gaynor03737182020-07-23 20:40:46 -0400974 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf),)
975 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100976 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800977
978 def set_session_cache_mode(self, mode):
979 """
Alex Chand072cae2018-02-15 09:57:59 +0000980 Set the behavior of the session cache used by all connections using
981 this Context. The previously set mode is returned. See
982 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983
984 :param mode: One or more of the SESS_CACHE_* flags (combine using
985 bitwise or)
986 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +0000987
988 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500990 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 raise TypeError("mode must be an integer")
992
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995 def get_session_cache_mode(self):
996 """
Alex Chand072cae2018-02-15 09:57:59 +0000997 Get the current session cache mode.
998
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001000
1001 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001002 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001004
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001005 def set_verify(self, mode, callback):
1006 """
Alex Chand072cae2018-02-15 09:57:59 +00001007 et the verification flags for this Context object to *mode* and specify
1008 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009
Alex Chand072cae2018-02-15 09:57:59 +00001010 :param mode: The verify mode, this should be one of
1011 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1012 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1013 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1014 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1015 :param callback: The Python callback to use. This should take five
1016 arguments: A Connection object, an X509 object, and three integer
1017 variables, which are in turn potential error number, error depth
1018 and return code. *callback* should return True if verification
1019 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020 :return: None
1021
1022 See SSL_CTX_set_verify(3SSL) for further details.
1023 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001024 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025 raise TypeError("mode must be an integer")
1026
1027 if not callable(callback):
1028 raise TypeError("callback must be callable")
1029
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001030 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001031 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001032 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001034 def set_verify_depth(self, depth):
1035 """
Alex Chand072cae2018-02-15 09:57:59 +00001036 Set the maximum depth for the certificate chain verification that shall
1037 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038
1039 :param depth: An integer specifying the verify depth
1040 :return: None
1041 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001042 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 raise TypeError("depth must be an integer")
1044
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001045 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001047 def get_verify_mode(self):
1048 """
Alex Chand072cae2018-02-15 09:57:59 +00001049 Retrieve the Context object's verify mode, as set by
1050 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051
1052 :return: The verify mode
1053 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001054 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056 def get_verify_depth(self):
1057 """
Alex Chand072cae2018-02-15 09:57:59 +00001058 Retrieve the Context object's verify depth, as set by
1059 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001060
1061 :return: The verify depth
1062 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001063 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065 def load_tmp_dh(self, dhfile):
1066 """
1067 Load parameters for Ephemeral Diffie-Hellman
1068
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001069 :param dhfile: The file to load EDH parameters from (``bytes`` or
1070 ``unicode``).
1071
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072 :return: None
1073 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001074 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001076 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001078 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1082 dh = _ffi.gc(dh, _lib.DH_free)
Paul Kehrer41dc1362020-08-04 23:44:18 -05001083 res = _lib.SSL_CTX_set_tmp_dh(self._context, dh)
1084 _openssl_assert(res == 1)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001085
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001086 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001087 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001088 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001089
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001090 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001091 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1092 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001093
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001094 :return: None
1095 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001096 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001097
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098 def set_cipher_list(self, cipher_list):
1099 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001100 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001101
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001102 See the OpenSSL manual for more information (e.g.
1103 :manpage:`ciphers(1)`).
1104
1105 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001106 :return: None
1107 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001108 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001109
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001110 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001111 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001112
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001113 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001114 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001115 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001116 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1117 # ciphers even if you pass an invalid cipher. Applications (like
1118 # Twisted) have tests that depend on an error being raised if an
1119 # invalid cipher string is passed, but without the following check
1120 # for the TLS 1.3 specific cipher suites it would never error.
1121 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001122 if tmpconn.get_cipher_list() == [
1123 "TLS_AES_256_GCM_SHA384",
1124 "TLS_CHACHA20_POLY1305_SHA256",
1125 "TLS_AES_128_GCM_SHA256",
1126 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001127 raise Error(
1128 [
1129 (
Alex Gaynor03737182020-07-23 20:40:46 -04001130 "SSL routines",
1131 "SSL_CTX_set_cipher_list",
1132 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001133 ),
1134 ],
1135 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001136
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001137 def set_client_ca_list(self, certificate_authorities):
1138 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001139 Set the list of preferred client certificate signers for this server
1140 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001141
Alex Gaynor62da94d2015-09-05 14:37:34 -04001142 This list of certificate authorities will be sent to the client when
1143 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144
1145 :param certificate_authorities: a sequence of X509Names.
1146 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001147
1148 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001149 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001150 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001151 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001152
1153 try:
1154 for ca_name in certificate_authorities:
1155 if not isinstance(ca_name, X509Name):
1156 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001157 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001158 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001159 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001161 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001163 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001164 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001165 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001166 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001168 raise
1169
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001171
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001172 def add_client_ca(self, certificate_authority):
1173 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001174 Add the CA certificate to the list of preferred signers for this
1175 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001176
1177 The list of certificate authorities will be sent to the client when the
1178 server requests a client certificate.
1179
1180 :param certificate_authority: certificate authority's X509 certificate.
1181 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001182
1183 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001185 if not isinstance(certificate_authority, X509):
1186 raise TypeError("certificate_authority must be an X509 instance")
1187
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001188 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001189 self._context, certificate_authority._x509
1190 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001191 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001192
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001193 def set_timeout(self, timeout):
1194 """
Alex Chand072cae2018-02-15 09:57:59 +00001195 Set the timeout for newly created sessions for this Context object to
1196 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1197 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198
Alex Chand072cae2018-02-15 09:57:59 +00001199 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001200 :return: The previous session timeout
1201 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001202 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001203 raise TypeError("timeout must be an integer")
1204
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001205 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001206
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207 def get_timeout(self):
1208 """
Alex Chand072cae2018-02-15 09:57:59 +00001209 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1210 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001211
1212 :return: The session timeout
1213 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001214 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001216 def set_info_callback(self, callback):
1217 """
Alex Chand072cae2018-02-15 09:57:59 +00001218 Set the information callback to *callback*. This function will be
1219 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001220
Alex Chand072cae2018-02-15 09:57:59 +00001221 :param callback: The Python callback to use. This should take three
1222 arguments: a Connection object and two integers. The first integer
1223 specifies where in the SSL handshake the function was called, and
1224 the other the return code from a (possibly failed) internal
1225 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001226 :return: None
1227 """
Alex Gaynor03737182020-07-23 20:40:46 -04001228
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001229 @wraps(callback)
1230 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001231 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001232
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001233 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001234 "void (*)(const SSL *, int, int)", wrapper
1235 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001236 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001237
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001238 @_requires_keylog
1239 def set_keylog_callback(self, callback):
1240 """
1241 Set the TLS key logging callback to *callback*. This function will be
1242 called whenever TLS key material is generated or received, in order
1243 to allow applications to store this keying material for debugging
1244 purposes.
1245
1246 :param callback: The Python callback to use. This should take two
1247 arguments: a Connection object and a bytestring that contains
1248 the key material in the format used by NSS for its SSLKEYLOGFILE
1249 debugging output.
1250 :return: None
1251 """
1252
1253 @wraps(callback)
1254 def wrapper(ssl, line):
1255 line = _ffi.string(line)
1256 callback(Connection._reverse_mapping[ssl], line)
1257
1258 self._keylog_callback = _ffi.callback(
1259 "void (*)(const SSL *, const char *)", wrapper
1260 )
1261 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1262
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001263 def get_app_data(self):
1264 """
Alex Chand072cae2018-02-15 09:57:59 +00001265 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001266
1267 :return: The application data
1268 """
1269 return self._app_data
1270
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001271 def set_app_data(self, data):
1272 """
1273 Set the application data (will be returned from get_app_data())
1274
1275 :param data: Any Python object
1276 :return: None
1277 """
1278 self._app_data = data
1279
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001280 def get_cert_store(self):
1281 """
Alex Chand072cae2018-02-15 09:57:59 +00001282 Get the certificate store for the context. This can be used to add
1283 "trusted" certificates without using the
1284 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001285
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001286 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001288 store = _lib.SSL_CTX_get_cert_store(self._context)
1289 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001290 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001291 return None
1292
1293 pystore = X509Store.__new__(X509Store)
1294 pystore._store = store
1295 return pystore
1296
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001297 def set_options(self, options):
1298 """
1299 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001300 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001301
1302 :param options: The options to add.
1303 :return: The new option bitmask.
1304 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001305 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001306 raise TypeError("options must be an integer")
1307
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001308 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001310 def set_mode(self, mode):
1311 """
Alex Chand072cae2018-02-15 09:57:59 +00001312 Add modes via bitmask. Modes set before are not cleared! This method
1313 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001314
1315 :param mode: The mode to add.
1316 :return: The new mode bitmask.
1317 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001318 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001319 raise TypeError("mode must be an integer")
1320
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001321 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001322
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001323 def set_tlsext_servername_callback(self, callback):
1324 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001325 Specify a callback function to be called when clients specify a server
1326 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001327
1328 :param callback: The callback function. It will be invoked with one
1329 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001330
1331 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001332 """
Alex Gaynor03737182020-07-23 20:40:46 -04001333
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001334 @wraps(callback)
1335 def wrapper(ssl, alert, arg):
1336 callback(Connection._reverse_mapping[ssl])
1337 return 0
1338
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001339 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001340 "int (*)(SSL *, int *, void *)", wrapper
1341 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001342 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001343 self._context, self._tlsext_servername_callback
1344 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001345
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001346 def set_tlsext_use_srtp(self, profiles):
1347 """
1348 Enable support for negotiating SRTP keying material.
1349
1350 :param bytes profiles: A colon delimited list of protection profile
1351 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1352 :return: None
1353 """
1354 if not isinstance(profiles, bytes):
1355 raise TypeError("profiles must be a byte string.")
1356
1357 _openssl_assert(
1358 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1359 )
1360
Cory Benfield7907e332015-04-13 17:18:25 -04001361 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001362 def set_alpn_protos(self, protos):
1363 """
Alex Chand072cae2018-02-15 09:57:59 +00001364 Specify the protocols that the client is prepared to speak after the
1365 TLS connection has been negotiated using Application Layer Protocol
1366 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001367
1368 :param protos: A list of the protocols to be offered to the server.
1369 This list should be a Python list of bytestrings representing the
1370 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1371 """
1372 # Take the list of protocols and join them together, prefixing them
1373 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001374 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001375 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1376 )
1377
1378 # Build a C string from the list. We don't need to save this off
1379 # because OpenSSL immediately copies the data out.
1380 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001381 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001382
Cory Benfield7907e332015-04-13 17:18:25 -04001383 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001384 def set_alpn_select_callback(self, callback):
1385 """
Alex Chand072cae2018-02-15 09:57:59 +00001386 Specify a callback function that will be called on the server when a
1387 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001388
1389 :param callback: The callback function. It will be invoked with two
1390 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001391 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1392 one of those bytestrings to indicate the chosen protocol, the
1393 empty bytestring to terminate the TLS connection, or the
1394 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1395 protocol was selected, but that the connection should not be
1396 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001397 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001398 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001399 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001400 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001401 self._context, self._alpn_select_callback, _ffi.NULL
1402 )
Cory Benfield12eae892014-06-07 15:42:56 +01001403
Cory Benfield496652a2017-01-24 11:42:56 +00001404 def _set_ocsp_callback(self, helper, data):
1405 """
1406 This internal helper does the common work for
1407 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1408 almost all of it.
1409 """
1410 self._ocsp_helper = helper
1411 self._ocsp_callback = helper.callback
1412 if data is None:
1413 self._ocsp_data = _ffi.NULL
1414 else:
1415 self._ocsp_data = _ffi.new_handle(data)
1416
1417 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1418 self._context, self._ocsp_callback
1419 )
1420 _openssl_assert(rc == 1)
1421 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1422 _openssl_assert(rc == 1)
1423
1424 def set_ocsp_server_callback(self, callback, data=None):
1425 """
1426 Set a callback to provide OCSP data to be stapled to the TLS handshake
1427 on the server side.
1428
1429 :param callback: The callback function. It will be invoked with two
1430 arguments: the Connection, and the optional arbitrary data you have
1431 provided. The callback must return a bytestring that contains the
1432 OCSP data to staple to the handshake. If no OCSP data is available
1433 for this connection, return the empty bytestring.
1434 :param data: Some opaque data that will be passed into the callback
1435 function when called. This can be used to avoid needing to do
1436 complex data lookups or to keep track of what context is being
1437 used. This parameter is optional.
1438 """
1439 helper = _OCSPServerCallbackHelper(callback)
1440 self._set_ocsp_callback(helper, data)
1441
1442 def set_ocsp_client_callback(self, callback, data=None):
1443 """
1444 Set a callback to validate OCSP data stapled to the TLS handshake on
1445 the client side.
1446
1447 :param callback: The callback function. It will be invoked with three
1448 arguments: the Connection, a bytestring containing the stapled OCSP
1449 assertion, and the optional arbitrary data you have provided. The
1450 callback must return a boolean that indicates the result of
1451 validating the OCSP data: ``True`` if the OCSP data is valid and
1452 the certificate can be trusted, or ``False`` if either the OCSP
1453 data is invalid or the certificate has been revoked.
1454 :param data: Some opaque data that will be passed into the callback
1455 function when called. This can be used to avoid needing to do
1456 complex data lookups or to keep track of what context is being
1457 used. This parameter is optional.
1458 """
1459 helper = _OCSPClientCallbackHelper(callback)
1460 self._set_ocsp_callback(helper, data)
1461
Alex Chanc6077062016-11-18 13:53:39 +00001462
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463class Connection(object):
1464 """
1465 """
Alex Gaynor03737182020-07-23 20:40:46 -04001466
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 _reverse_mapping = WeakValueDictionary()
1468
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469 def __init__(self, context, socket=None):
1470 """
1471 Create a new Connection object, using the given OpenSSL.SSL.Context
1472 instance and socket.
1473
1474 :param context: An SSL Context to use for this connection
1475 :param socket: The socket to use for transport layer
1476 """
1477 if not isinstance(context, Context):
1478 raise TypeError("context must be a Context instance")
1479
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001480 ssl = _lib.SSL_new(context._context)
1481 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001482 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1483 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1484 # even though there is still data on the underlying transport.
1485 # See https://github.com/openssl/openssl/issues/6234 for more details.
1486 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001487 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001488 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001489
Cory Benfield12eae892014-06-07 15:42:56 +01001490 # References to strings used for Application Layer Protocol
1491 # Negotiation. These strings get copied at some point but it's well
1492 # after the callback returns, so we have to hang them somewhere to
1493 # avoid them getting freed.
1494 self._alpn_select_callback_args = None
1495
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001496 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001497
1498 if socket is None:
1499 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001500 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001501 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001502 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001503
Alex Gaynora829e902016-06-04 18:16:01 -07001504 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1505 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001506
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001507 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001508 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001509 self._into_ssl = None
1510 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001511 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001512 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001513 self._ssl, _asFileDescriptor(self._socket)
1514 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001515 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517 def __getattr__(self, name):
1518 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001519 Look up attributes on the wrapped socket object if they are not found
1520 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521 """
kjav0b66fa12015-09-02 11:51:26 +01001522 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001523 raise AttributeError(
1524 "'%s' object has no attribute '%s'"
1525 % (self.__class__.__name__, name)
1526 )
kjav0b66fa12015-09-02 11:51:26 +01001527 else:
1528 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001529
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001530 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001531 if self._context._verify_helper is not None:
1532 self._context._verify_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001533 if self._context._alpn_select_helper is not None:
1534 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001535 if self._context._ocsp_helper is not None:
1536 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001537
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001538 error = _lib.SSL_get_error(ssl, result)
1539 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001540 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001541 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001542 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001543 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001544 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001545 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001546 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001547 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001548 elif error == _lib.SSL_ERROR_SYSCALL:
1549 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001550 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001551 if platform == "win32":
1552 errno = _ffi.getwinerror()[0]
1553 else:
1554 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001555
1556 if errno != 0:
1557 raise SysCallError(errno, errorcode.get(errno))
1558 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001559 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001560 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001561 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001562 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001563 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001564 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001565 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001566
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 def get_context(self):
1568 """
Alex Chand072cae2018-02-15 09:57:59 +00001569 Retrieve the :class:`Context` object associated with this
1570 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001571 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001572 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001573
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001574 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001575 """
Alex Chand072cae2018-02-15 09:57:59 +00001576 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001577
Alex Chand072cae2018-02-15 09:57:59 +00001578 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001579 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001580 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581 if not isinstance(context, Context):
1582 raise TypeError("context must be a Context instance")
1583
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001584 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001585 self._context = context
1586
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587 def get_servername(self):
1588 """
1589 Retrieve the servername extension value if provided in the client hello
1590 message, or None if there wasn't one.
1591
Alex Chand072cae2018-02-15 09:57:59 +00001592 :return: A byte string giving the server name or :data:`None`.
1593
1594 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001595 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001596 name = _lib.SSL_get_servername(
1597 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1598 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001600 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001601
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001602 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001603
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001605 """
1606 Set the value of the servername extension to send in the client hello.
1607
1608 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001609
1610 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001611 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001612 if not isinstance(name, bytes):
1613 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001614 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001615 raise TypeError("name must not contain NUL byte")
1616
1617 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001618 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620 def pending(self):
1621 """
Alex Chand072cae2018-02-15 09:57:59 +00001622 Get the number of bytes that can be safely read from the SSL buffer
1623 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001624
1625 :return: The number of bytes available in the receive buffer.
1626 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001627 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001628
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001629 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001630 """
1631 Send data on the connection. NOTE: If you get one of the WantRead,
1632 WantWrite or WantX509Lookup exceptions on this, you have to call the
1633 method again with the SAME buffer.
1634
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001635 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001636 :param flags: (optional) Included for compatibility with the socket
1637 API, the value is ignored
1638 :return: The number of bytes written
1639 """
Abraham Martine82326c2015-02-04 10:18:10 +00001640 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001641 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001642
Daniel Holth079c9632019-11-17 22:45:52 -05001643 with _from_buffer(buf) as data:
1644 # check len(buf) instead of len(data) for testability
1645 if len(buf) > 2147483647:
1646 raise ValueError(
1647 "Cannot send more than 2**31-1 bytes at once."
1648 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001649
Daniel Holth079c9632019-11-17 22:45:52 -05001650 result = _lib.SSL_write(self._ssl, data, len(data))
1651 self._raise_ssl_error(self._ssl, result)
1652
1653 return result
1654
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655 write = send
1656
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001658 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001659 Send "all" data on the connection. This calls send() repeatedly until
1660 all data is sent. If an error occurs, it's impossible to tell how much
1661 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001663 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001664 :param flags: (optional) Included for compatibility with the socket
1665 API, the value is ignored
1666 :return: The number of bytes written
1667 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001668 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001669
Daniel Holth079c9632019-11-17 22:45:52 -05001670 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671
Daniel Holth079c9632019-11-17 22:45:52 -05001672 left_to_send = len(buf)
1673 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674
Daniel Holth079c9632019-11-17 22:45:52 -05001675 while left_to_send:
1676 # SSL_write's num arg is an int,
1677 # so we cannot send more than 2**31-1 bytes at once.
1678 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001679 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001680 )
1681 self._raise_ssl_error(self._ssl, result)
1682 total_sent += result
1683 left_to_send -= result
1684
1685 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001686
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001687 def recv(self, bufsiz, flags=None):
1688 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001689 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001690
1691 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001692 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1693 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001694 :return: The string read from the Connection
1695 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001696 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001697 if flags is not None and flags & socket.MSG_PEEK:
1698 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1699 else:
1700 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001701 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001702 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001703
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001704 read = recv
1705
Cory Benfield62d10332014-06-15 10:03:41 +01001706 def recv_into(self, buffer, nbytes=None, flags=None):
1707 """
Alex Chand072cae2018-02-15 09:57:59 +00001708 Receive data on the connection and copy it directly into the provided
1709 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001710
1711 :param buffer: The buffer to copy into.
1712 :param nbytes: (optional) The maximum number of bytes to read into the
1713 buffer. If not present, defaults to the size of the buffer. If
1714 larger than the size of the buffer, is reduced to the size of the
1715 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001716 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1717 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001718 :return: The number of bytes read into the buffer.
1719 """
1720 if nbytes is None:
1721 nbytes = len(buffer)
1722 else:
1723 nbytes = min(nbytes, len(buffer))
1724
1725 # We need to create a temporary buffer. This is annoying, it would be
1726 # better if we could pass memoryviews straight into the SSL_read call,
1727 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001728 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001729 if flags is not None and flags & socket.MSG_PEEK:
1730 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1731 else:
1732 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001733 self._raise_ssl_error(self._ssl, result)
1734
1735 # This strange line is all to avoid a memory copy. The buffer protocol
1736 # should allow us to assign a CFFI buffer to the LHS of this line, but
1737 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001738 # wrap it in a memoryview.
1739 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001740
1741 return result
1742
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001743 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001744 if _lib.BIO_should_retry(bio):
1745 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001746 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001747 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001748 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001749 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001750 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001751 # TODO: This is untested. I think io_special means the socket
1752 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001753 raise ValueError("BIO_should_io_special")
1754 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001755 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001756 raise ValueError("unknown bio failure")
1757 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001758 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001759 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001760
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001762 """
Alex Chand072cae2018-02-15 09:57:59 +00001763 If the Connection was created with a memory BIO, this method can be
1764 used to read bytes from the write end of that memory BIO. Many
1765 Connection methods will add bytes which must be read in this manner or
1766 the buffer will eventually fill up and the Connection will be able to
1767 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768
1769 :param bufsiz: The maximum number of bytes to read
1770 :return: The string read.
1771 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001772 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001773 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001774
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001775 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001776 raise TypeError("bufsiz must be an integer")
1777
Cory Benfielde62840e2016-11-28 12:17:08 +00001778 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001779 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780 if result <= 0:
1781 self._handle_bio_errors(self._from_ssl, result)
1782
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001783 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001784
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001785 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001786 """
Alex Chand072cae2018-02-15 09:57:59 +00001787 If the Connection was created with a memory BIO, this method can be
1788 used to add bytes to the read end of that memory BIO. The Connection
1789 can then read the bytes (for example, in response to a call to
1790 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001791
1792 :param buf: The string to put into the memory BIO.
1793 :return: The number of bytes written
1794 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001795 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001796
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001797 if self._into_ssl is None:
1798 raise TypeError("Connection sock was not None")
1799
Daniel Holth079c9632019-11-17 22:45:52 -05001800 with _from_buffer(buf) as data:
1801 result = _lib.BIO_write(self._into_ssl, data, len(data))
1802 if result <= 0:
1803 self._handle_bio_errors(self._into_ssl, result)
1804 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001805
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001806 def renegotiate(self):
1807 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001808 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001810 :return: True if the renegotiation can be started, False otherwise
1811 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001812 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001813 if not self.renegotiate_pending():
1814 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1815 return True
1816 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001817
1818 def do_handshake(self):
1819 """
Alex Chand072cae2018-02-15 09:57:59 +00001820 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001821 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001822 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823
1824 :return: None.
1825 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001826 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001827 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001828
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001829 def renegotiate_pending(self):
1830 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001831 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001832 a renegotiation is finished.
1833
1834 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001835 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001836 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001837 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001838
1839 def total_renegotiations(self):
1840 """
1841 Find out the total number of renegotiations.
1842
1843 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001844 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001845 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001846 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001847
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001848 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001849 """
Alex Chand072cae2018-02-15 09:57:59 +00001850 Call the :meth:`connect` method of the underlying socket and set up SSL
1851 on the socket, using the :class:`Context` object supplied to this
1852 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001853
1854 :param addr: A remote address
1855 :return: What the socket's connect method returns
1856 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001857 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001858 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001859
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001860 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001861 """
Alex Chand072cae2018-02-15 09:57:59 +00001862 Call the :meth:`connect_ex` method of the underlying socket and set up
1863 SSL on the socket, using the Context object supplied to this Connection
1864 object at creation. Note that if the :meth:`connect_ex` method of the
1865 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866
1867 :param addr: A remove address
1868 :return: What the socket's connect_ex method returns
1869 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001870 connect_ex = self._socket.connect_ex
1871 self.set_connect_state()
1872 return connect_ex(addr)
1873
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001874 def accept(self):
1875 """
Alex Chand072cae2018-02-15 09:57:59 +00001876 Call the :meth:`accept` method of the underlying socket and set up SSL
1877 on the returned socket, using the Context object supplied to this
1878 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879
Alex Chand072cae2018-02-15 09:57:59 +00001880 :return: A *(conn, addr)* pair where *conn* is the new
1881 :class:`Connection` object created, and *address* is as returned by
1882 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001883 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001884 client, addr = self._socket.accept()
1885 conn = Connection(self._context, client)
1886 conn.set_accept_state()
1887 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001888
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889 def bio_shutdown(self):
1890 """
Alex Chand072cae2018-02-15 09:57:59 +00001891 If the Connection was created with a memory BIO, this method can be
1892 used to indicate that *end of file* has been reached on the read end of
1893 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001894
1895 :return: None
1896 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001897 if self._from_ssl is None:
1898 raise TypeError("Connection sock was not None")
1899
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001900 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001901
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001902 def shutdown(self):
1903 """
Alex Chand072cae2018-02-15 09:57:59 +00001904 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001905
1906 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001907 have sent closure alerts), False otherwise (in which case you
1908 call :meth:`recv` or :meth:`send` when the connection becomes
1909 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001910 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001911 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001913 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001914 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001915 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916 else:
1917 return False
1918
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001919 def get_cipher_list(self):
1920 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001921 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001922
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001923 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001924 """
1925 ciphers = []
1926 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001927 result = _lib.SSL_get_cipher_list(self._ssl, i)
1928 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001930 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001931 return ciphers
1932
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001933 def get_client_ca_list(self):
1934 """
1935 Get CAs whose certificates are suggested for client authentication.
1936
Alex Chand072cae2018-02-15 09:57:59 +00001937 :return: If this is a server connection, the list of certificate
1938 authorities that will be sent or has been sent to the client, as
1939 controlled by this :class:`Connection`'s :class:`Context`.
1940
1941 If this is a client connection, the list will be empty until the
1942 connection with the server is established.
1943
1944 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001945 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001946 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1947 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001948 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001949 return []
1950
1951 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001952 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1953 name = _lib.sk_X509_NAME_value(ca_names, i)
1954 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001955 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001956
1957 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001958 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001959 result.append(pyname)
1960 return result
1961
Aykee7f33452018-05-16 19:18:16 +02001962 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001963 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001964 The makefile() method is not implemented, since there is no dup
1965 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001967 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968 """
Alex Gaynor83284952015-09-05 10:43:30 -04001969 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04001970 "Cannot make file object of OpenSSL.SSL.Connection"
1971 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001972
1973 def get_app_data(self):
1974 """
Alex Chand072cae2018-02-15 09:57:59 +00001975 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001976
1977 :return: The application data
1978 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001979 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001981 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982 """
1983 Set application data
1984
Alex Chand072cae2018-02-15 09:57:59 +00001985 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001986 :return: None
1987 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001988 self._app_data = data
1989
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990 def get_shutdown(self):
1991 """
Alex Chand072cae2018-02-15 09:57:59 +00001992 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993
Alex Gaynor62da94d2015-09-05 14:37:34 -04001994 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1995 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001996 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001997 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001998
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001999 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002000 """
Alex Chand072cae2018-02-15 09:57:59 +00002001 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002002
Alex Chand072cae2018-02-15 09:57:59 +00002003 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 :return: None
2005 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002006 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002007 raise TypeError("state must be an integer")
2008
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002009 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002010
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002011 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002012 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002013 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002014
2015 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002016 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002017 """
kjavc704a2e2015-09-07 12:12:27 +01002018 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019
2020 def server_random(self):
2021 """
Alex Chand072cae2018-02-15 09:57:59 +00002022 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002023
2024 :return: A string representing the state
2025 """
Alex Gaynor93603062016-06-01 20:13:09 -07002026 session = _lib.SSL_get_session(self._ssl)
2027 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002028 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002029 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002030 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002031 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002032 _lib.SSL_get_server_random(self._ssl, outp, length)
2033 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002034
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035 def client_random(self):
2036 """
Alex Chand072cae2018-02-15 09:57:59 +00002037 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002038
2039 :return: A string representing the state
2040 """
Alex Gaynor93603062016-06-01 20:13:09 -07002041 session = _lib.SSL_get_session(self._ssl)
2042 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002043 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002044
2045 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002046 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002047 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002048 _lib.SSL_get_client_random(self._ssl, outp, length)
2049 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002050
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002051 def master_key(self):
2052 """
Alex Chand072cae2018-02-15 09:57:59 +00002053 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002054
2055 :return: A string representing the state
2056 """
Alex Gaynor93603062016-06-01 20:13:09 -07002057 session = _lib.SSL_get_session(self._ssl)
2058 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002059 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002060
2061 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002062 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002063 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002064 _lib.SSL_SESSION_get_master_key(session, outp, length)
2065 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002066
Paul Kehrerbdb76392017-12-01 04:54:32 +08002067 def export_keying_material(self, label, olen, context=None):
2068 """
2069 Obtain keying material for application use.
2070
Alex Chand072cae2018-02-15 09:57:59 +00002071 :param: label - a disambiguating label string as described in RFC 5705
2072 :param: olen - the length of the exported key material in bytes
2073 :param: context - a per-association context value
2074 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002075 """
2076 outp = _no_zero_allocator("unsigned char[]", olen)
2077 context_buf = _ffi.NULL
2078 context_len = 0
2079 use_context = 0
2080 if context is not None:
2081 context_buf = context
2082 context_len = len(context)
2083 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002084 success = _lib.SSL_export_keying_material(
2085 self._ssl,
2086 outp,
2087 olen,
2088 label,
2089 len(label),
2090 context_buf,
2091 context_len,
2092 use_context,
2093 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002094 _openssl_assert(success == 1)
2095 return _ffi.buffer(outp, olen)[:]
2096
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002097 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002098 """
Alex Chand072cae2018-02-15 09:57:59 +00002099 Call the :meth:`shutdown` method of the underlying socket.
2100 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002101
2102 :return: What the socket's shutdown() method returns
2103 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002104 return self._socket.shutdown(*args, **kwargs)
2105
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002106 def get_certificate(self):
2107 """
2108 Retrieve the local certificate (if any)
2109
2110 :return: The local certificate
2111 """
2112 cert = _lib.SSL_get_certificate(self._ssl)
2113 if cert != _ffi.NULL:
2114 _lib.X509_up_ref(cert)
2115 return X509._from_raw_x509_ptr(cert)
2116 return None
2117
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002118 def get_peer_certificate(self):
2119 """
2120 Retrieve the other side's certificate (if any)
2121
2122 :return: The peer's certificate
2123 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002124 cert = _lib.SSL_get_peer_certificate(self._ssl)
2125 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002126 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002127 return None
2128
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002129 def get_peer_cert_chain(self):
2130 """
2131 Retrieve the other side's certificate (if any)
2132
2133 :return: A list of X509 instances giving the peer's certificate chain,
2134 or None if it does not have one.
2135 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002136 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2137 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002138 return None
2139
2140 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002141 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002142 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002143 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002144 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002145 result.append(pycert)
2146 return result
2147
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002148 def want_read(self):
2149 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002150 Checks if more data has to be read from the transport layer to complete
2151 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002152
2153 :return: True iff more data has to be read
2154 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002155 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002156
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002157 def want_write(self):
2158 """
2159 Checks if there is data to write to the transport layer to complete an
2160 operation.
2161
2162 :return: True iff there is data to write
2163 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002164 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002165
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002166 def set_accept_state(self):
2167 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002168 Set the connection to work in server mode. The handshake will be
2169 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002170
2171 :return: None
2172 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002173 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002174
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002175 def set_connect_state(self):
2176 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002177 Set the connection to work in client mode. The handshake will be
2178 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002179
2180 :return: None
2181 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002182 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002183
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002184 def get_session(self):
2185 """
2186 Returns the Session currently used.
2187
Alex Chand072cae2018-02-15 09:57:59 +00002188 :return: An instance of :class:`OpenSSL.SSL.Session` or
2189 :obj:`None` if no session exists.
2190
2191 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002192 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002193 session = _lib.SSL_get1_session(self._ssl)
2194 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002195 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002197 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002198 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002199 return pysession
2200
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002201 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002202 """
2203 Set the session to be used when the TLS/SSL connection is established.
2204
2205 :param session: A Session instance representing the session to use.
2206 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002207
2208 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002209 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002210 if not isinstance(session, Session):
2211 raise TypeError("session must be a Session instance")
2212
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002213 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002214 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002215
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002216 def _get_finished_message(self, function):
2217 """
Alex Chand072cae2018-02-15 09:57:59 +00002218 Helper to implement :meth:`get_finished` and
2219 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002220
Alex Chand072cae2018-02-15 09:57:59 +00002221 :param function: Either :data:`SSL_get_finished`: or
2222 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002223
Alex Chand072cae2018-02-15 09:57:59 +00002224 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002225 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002226 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002227 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002228 # The OpenSSL documentation says nothing about what might happen if the
2229 # count argument given is zero. Specifically, it doesn't say whether
2230 # the output buffer may be NULL in that case or not. Inspection of the
2231 # implementation reveals that it calls memcpy() unconditionally.
2232 # Section 7.1.4, paragraph 1 of the C standard suggests that
2233 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2234 # alone desirable) behavior (though it probably does on just about
2235 # every implementation...)
2236 #
2237 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2238 # one might expect) for the initial call so as to be safe against this
2239 # potentially undefined behavior.
2240 empty = _ffi.new("char[]", 0)
2241 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002242 if size == 0:
2243 # No Finished message so far.
2244 return None
2245
Cory Benfielde62840e2016-11-28 12:17:08 +00002246 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002247 function(self._ssl, buf, size)
2248 return _ffi.buffer(buf, size)[:]
2249
Fedor Brunner5747b932014-03-05 14:22:34 +01002250 def get_finished(self):
2251 """
Alex Chand072cae2018-02-15 09:57:59 +00002252 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002253
Alex Chand072cae2018-02-15 09:57:59 +00002254 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002255 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002256 :rtype: :class:`bytes` or :class:`NoneType`
2257
2258 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002259 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002260 return self._get_finished_message(_lib.SSL_get_finished)
2261
Fedor Brunner5747b932014-03-05 14:22:34 +01002262 def get_peer_finished(self):
2263 """
Alex Chand072cae2018-02-15 09:57:59 +00002264 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002265
Alex Chand072cae2018-02-15 09:57:59 +00002266 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002267 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002268 :rtype: :class:`bytes` or :class:`NoneType`
2269
2270 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002271 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002272 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002273
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002274 def get_cipher_name(self):
2275 """
2276 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002277
Alex Chand072cae2018-02-15 09:57:59 +00002278 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002279 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002280 :rtype: :class:`unicode` or :class:`NoneType`
2281
2282 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002283 """
2284 cipher = _lib.SSL_get_current_cipher(self._ssl)
2285 if cipher == _ffi.NULL:
2286 return None
2287 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002288 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2289 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002290
2291 def get_cipher_bits(self):
2292 """
2293 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002294
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002295 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002296 or :obj:`None` if no connection has been established.
2297 :rtype: :class:`int` or :class:`NoneType`
2298
2299 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002300 """
2301 cipher = _lib.SSL_get_current_cipher(self._ssl)
2302 if cipher == _ffi.NULL:
2303 return None
2304 else:
2305 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2306
2307 def get_cipher_version(self):
2308 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002309 Obtain the protocol version of the currently used cipher.
2310
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002311 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002312 or :obj:`None` if no connection has been established.
2313 :rtype: :class:`unicode` or :class:`NoneType`
2314
2315 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002316 """
2317 cipher = _lib.SSL_get_current_cipher(self._ssl)
2318 if cipher == _ffi.NULL:
2319 return None
2320 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002321 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002322 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002323
Jim Shaverabff1882015-05-27 09:15:55 -04002324 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002325 """
Alex Chand072cae2018-02-15 09:57:59 +00002326 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002327
2328 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002329 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002330 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002331 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002332 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002333 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002334 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002335
Jim Shaver208438c2015-05-28 09:52:38 -04002336 def get_protocol_version(self):
2337 """
Alex Chand072cae2018-02-15 09:57:59 +00002338 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002339
Alex Chand072cae2018-02-15 09:57:59 +00002340 :returns: The TLS version of the current connection. For example,
2341 it will return ``0x769`` for connections made over TLS version 1.
2342 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002343 """
2344 version = _lib.SSL_version(self._ssl)
2345 return version
2346
Cory Benfield7907e332015-04-13 17:18:25 -04002347 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002348 def set_alpn_protos(self, protos):
2349 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002350 Specify the client's ALPN protocol list.
2351
2352 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002353
2354 :param protos: A list of the protocols to be offered to the server.
2355 This list should be a Python list of bytestrings representing the
2356 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2357 """
2358 # Take the list of protocols and join them together, prefixing them
2359 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002360 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002361 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2362 )
2363
2364 # Build a C string from the list. We don't need to save this off
2365 # because OpenSSL immediately copies the data out.
2366 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002367 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002368
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002369 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002370 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002371 """
2372 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002373
2374 :returns: A bytestring of the protocol name. If no protocol has been
2375 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002376 """
Cory Benfield12eae892014-06-07 15:42:56 +01002377 data = _ffi.new("unsigned char **")
2378 data_len = _ffi.new("unsigned int *")
2379
2380 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2381
Cory Benfielde8e9c382015-04-11 17:33:48 -04002382 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002383 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002384
Cory Benfield12eae892014-06-07 15:42:56 +01002385 return _ffi.buffer(data[0], data_len[0])[:]
2386
Cory Benfield496652a2017-01-24 11:42:56 +00002387 def request_ocsp(self):
2388 """
2389 Called to request that the server sends stapled OCSP data, if
2390 available. If this is not called on the client side then the server
2391 will not send OCSP data. Should be used in conjunction with
2392 :meth:`Context.set_ocsp_client_callback`.
2393 """
2394 rc = _lib.SSL_set_tlsext_status_type(
2395 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2396 )
2397 _openssl_assert(rc == 1)
2398
Cory Benfield12eae892014-06-07 15:42:56 +01002399
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002400# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2401# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002402_lib.SSL_library_init()