blob: ed20d302d801223572c3b491c81775f971fc9804 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Alex Gaynorbe2bd542019-02-21 21:41:22 -05003import warnings
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02004from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05005from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01006from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08007from weakref import WeakValueDictionary
8from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08009
Alex Gaynor12576002019-11-18 00:18:50 -050010from six import integer_types, int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
Daniel Holth079c9632019-11-17 22:45:52 -050016 from_buffer as _from_buffer,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010018 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010019 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040020 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000022 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040023)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080024
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025from OpenSSL.crypto import (
Alex Gaynor03737182020-07-23 20:40:46 -040026 FILETYPE_PEM,
27 _PassphraseHelper,
28 PKey,
29 X509Name,
30 X509,
31 X509Store,
32)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080033
Nicolas Karolak736c6212017-11-26 14:40:28 +010034__all__ = [
Alex Gaynor03737182020-07-23 20:40:46 -040035 "OPENSSL_VERSION_NUMBER",
36 "SSLEAY_VERSION",
37 "SSLEAY_CFLAGS",
38 "SSLEAY_PLATFORM",
39 "SSLEAY_DIR",
40 "SSLEAY_BUILT_ON",
41 "SENT_SHUTDOWN",
42 "RECEIVED_SHUTDOWN",
43 "SSLv2_METHOD",
44 "SSLv3_METHOD",
45 "SSLv23_METHOD",
46 "TLSv1_METHOD",
47 "TLSv1_1_METHOD",
48 "TLSv1_2_METHOD",
49 "OP_NO_SSLv2",
50 "OP_NO_SSLv3",
51 "OP_NO_TLSv1",
52 "OP_NO_TLSv1_1",
53 "OP_NO_TLSv1_2",
54 "OP_NO_TLSv1_3",
55 "MODE_RELEASE_BUFFERS",
56 "OP_SINGLE_DH_USE",
57 "OP_SINGLE_ECDH_USE",
58 "OP_EPHEMERAL_RSA",
59 "OP_MICROSOFT_SESS_ID_BUG",
60 "OP_NETSCAPE_CHALLENGE_BUG",
61 "OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
62 "OP_SSLREF2_REUSE_CERT_TYPE_BUG",
63 "OP_MICROSOFT_BIG_SSLV3_BUFFER",
64 "OP_MSIE_SSLV2_RSA_PADDING",
65 "OP_SSLEAY_080_CLIENT_DH_BUG",
66 "OP_TLS_D5_BUG",
67 "OP_TLS_BLOCK_PADDING_BUG",
68 "OP_DONT_INSERT_EMPTY_FRAGMENTS",
69 "OP_CIPHER_SERVER_PREFERENCE",
70 "OP_TLS_ROLLBACK_BUG",
71 "OP_PKCS1_CHECK_1",
72 "OP_PKCS1_CHECK_2",
73 "OP_NETSCAPE_CA_DN_BUG",
74 "OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
75 "OP_NO_COMPRESSION",
76 "OP_NO_QUERY_MTU",
77 "OP_COOKIE_EXCHANGE",
78 "OP_NO_TICKET",
79 "OP_ALL",
80 "VERIFY_PEER",
81 "VERIFY_FAIL_IF_NO_PEER_CERT",
82 "VERIFY_CLIENT_ONCE",
83 "VERIFY_NONE",
84 "SESS_CACHE_OFF",
85 "SESS_CACHE_CLIENT",
86 "SESS_CACHE_SERVER",
87 "SESS_CACHE_BOTH",
88 "SESS_CACHE_NO_AUTO_CLEAR",
89 "SESS_CACHE_NO_INTERNAL_LOOKUP",
90 "SESS_CACHE_NO_INTERNAL_STORE",
91 "SESS_CACHE_NO_INTERNAL",
92 "SSL_ST_CONNECT",
93 "SSL_ST_ACCEPT",
94 "SSL_ST_MASK",
95 "SSL_CB_LOOP",
96 "SSL_CB_EXIT",
97 "SSL_CB_READ",
98 "SSL_CB_WRITE",
99 "SSL_CB_ALERT",
100 "SSL_CB_READ_ALERT",
101 "SSL_CB_WRITE_ALERT",
102 "SSL_CB_ACCEPT_LOOP",
103 "SSL_CB_ACCEPT_EXIT",
104 "SSL_CB_CONNECT_LOOP",
105 "SSL_CB_CONNECT_EXIT",
106 "SSL_CB_HANDSHAKE_START",
107 "SSL_CB_HANDSHAKE_DONE",
108 "Error",
109 "WantReadError",
110 "WantWriteError",
111 "WantX509LookupError",
112 "ZeroReturnError",
113 "SysCallError",
114 "SSLeay_version",
115 "Session",
116 "Context",
117 "Connection",
Nicolas Karolak736c6212017-11-26 14:40:28 +0100118]
119
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500120try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200121 _buffer = buffer
122except NameError:
Alex Gaynor03737182020-07-23 20:40:46 -0400123
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200124 class _buffer(object):
125 pass
126
Alex Gaynor03737182020-07-23 20:40:46 -0400127
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
129SSLEAY_VERSION = _lib.SSLEAY_VERSION
130SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
131SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
132SSLEAY_DIR = _lib.SSLEAY_DIR
133SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800134
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500135SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
136RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
138SSLv2_METHOD = 1
139SSLv3_METHOD = 2
140SSLv23_METHOD = 3
141TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500142TLSv1_1_METHOD = 5
143TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800144
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500145OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
146OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
147OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700148OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
149OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700150try:
151 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
152except AttributeError:
153 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800154
Alex Gaynorbf012872016-06-04 13:18:39 -0700155MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800156
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500157OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900158OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500159OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
160OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
161OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400162OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
163 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
164)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500165OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
166OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400167OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500168OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
169OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
170OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
171OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
172OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
173OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
174OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
175OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
176OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400177OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
178 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
179)
Alex Gaynorbf012872016-06-04 13:18:39 -0700180OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800181
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500182OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
183OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400184OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800185
Alex Gaynorc4889812015-09-04 08:43:17 -0400186OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800187
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500188VERIFY_PEER = _lib.SSL_VERIFY_PEER
189VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
190VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
191VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800192
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500193SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
194SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
195SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
196SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
197SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
198SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
199SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
200SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800201
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500202SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
203SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
204SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400205if _lib.Cryptography_HAS_SSL_ST:
206 SSL_ST_INIT = _lib.SSL_ST_INIT
207 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
208 SSL_ST_OK = _lib.SSL_ST_OK
209 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Alex Gaynor03737182020-07-23 20:40:46 -0400210 __all__.extend(
211 ["SSL_ST_INIT", "SSL_ST_BEFORE", "SSL_ST_OK", "SSL_ST_RENEGOTIATE"]
212 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800213
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500214SSL_CB_LOOP = _lib.SSL_CB_LOOP
215SSL_CB_EXIT = _lib.SSL_CB_EXIT
216SSL_CB_READ = _lib.SSL_CB_READ
217SSL_CB_WRITE = _lib.SSL_CB_WRITE
218SSL_CB_ALERT = _lib.SSL_CB_ALERT
219SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
220SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
221SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
222SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
223SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
224SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
225SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
226SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800227
Paul Kehrer55fb3412017-06-29 18:44:08 -0500228# Taken from https://golang.org/src/crypto/x509/root_linux.go
229_CERTIFICATE_FILE_LOCATIONS = [
230 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
231 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
232 "/etc/ssl/ca-bundle.pem", # OpenSUSE
233 "/etc/pki/tls/cacert.pem", # OpenELEC
234 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
235]
236
237_CERTIFICATE_PATH_LOCATIONS = [
238 "/etc/ssl/certs", # SLES10/SLES11
239]
240
Paul Kehrera92a1a72017-07-19 15:53:23 +0200241# These values are compared to output from cffi's ffi.string so they must be
242# byte strings.
243_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
244_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500245
Alex Gaynor83284952015-09-05 10:43:30 -0400246
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500248 """
249 An error occurred in an `OpenSSL.SSL` API.
250 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251
252
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500253_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100254_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500255
256
257class WantReadError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class WantWriteError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class WantX509LookupError(Error):
266 pass
267
268
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269class ZeroReturnError(Error):
270 pass
271
272
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500273class SysCallError(Error):
274 pass
275
276
Cory Benfield0ea76e72015-03-22 09:05:28 +0000277class _CallbackExceptionHelper(object):
278 """
279 A base class for wrapper classes that allow for intelligent exception
280 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500281
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400282 :ivar list _problems: Any exceptions that occurred while executing in a
283 context where they could not be raised in the normal way. Typically
284 this is because OpenSSL has called into some Python code and requires a
285 return value. The exceptions are saved to be raised later when it is
286 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000287 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400288
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400289 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800290 self._problems = []
291
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400293 """
294 Raise an exception from the OpenSSL error queue or that was previously
295 captured whe running a callback.
296 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000297 if self._problems:
298 try:
299 _raise_current_error()
300 except Error:
301 pass
302 raise self._problems.pop(0)
303
304
305class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400306 """
307 Wrap a callback such that it can be used as a certificate verification
308 callback.
309 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400310
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800311 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400312 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800313
314 @wraps(callback)
315 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800316 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
317 _lib.X509_up_ref(x509)
318 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500319 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
320 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800321
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400322 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
323 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
324 connection = Connection._reverse_mapping[ssl]
325
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800326 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400327 result = callback(
328 connection, cert, error_number, error_depth, ok
329 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800330 except Exception as e:
331 self._problems.append(e)
332 return 0
333 else:
334 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500335 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800336 return 1
337 else:
338 return 0
339
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500340 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400341 "int (*)(int, X509_STORE_CTX *)", wrapper
342 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800343
344
Cory Benfield0ea76e72015-03-22 09:05:28 +0000345class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400346 """
347 Wrap a callback such that it can be used as an NPN advertisement callback.
348 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400349
Cory Benfield0ea76e72015-03-22 09:05:28 +0000350 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400351 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800352
Cory Benfield0ea76e72015-03-22 09:05:28 +0000353 @wraps(callback)
354 def wrapper(ssl, out, outlen, arg):
355 try:
356 conn = Connection._reverse_mapping[ssl]
357 protos = callback(conn)
358
359 # Join the protocols into a Python bytestring, length-prefixing
360 # each element.
Alex Gaynor03737182020-07-23 20:40:46 -0400361 protostr = b"".join(
Cory Benfield0ea76e72015-03-22 09:05:28 +0000362 chain.from_iterable((int2byte(len(p)), p) for p in protos)
363 )
364
365 # Save our callback arguments on the connection object. This is
366 # done to make sure that they don't get freed before OpenSSL
367 # uses them. Then, return them appropriately in the output
368 # parameters.
369 conn._npn_advertise_callback_args = [
370 _ffi.new("unsigned int *", len(protostr)),
371 _ffi.new("unsigned char[]", protostr),
372 ]
373 outlen[0] = conn._npn_advertise_callback_args[0][0]
374 out[0] = conn._npn_advertise_callback_args[1]
375 return 0
376 except Exception as e:
377 self._problems.append(e)
378 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
379
380 self.callback = _ffi.callback(
381 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
Alex Gaynor03737182020-07-23 20:40:46 -0400382 wrapper,
Cory Benfield0ea76e72015-03-22 09:05:28 +0000383 )
384
385
386class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400387 """
388 Wrap a callback such that it can be used as an NPN selection callback.
389 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400390
Cory Benfield0ea76e72015-03-22 09:05:28 +0000391 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400392 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000393
394 @wraps(callback)
395 def wrapper(ssl, out, outlen, in_, inlen, arg):
396 try:
397 conn = Connection._reverse_mapping[ssl]
398
399 # The string passed to us is actually made up of multiple
400 # length-prefixed bytestrings. We need to split that into a
401 # list.
402 instr = _ffi.buffer(in_, inlen)[:]
403 protolist = []
404 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500405 length = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400406 proto = instr[1 : length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000407 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400408 instr = instr[length + 1 :]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000409
410 # Call the callback
411 outstr = callback(conn, protolist)
412
413 # Save our callback arguments on the connection object. This is
414 # done to make sure that they don't get freed before OpenSSL
415 # uses them. Then, return them appropriately in the output
416 # parameters.
417 conn._npn_select_callback_args = [
418 _ffi.new("unsigned char *", len(outstr)),
419 _ffi.new("unsigned char[]", outstr),
420 ]
421 outlen[0] = conn._npn_select_callback_args[0][0]
422 out[0] = conn._npn_select_callback_args[1]
423 return 0
424 except Exception as e:
425 self._problems.append(e)
426 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
427
428 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400429 (
430 "int (*)(SSL *, unsigned char **, unsigned char *, "
431 "const unsigned char *, unsigned int, void *)"
432 ),
433 wrapper,
Cory Benfield0ea76e72015-03-22 09:05:28 +0000434 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800435
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800436
Mark Williams5d890a02019-11-17 19:56:26 -0800437NO_OVERLAPPING_PROTOCOLS = object()
438
439
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400440class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400441 """
442 Wrap a callback such that it can be used as an ALPN selection callback.
443 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400444
Cory Benfieldf1177e72015-04-12 09:11:49 -0400445 def __init__(self, callback):
446 _CallbackExceptionHelper.__init__(self)
447
448 @wraps(callback)
449 def wrapper(ssl, out, outlen, in_, inlen, arg):
450 try:
451 conn = Connection._reverse_mapping[ssl]
452
453 # The string passed to us is made up of multiple
454 # length-prefixed bytestrings. We need to split that into a
455 # list.
456 instr = _ffi.buffer(in_, inlen)[:]
457 protolist = []
458 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400459 encoded_len = indexbytes(instr, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400460 proto = instr[1 : encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400461 protolist.append(proto)
Alex Gaynor03737182020-07-23 20:40:46 -0400462 instr = instr[encoded_len + 1 :]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400463
464 # Call the callback
Mark Williams5d890a02019-11-17 19:56:26 -0800465 outbytes = callback(conn, protolist)
466 any_accepted = True
467 if outbytes is NO_OVERLAPPING_PROTOCOLS:
Alex Gaynor03737182020-07-23 20:40:46 -0400468 outbytes = b""
Mark Williams5d890a02019-11-17 19:56:26 -0800469 any_accepted = False
Alex Gaynor12576002019-11-18 00:18:50 -0500470 elif not isinstance(outbytes, bytes):
Mark Williams5d890a02019-11-17 19:56:26 -0800471 raise TypeError(
472 "ALPN callback must return a bytestring or the "
473 "special NO_OVERLAPPING_PROTOCOLS sentinel value."
474 )
Cory Benfieldf1177e72015-04-12 09:11:49 -0400475
476 # Save our callback arguments on the connection object to make
477 # sure that they don't get freed before OpenSSL can use them.
478 # Then, return them in the appropriate output parameters.
479 conn._alpn_select_callback_args = [
Mark Williams5d890a02019-11-17 19:56:26 -0800480 _ffi.new("unsigned char *", len(outbytes)),
481 _ffi.new("unsigned char[]", outbytes),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400482 ]
483 outlen[0] = conn._alpn_select_callback_args[0][0]
484 out[0] = conn._alpn_select_callback_args[1]
Mark Williams5d890a02019-11-17 19:56:26 -0800485 if not any_accepted:
486 return _lib.SSL_TLSEXT_ERR_NOACK
487 return _lib.SSL_TLSEXT_ERR_OK
Cory Benfieldf1177e72015-04-12 09:11:49 -0400488 except Exception as e:
489 self._problems.append(e)
Mark Williams5d890a02019-11-17 19:56:26 -0800490 return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
Cory Benfieldf1177e72015-04-12 09:11:49 -0400491
492 self.callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -0400493 (
494 "int (*)(SSL *, unsigned char **, unsigned char *, "
495 "const unsigned char *, unsigned int, void *)"
496 ),
497 wrapper,
Cory Benfieldf1177e72015-04-12 09:11:49 -0400498 )
499
500
Cory Benfield496652a2017-01-24 11:42:56 +0000501class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
502 """
503 Wrap a callback such that it can be used as an OCSP callback for the server
504 side.
505
506 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
507 ways. For servers, that callback is expected to retrieve some OCSP data and
508 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
509 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
510 is expected to check the OCSP data, and returns a negative value on error,
511 0 if the response is not acceptable, or positive if it is. These are
512 mutually exclusive return code behaviours, and they mean that we need two
513 helpers so that we always return an appropriate error code if the user's
514 code throws an exception.
515
516 Given that we have to have two helpers anyway, these helpers are a bit more
517 helpery than most: specifically, they hide a few more of the OpenSSL
518 functions so that the user has an easier time writing these callbacks.
519
520 This helper implements the server side.
521 """
522
523 def __init__(self, callback):
524 _CallbackExceptionHelper.__init__(self)
525
526 @wraps(callback)
527 def wrapper(ssl, cdata):
528 try:
529 conn = Connection._reverse_mapping[ssl]
530
531 # Extract the data if any was provided.
532 if cdata != _ffi.NULL:
533 data = _ffi.from_handle(cdata)
534 else:
535 data = None
536
537 # Call the callback.
538 ocsp_data = callback(conn, data)
539
Alex Gaynor12576002019-11-18 00:18:50 -0500540 if not isinstance(ocsp_data, bytes):
Cory Benfield496652a2017-01-24 11:42:56 +0000541 raise TypeError("OCSP callback must return a bytestring.")
542
543 # If the OCSP data was provided, we will pass it to OpenSSL.
544 # However, we have an early exit here: if no OCSP data was
545 # provided we will just exit out and tell OpenSSL that there
546 # is nothing to do.
547 if not ocsp_data:
548 return 3 # SSL_TLSEXT_ERR_NOACK
549
David Benjamin7ac5f272018-05-21 21:24:04 -0400550 # OpenSSL takes ownership of this data and expects it to have
551 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000552 ocsp_data_length = len(ocsp_data)
553 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
554 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
555
556 _lib.SSL_set_tlsext_status_ocsp_resp(
557 ssl, data_ptr, ocsp_data_length
558 )
559
560 return 0
561 except Exception as e:
562 self._problems.append(e)
563 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
564
565 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
566
567
568class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
569 """
570 Wrap a callback such that it can be used as an OCSP callback for the client
571 side.
572
573 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
574 ways. For servers, that callback is expected to retrieve some OCSP data and
575 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
576 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
577 is expected to check the OCSP data, and returns a negative value on error,
578 0 if the response is not acceptable, or positive if it is. These are
579 mutually exclusive return code behaviours, and they mean that we need two
580 helpers so that we always return an appropriate error code if the user's
581 code throws an exception.
582
583 Given that we have to have two helpers anyway, these helpers are a bit more
584 helpery than most: specifically, they hide a few more of the OpenSSL
585 functions so that the user has an easier time writing these callbacks.
586
587 This helper implements the client side.
588 """
589
590 def __init__(self, callback):
591 _CallbackExceptionHelper.__init__(self)
592
593 @wraps(callback)
594 def wrapper(ssl, cdata):
595 try:
596 conn = Connection._reverse_mapping[ssl]
597
598 # Extract the data if any was provided.
599 if cdata != _ffi.NULL:
600 data = _ffi.from_handle(cdata)
601 else:
602 data = None
603
604 # Get the OCSP data.
605 ocsp_ptr = _ffi.new("unsigned char **")
606 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
607 if ocsp_len < 0:
608 # No OCSP data.
Alex Gaynor03737182020-07-23 20:40:46 -0400609 ocsp_data = b""
Cory Benfield496652a2017-01-24 11:42:56 +0000610 else:
611 # Copy the OCSP data, then pass it to the callback.
612 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
613
614 valid = callback(conn, ocsp_data, data)
615
616 # Return 1 on success or 0 on error.
617 return int(bool(valid))
618
619 except Exception as e:
620 self._problems.append(e)
621 # Return negative value if an exception is hit.
622 return -1
623
624 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
625
626
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800627def _asFileDescriptor(obj):
628 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800629 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800630 meth = getattr(obj, "fileno", None)
631 if meth is not None:
632 obj = meth()
633
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800634 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800635 fd = obj
636
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800637 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800638 raise TypeError("argument must be an int, or have a fileno() method.")
639 elif fd < 0:
640 raise ValueError(
Alex Gaynor03737182020-07-23 20:40:46 -0400641 "file descriptor cannot be a negative integer (%i)" % (fd,)
642 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800643
644 return fd
645
646
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800647def SSLeay_version(type):
648 """
649 Return a string describing the version of OpenSSL in use.
650
Alex Chand072cae2018-02-15 09:57:59 +0000651 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800652 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500653 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800654
655
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500656def _warn_npn():
Alex Gaynor03737182020-07-23 20:40:46 -0400657 warnings.warn(
658 "NPN is deprecated. Protocols should switch to using ALPN.",
659 DeprecationWarning,
660 stacklevel=3,
661 )
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500662
663
Cory Benfieldef404df2016-03-29 15:32:48 +0100664def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400665 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100666 Builds a decorator that ensures that functions that rely on OpenSSL
667 functions that are not present in this build raise NotImplementedError,
668 rather than AttributeError coming out of cryptography.
669
670 :param flag: A cryptography flag that guards the functions, e.g.
671 ``Cryptography_HAS_NEXTPROTONEG``.
672 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400673 """
Alex Gaynor03737182020-07-23 20:40:46 -0400674
Cory Benfieldef404df2016-03-29 15:32:48 +0100675 def _requires_decorator(func):
676 if not flag:
Alex Gaynor03737182020-07-23 20:40:46 -0400677
Cory Benfieldef404df2016-03-29 15:32:48 +0100678 @wraps(func)
679 def explode(*args, **kwargs):
680 raise NotImplementedError(error)
Alex Gaynor03737182020-07-23 20:40:46 -0400681
Cory Benfieldef404df2016-03-29 15:32:48 +0100682 return explode
683 else:
684 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400685
Cory Benfieldef404df2016-03-29 15:32:48 +0100686 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400687
688
Cory Benfieldef404df2016-03-29 15:32:48 +0100689_requires_npn = _make_requires(
690 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
691)
Cory Benfield7907e332015-04-13 17:18:25 -0400692
693
Cory Benfieldef404df2016-03-29 15:32:48 +0100694_requires_alpn = _make_requires(
695 _lib.Cryptography_HAS_ALPN, "ALPN not available"
696)
Cory Benfielde6f35882016-03-29 11:21:04 +0100697
Cory Benfielde6f35882016-03-29 11:21:04 +0100698
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200699_requires_keylog = _make_requires(
700 getattr(_lib, "Cryptography_HAS_KEYLOG", None), "Key logging not available"
701)
702
703
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800704class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000705 """
706 A class representing an SSL session. A session defines certain connection
707 parameters which may be re-used to speed up the setup of subsequent
708 connections.
709
710 .. versionadded:: 0.14
711 """
Alex Gaynor03737182020-07-23 20:40:46 -0400712
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800713 pass
714
715
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716class Context(object):
717 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100718 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400719 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000720
721 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
722 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800723 """
Alex Gaynor03737182020-07-23 20:40:46 -0400724
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800725 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800726 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500727 SSLv3_METHOD: "SSLv3_method",
728 SSLv23_METHOD: "SSLv23_method",
729 TLSv1_METHOD: "TLSv1_method",
730 TLSv1_1_METHOD: "TLSv1_1_method",
731 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400732 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500733 _methods = dict(
734 (identifier, getattr(_lib, name))
735 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400736 if getattr(_lib, name, None) is not None
737 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738
739 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500740 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 raise TypeError("method must be an integer")
742
743 try:
744 method_func = self._methods[method]
745 except KeyError:
746 raise ValueError("No such protocol")
747
748 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700749 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500751 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700752 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500753 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800754
Alex Gaynor77debda2020-04-07 13:40:59 -0400755 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
756 # auto-selected. This function was added in 1.0.2 and made a noop in
757 # 1.1.0+ (where it is set automatically).
758 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
759 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600760
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800762 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800763 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800764 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800765 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800766 self._verify_callback = None
767 self._info_callback = None
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200768 self._keylog_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800770 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000771 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100772 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000773 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100774 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400775 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100776 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000777 self._ocsp_helper = None
778 self._ocsp_callback = None
779 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500781 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def load_verify_locations(self, cafile, capath=None):
784 """
785 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000786 chain. Note that the certificates have to be in PEM format.
787
788 If capath is passed, it must be a directory prepared using the
789 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
790 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400792 :param cafile: In which file we can find the certificates (``bytes`` or
793 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400795 (``bytes`` or ``unicode``).
796
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800797 :return: None
798 """
799 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500800 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400801 else:
802 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800803
804 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500805 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400806 else:
807 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800808
Alex Gaynor62da94d2015-09-05 14:37:34 -0400809 load_result = _lib.SSL_CTX_load_verify_locations(
810 self._context, cafile, capath
811 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800812 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500813 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815 def _wrap_callback(self, callback):
816 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800817 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400819
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800820 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400821 FILETYPE_PEM, wrapper, more_args=True, truncate=True
822 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800823
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800824 def set_passwd_cb(self, callback, userdata=None):
825 """
Alex Chand072cae2018-02-15 09:57:59 +0000826 Set the passphrase callback. This function will be called
827 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800828
Alex Chand072cae2018-02-15 09:57:59 +0000829 :param callback: The Python callback to use. This must accept three
830 positional arguments. First, an integer giving the maximum length
831 of the passphrase it may return. If the returned passphrase is
832 longer than this, it will be truncated. Second, a boolean value
833 which will be true if the user should be prompted for the
834 passphrase twice and the callback should verify that the two values
835 supplied are equal. Third, the value given as the *userdata*
836 parameter to :meth:`set_passwd_cb`. The *callback* must return
837 a byte string. If an error occurs, *callback* should return a false
838 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800839 :param userdata: (optional) A Python object which will be given as
840 argument to the callback
841 :return: None
842 """
843 if not callable(callback):
844 raise TypeError("callback must be callable")
845
846 self._passphrase_helper = self._wrap_callback(callback)
847 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500848 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400849 self._context, self._passphrase_callback
850 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800851 self._passphrase_userdata = userdata
852
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800853 def set_default_verify_paths(self):
854 """
Alex Chand072cae2018-02-15 09:57:59 +0000855 Specify that the platform provided CA certificates are to be used for
856 verification purposes. This method has some caveats related to the
857 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
858
859 * macOS will only load certificates using this method if the user has
860 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
861 in the default location.
862 * Windows will not work.
863 * manylinux1 cryptography wheels will work on most common Linux
864 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
865 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800866
867 :return: None
868 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500869 # SSL_CTX_set_default_verify_paths will attempt to load certs from
870 # both a cafile and capath that are set at compile time. However,
871 # it will first check environment variables and, if present, load
872 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500873 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400874 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500875 # After attempting to set default_verify_paths we need to know whether
876 # to go down the fallback path.
877 # First we'll check to see if any env vars have been set. If so,
878 # we won't try to do anything else because the user has set the path
879 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400880 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
881 "ascii"
882 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500883 file_env_var = _ffi.string(
884 _lib.X509_get_default_cert_file_env()
885 ).decode("ascii")
886 if not self._check_env_vars_set(dir_env_var, file_env_var):
887 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
888 default_file = _ffi.string(_lib.X509_get_default_cert_file())
889 # Now we check to see if the default_dir and default_file are set
890 # to the exact values we use in our manylinux1 builds. If they are
891 # then we know to load the fallbacks
892 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400893 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
894 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500895 ):
896 # This is manylinux1, let's load our fallback paths
897 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400898 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500899 )
900
901 def _check_env_vars_set(self, dir_env_var, file_env_var):
902 """
903 Check to see if the default cert dir/file environment vars are present.
904
905 :return: bool
906 """
907 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400908 os.environ.get(file_env_var) is not None
909 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500910 )
911
912 def _fallback_default_verify_paths(self, file_path, dir_path):
913 """
914 Default verify paths are based on the compiled version of OpenSSL.
915 However, when pyca/cryptography is compiled as a manylinux1 wheel
916 that compiled location can potentially be wrong. So, like Go, we
917 will try a predefined set of paths and attempt to load roots
918 from there.
919
920 :return: None
921 """
922 for cafile in file_path:
923 if os.path.isfile(cafile):
924 self.load_verify_locations(cafile)
925 break
926
927 for capath in dir_path:
928 if os.path.isdir(capath):
929 self.load_verify_locations(None, capath)
930 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800931
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800932 def use_certificate_chain_file(self, certfile):
933 """
Alex Chand072cae2018-02-15 09:57:59 +0000934 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800935
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400936 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000937 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400938
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939 :return: None
940 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400941 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800942
Alex Gaynor62da94d2015-09-05 14:37:34 -0400943 result = _lib.SSL_CTX_use_certificate_chain_file(
944 self._context, certfile
945 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800946 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500947 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800948
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800949 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800950 """
951 Load a certificate from a file
952
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400953 :param certfile: The name of the certificate file (``bytes`` or
954 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000955 :param filetype: (optional) The encoding of the file, which is either
956 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
957 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400958
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959 :return: None
960 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400961 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500962 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800963 raise TypeError("filetype must be an integer")
964
Alex Gaynor62da94d2015-09-05 14:37:34 -0400965 use_result = _lib.SSL_CTX_use_certificate_file(
966 self._context, certfile, filetype
967 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800968 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500969 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800970
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800971 def use_certificate(self, cert):
972 """
973 Load a certificate from a X509 object
974
975 :param cert: The X509 object
976 :return: None
977 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800978 if not isinstance(cert, X509):
979 raise TypeError("cert must be an X509 instance")
980
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500981 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800982 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500983 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800984
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800985 def add_extra_chain_cert(self, certobj):
986 """
987 Add certificate to chain
988
989 :param certobj: The X509 certificate object to add to the chain
990 :return: None
991 """
992 if not isinstance(certobj, X509):
993 raise TypeError("certobj must be an X509 instance")
994
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500995 copy = _lib.X509_dup(certobj._x509)
996 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500998 # TODO: This is untested.
999 _lib.X509_free(copy)
1000 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001002 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -05001003 if self._passphrase_helper is not None:
1004 self._passphrase_helper.raise_if_problem(Error)
1005
1006 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001007
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001008 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009 """
1010 Load a private key from a file
1011
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -04001012 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +00001013 :param filetype: (optional) The encoding of the file, which is either
1014 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
1015 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -04001016
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017 :return: None
1018 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -04001019 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001021 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001022 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001023 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001024 raise TypeError("filetype must be an integer")
1025
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001026 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -04001027 self._context, keyfile, filetype
1028 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001029 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001030 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001031
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032 def use_privatekey(self, pkey):
1033 """
1034 Load a private key from a PKey object
1035
1036 :param pkey: The PKey object
1037 :return: None
1038 """
1039 if not isinstance(pkey, PKey):
1040 raise TypeError("pkey must be a PKey instance")
1041
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001042 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001044 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046 def check_privatekey(self):
1047 """
Alex Chand072cae2018-02-15 09:57:59 +00001048 Check if the private key (loaded with :meth:`use_privatekey`) matches
1049 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001050
Alex Chand072cae2018-02-15 09:57:59 +00001051 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001052 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001053 if not _lib.SSL_CTX_check_private_key(self._context):
1054 _raise_current_error()
1055
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056 def load_client_ca(self, cafile):
1057 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001058 Load the trusted certificates that will be sent to the client. Does
1059 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001060 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001062 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001063 :return: None
1064 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001065 ca_list = _lib.SSL_load_client_CA_file(
1066 _text_to_bytes_and_warn("cafile", cafile)
1067 )
1068 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001069 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070
1071 def set_session_id(self, buf):
1072 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001073 Set the session id to *buf* within which a session can be reused for
1074 this Context object. This is needed when doing session resumption,
1075 because there is no way for a stored session to know which Context
1076 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001077
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001078 :param bytes buf: The session id.
1079
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080 :returns: None
1081 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001082 buf = _text_to_bytes_and_warn("buf", buf)
1083 _openssl_assert(
Alex Gaynor03737182020-07-23 20:40:46 -04001084 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf),)
1085 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001086 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
1088 def set_session_cache_mode(self, mode):
1089 """
Alex Chand072cae2018-02-15 09:57:59 +00001090 Set the behavior of the session cache used by all connections using
1091 this Context. The previously set mode is returned. See
1092 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093
1094 :param mode: One or more of the SESS_CACHE_* flags (combine using
1095 bitwise or)
1096 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001097
1098 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001100 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001101 raise TypeError("mode must be an integer")
1102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001103 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001104
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 def get_session_cache_mode(self):
1106 """
Alex Chand072cae2018-02-15 09:57:59 +00001107 Get the current session cache mode.
1108
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001110
1111 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001112 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001113 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001114
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001115 def set_verify(self, mode, callback):
1116 """
Alex Chand072cae2018-02-15 09:57:59 +00001117 et the verification flags for this Context object to *mode* and specify
1118 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001119
Alex Chand072cae2018-02-15 09:57:59 +00001120 :param mode: The verify mode, this should be one of
1121 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1122 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1123 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1124 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1125 :param callback: The Python callback to use. This should take five
1126 arguments: A Connection object, an X509 object, and three integer
1127 variables, which are in turn potential error number, error depth
1128 and return code. *callback* should return True if verification
1129 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001130 :return: None
1131
1132 See SSL_CTX_set_verify(3SSL) for further details.
1133 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001134 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001135 raise TypeError("mode must be an integer")
1136
1137 if not callable(callback):
1138 raise TypeError("callback must be callable")
1139
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001140 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001141 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001142 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144 def set_verify_depth(self, depth):
1145 """
Alex Chand072cae2018-02-15 09:57:59 +00001146 Set the maximum depth for the certificate chain verification that shall
1147 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001148
1149 :param depth: An integer specifying the verify depth
1150 :return: None
1151 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001152 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001153 raise TypeError("depth must be an integer")
1154
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001156
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001157 def get_verify_mode(self):
1158 """
Alex Chand072cae2018-02-15 09:57:59 +00001159 Retrieve the Context object's verify mode, as set by
1160 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161
1162 :return: The verify mode
1163 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001164 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001165
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001166 def get_verify_depth(self):
1167 """
Alex Chand072cae2018-02-15 09:57:59 +00001168 Retrieve the Context object's verify depth, as set by
1169 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001170
1171 :return: The verify depth
1172 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001174
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001175 def load_tmp_dh(self, dhfile):
1176 """
1177 Load parameters for Ephemeral Diffie-Hellman
1178
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001179 :param dhfile: The file to load EDH parameters from (``bytes`` or
1180 ``unicode``).
1181
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182 :return: None
1183 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001184 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001185
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001186 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001187 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001188 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001189 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001190
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001191 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1192 dh = _ffi.gc(dh, _lib.DH_free)
1193 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001194
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001195 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001196 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001197 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001198
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001199 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001200 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1201 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001202
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001203 :return: None
1204 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001205 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001206
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207 def set_cipher_list(self, cipher_list):
1208 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001209 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001210
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001211 See the OpenSSL manual for more information (e.g.
1212 :manpage:`ciphers(1)`).
1213
1214 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215 :return: None
1216 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001217 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001218
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001219 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001220 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001221
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001222 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001223 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001224 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001225 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1226 # ciphers even if you pass an invalid cipher. Applications (like
1227 # Twisted) have tests that depend on an error being raised if an
1228 # invalid cipher string is passed, but without the following check
1229 # for the TLS 1.3 specific cipher suites it would never error.
1230 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001231 if tmpconn.get_cipher_list() == [
1232 "TLS_AES_256_GCM_SHA384",
1233 "TLS_CHACHA20_POLY1305_SHA256",
1234 "TLS_AES_128_GCM_SHA256",
1235 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001236 raise Error(
1237 [
1238 (
Alex Gaynor03737182020-07-23 20:40:46 -04001239 "SSL routines",
1240 "SSL_CTX_set_cipher_list",
1241 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001242 ),
1243 ],
1244 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001245
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001246 def set_client_ca_list(self, certificate_authorities):
1247 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001248 Set the list of preferred client certificate signers for this server
1249 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001250
Alex Gaynor62da94d2015-09-05 14:37:34 -04001251 This list of certificate authorities will be sent to the client when
1252 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001253
1254 :param certificate_authorities: a sequence of X509Names.
1255 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001256
1257 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001258 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001259 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001260 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001261
1262 try:
1263 for ca_name in certificate_authorities:
1264 if not isinstance(ca_name, X509Name):
1265 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001266 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001267 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001268 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001269 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001270 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001271 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001272 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001273 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001274 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001275 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001276 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001277 raise
1278
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001279 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001280
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001281 def add_client_ca(self, certificate_authority):
1282 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001283 Add the CA certificate to the list of preferred signers for this
1284 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001285
1286 The list of certificate authorities will be sent to the client when the
1287 server requests a client certificate.
1288
1289 :param certificate_authority: certificate authority's X509 certificate.
1290 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001291
1292 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001293 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001294 if not isinstance(certificate_authority, X509):
1295 raise TypeError("certificate_authority must be an X509 instance")
1296
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001297 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001298 self._context, certificate_authority._x509
1299 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001300 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001301
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001302 def set_timeout(self, timeout):
1303 """
Alex Chand072cae2018-02-15 09:57:59 +00001304 Set the timeout for newly created sessions for this Context object to
1305 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1306 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001307
Alex Chand072cae2018-02-15 09:57:59 +00001308 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309 :return: The previous session timeout
1310 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001311 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001312 raise TypeError("timeout must be an integer")
1313
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001314 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001315
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001316 def get_timeout(self):
1317 """
Alex Chand072cae2018-02-15 09:57:59 +00001318 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1319 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001320
1321 :return: The session timeout
1322 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001323 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001324
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001325 def set_info_callback(self, callback):
1326 """
Alex Chand072cae2018-02-15 09:57:59 +00001327 Set the information callback to *callback*. This function will be
1328 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001329
Alex Chand072cae2018-02-15 09:57:59 +00001330 :param callback: The Python callback to use. This should take three
1331 arguments: a Connection object and two integers. The first integer
1332 specifies where in the SSL handshake the function was called, and
1333 the other the return code from a (possibly failed) internal
1334 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001335 :return: None
1336 """
Alex Gaynor03737182020-07-23 20:40:46 -04001337
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001338 @wraps(callback)
1339 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001340 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001341
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001342 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001343 "void (*)(const SSL *, int, int)", wrapper
1344 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001345 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001346
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001347 @_requires_keylog
1348 def set_keylog_callback(self, callback):
1349 """
1350 Set the TLS key logging callback to *callback*. This function will be
1351 called whenever TLS key material is generated or received, in order
1352 to allow applications to store this keying material for debugging
1353 purposes.
1354
1355 :param callback: The Python callback to use. This should take two
1356 arguments: a Connection object and a bytestring that contains
1357 the key material in the format used by NSS for its SSLKEYLOGFILE
1358 debugging output.
1359 :return: None
1360 """
1361
1362 @wraps(callback)
1363 def wrapper(ssl, line):
1364 line = _ffi.string(line)
1365 callback(Connection._reverse_mapping[ssl], line)
1366
1367 self._keylog_callback = _ffi.callback(
1368 "void (*)(const SSL *, const char *)", wrapper
1369 )
1370 _lib.SSL_CTX_set_keylog_callback(self._context, self._keylog_callback)
1371
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001372 def get_app_data(self):
1373 """
Alex Chand072cae2018-02-15 09:57:59 +00001374 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001375
1376 :return: The application data
1377 """
1378 return self._app_data
1379
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001380 def set_app_data(self, data):
1381 """
1382 Set the application data (will be returned from get_app_data())
1383
1384 :param data: Any Python object
1385 :return: None
1386 """
1387 self._app_data = data
1388
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001389 def get_cert_store(self):
1390 """
Alex Chand072cae2018-02-15 09:57:59 +00001391 Get the certificate store for the context. This can be used to add
1392 "trusted" certificates without using the
1393 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001394
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001395 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001396 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001397 store = _lib.SSL_CTX_get_cert_store(self._context)
1398 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001399 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001400 return None
1401
1402 pystore = X509Store.__new__(X509Store)
1403 pystore._store = store
1404 return pystore
1405
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001406 def set_options(self, options):
1407 """
1408 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001409 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001410
1411 :param options: The options to add.
1412 :return: The new option bitmask.
1413 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001414 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001415 raise TypeError("options must be an integer")
1416
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001417 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001418
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001419 def set_mode(self, mode):
1420 """
Alex Chand072cae2018-02-15 09:57:59 +00001421 Add modes via bitmask. Modes set before are not cleared! This method
1422 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001423
1424 :param mode: The mode to add.
1425 :return: The new mode bitmask.
1426 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001427 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001428 raise TypeError("mode must be an integer")
1429
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001430 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001431
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001432 def set_tlsext_servername_callback(self, callback):
1433 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001434 Specify a callback function to be called when clients specify a server
1435 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001436
1437 :param callback: The callback function. It will be invoked with one
1438 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001439
1440 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001441 """
Alex Gaynor03737182020-07-23 20:40:46 -04001442
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001443 @wraps(callback)
1444 def wrapper(ssl, alert, arg):
1445 callback(Connection._reverse_mapping[ssl])
1446 return 0
1447
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001448 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001449 "int (*)(SSL *, int *, void *)", wrapper
1450 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001452 self._context, self._tlsext_servername_callback
1453 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001454
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001455 def set_tlsext_use_srtp(self, profiles):
1456 """
1457 Enable support for negotiating SRTP keying material.
1458
1459 :param bytes profiles: A colon delimited list of protection profile
1460 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1461 :return: None
1462 """
1463 if not isinstance(profiles, bytes):
1464 raise TypeError("profiles must be a byte string.")
1465
1466 _openssl_assert(
1467 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1468 )
1469
Cory Benfield10b277f2015-04-13 17:12:42 -04001470 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001471 def set_npn_advertise_callback(self, callback):
1472 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001473 Specify a callback function that will be called when offering `Next
1474 Protocol Negotiation
1475 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001476
1477 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001478 argument, the :class:`Connection` instance. It should return a
1479 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001480 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001481
1482 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001483 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001484 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001485 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1486 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001487 _lib.SSL_CTX_set_next_protos_advertised_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001488 self._context, self._npn_advertise_callback, _ffi.NULL
1489 )
Cory Benfield84a121e2014-03-31 20:30:25 +01001490
Cory Benfield10b277f2015-04-13 17:12:42 -04001491 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001492 def set_npn_select_callback(self, callback):
1493 """
1494 Specify a callback function that will be called when a server offers
1495 Next Protocol Negotiation options.
1496
1497 :param callback: The callback function. It will be invoked with two
1498 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001499 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1500 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001501
1502 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001503 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001504 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001505 self._npn_select_helper = _NpnSelectHelper(callback)
1506 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001507 _lib.SSL_CTX_set_next_proto_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001508 self._context, self._npn_select_callback, _ffi.NULL
1509 )
Cory Benfield84a121e2014-03-31 20:30:25 +01001510
Cory Benfield7907e332015-04-13 17:18:25 -04001511 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001512 def set_alpn_protos(self, protos):
1513 """
Alex Chand072cae2018-02-15 09:57:59 +00001514 Specify the protocols that the client is prepared to speak after the
1515 TLS connection has been negotiated using Application Layer Protocol
1516 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001517
1518 :param protos: A list of the protocols to be offered to the server.
1519 This list should be a Python list of bytestrings representing the
1520 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1521 """
1522 # Take the list of protocols and join them together, prefixing them
1523 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001524 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001525 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1526 )
1527
1528 # Build a C string from the list. We don't need to save this off
1529 # because OpenSSL immediately copies the data out.
1530 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001531 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001532
Cory Benfield7907e332015-04-13 17:18:25 -04001533 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001534 def set_alpn_select_callback(self, callback):
1535 """
Alex Chand072cae2018-02-15 09:57:59 +00001536 Specify a callback function that will be called on the server when a
1537 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001538
1539 :param callback: The callback function. It will be invoked with two
1540 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001541 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1542 one of those bytestrings to indicate the chosen protocol, the
1543 empty bytestring to terminate the TLS connection, or the
1544 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1545 protocol was selected, but that the connection should not be
1546 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001547 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001548 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001549 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001550 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001551 self._context, self._alpn_select_callback, _ffi.NULL
1552 )
Cory Benfield12eae892014-06-07 15:42:56 +01001553
Cory Benfield496652a2017-01-24 11:42:56 +00001554 def _set_ocsp_callback(self, helper, data):
1555 """
1556 This internal helper does the common work for
1557 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1558 almost all of it.
1559 """
1560 self._ocsp_helper = helper
1561 self._ocsp_callback = helper.callback
1562 if data is None:
1563 self._ocsp_data = _ffi.NULL
1564 else:
1565 self._ocsp_data = _ffi.new_handle(data)
1566
1567 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1568 self._context, self._ocsp_callback
1569 )
1570 _openssl_assert(rc == 1)
1571 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1572 _openssl_assert(rc == 1)
1573
1574 def set_ocsp_server_callback(self, callback, data=None):
1575 """
1576 Set a callback to provide OCSP data to be stapled to the TLS handshake
1577 on the server side.
1578
1579 :param callback: The callback function. It will be invoked with two
1580 arguments: the Connection, and the optional arbitrary data you have
1581 provided. The callback must return a bytestring that contains the
1582 OCSP data to staple to the handshake. If no OCSP data is available
1583 for this connection, return the empty bytestring.
1584 :param data: Some opaque data that will be passed into the callback
1585 function when called. This can be used to avoid needing to do
1586 complex data lookups or to keep track of what context is being
1587 used. This parameter is optional.
1588 """
1589 helper = _OCSPServerCallbackHelper(callback)
1590 self._set_ocsp_callback(helper, data)
1591
1592 def set_ocsp_client_callback(self, callback, data=None):
1593 """
1594 Set a callback to validate OCSP data stapled to the TLS handshake on
1595 the client side.
1596
1597 :param callback: The callback function. It will be invoked with three
1598 arguments: the Connection, a bytestring containing the stapled OCSP
1599 assertion, and the optional arbitrary data you have provided. The
1600 callback must return a boolean that indicates the result of
1601 validating the OCSP data: ``True`` if the OCSP data is valid and
1602 the certificate can be trusted, or ``False`` if either the OCSP
1603 data is invalid or the certificate has been revoked.
1604 :param data: Some opaque data that will be passed into the callback
1605 function when called. This can be used to avoid needing to do
1606 complex data lookups or to keep track of what context is being
1607 used. This parameter is optional.
1608 """
1609 helper = _OCSPClientCallbackHelper(callback)
1610 self._set_ocsp_callback(helper, data)
1611
Alex Chanc6077062016-11-18 13:53:39 +00001612
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001613class Connection(object):
1614 """
1615 """
Alex Gaynor03737182020-07-23 20:40:46 -04001616
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 _reverse_mapping = WeakValueDictionary()
1618
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001619 def __init__(self, context, socket=None):
1620 """
1621 Create a new Connection object, using the given OpenSSL.SSL.Context
1622 instance and socket.
1623
1624 :param context: An SSL Context to use for this connection
1625 :param socket: The socket to use for transport layer
1626 """
1627 if not isinstance(context, Context):
1628 raise TypeError("context must be a Context instance")
1629
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001630 ssl = _lib.SSL_new(context._context)
1631 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001632 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1633 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1634 # even though there is still data on the underlying transport.
1635 # See https://github.com/openssl/openssl/issues/6234 for more details.
1636 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001637 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001638 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001640 # References to strings used for Next Protocol Negotiation. OpenSSL's
1641 # header files suggest that these might get copied at some point, but
1642 # doesn't specify when, so we store them here to make sure they don't
1643 # get freed before OpenSSL uses them.
1644 self._npn_advertise_callback_args = None
1645 self._npn_select_callback_args = None
1646
Cory Benfield12eae892014-06-07 15:42:56 +01001647 # References to strings used for Application Layer Protocol
1648 # Negotiation. These strings get copied at some point but it's well
1649 # after the callback returns, so we have to hang them somewhere to
1650 # avoid them getting freed.
1651 self._alpn_select_callback_args = None
1652
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001653 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654
1655 if socket is None:
1656 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001657 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001658 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001659 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001660
Alex Gaynora829e902016-06-04 18:16:01 -07001661 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1662 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001664 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666 self._into_ssl = None
1667 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001668 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001669 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001670 self._ssl, _asFileDescriptor(self._socket)
1671 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001672 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001674 def __getattr__(self, name):
1675 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001676 Look up attributes on the wrapped socket object if they are not found
1677 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001678 """
kjav0b66fa12015-09-02 11:51:26 +01001679 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001680 raise AttributeError(
1681 "'%s' object has no attribute '%s'"
1682 % (self.__class__.__name__, name)
1683 )
kjav0b66fa12015-09-02 11:51:26 +01001684 else:
1685 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001688 if self._context._verify_helper is not None:
1689 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001690 if self._context._npn_advertise_helper is not None:
1691 self._context._npn_advertise_helper.raise_if_problem()
1692 if self._context._npn_select_helper is not None:
1693 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001694 if self._context._alpn_select_helper is not None:
1695 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001696 if self._context._ocsp_helper is not None:
1697 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001698
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001699 error = _lib.SSL_get_error(ssl, result)
1700 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001702 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001703 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001704 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001705 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001706 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001707 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001708 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 elif error == _lib.SSL_ERROR_SYSCALL:
1710 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001711 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001712 if platform == "win32":
1713 errno = _ffi.getwinerror()[0]
1714 else:
1715 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001716
1717 if errno != 0:
1718 raise SysCallError(errno, errorcode.get(errno))
1719 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001721 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001722 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001723 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001724 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001726 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001727
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001728 def get_context(self):
1729 """
Alex Chand072cae2018-02-15 09:57:59 +00001730 Retrieve the :class:`Context` object associated with this
1731 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001733 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001734
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001735 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001736 """
Alex Chand072cae2018-02-15 09:57:59 +00001737 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001738
Alex Chand072cae2018-02-15 09:57:59 +00001739 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001740 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001741 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 if not isinstance(context, Context):
1743 raise TypeError("context must be a Context instance")
1744
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001746 self._context = context
1747
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001748 def get_servername(self):
1749 """
1750 Retrieve the servername extension value if provided in the client hello
1751 message, or None if there wasn't one.
1752
Alex Chand072cae2018-02-15 09:57:59 +00001753 :return: A byte string giving the server name or :data:`None`.
1754
1755 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001756 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001757 name = _lib.SSL_get_servername(
1758 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1759 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001760 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001762
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001763 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001764
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001765 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001766 """
1767 Set the value of the servername extension to send in the client hello.
1768
1769 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001770
1771 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001772 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001773 if not isinstance(name, bytes):
1774 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001775 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001776 raise TypeError("name must not contain NUL byte")
1777
1778 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001779 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001781 def pending(self):
1782 """
Alex Chand072cae2018-02-15 09:57:59 +00001783 Get the number of bytes that can be safely read from the SSL buffer
1784 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001785
1786 :return: The number of bytes available in the receive buffer.
1787 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001788 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001789
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001790 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001791 """
1792 Send data on the connection. NOTE: If you get one of the WantRead,
1793 WantWrite or WantX509Lookup exceptions on this, you have to call the
1794 method again with the SAME buffer.
1795
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001796 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001797 :param flags: (optional) Included for compatibility with the socket
1798 API, the value is ignored
1799 :return: The number of bytes written
1800 """
Abraham Martine82326c2015-02-04 10:18:10 +00001801 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001802 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001803
Daniel Holth079c9632019-11-17 22:45:52 -05001804 with _from_buffer(buf) as data:
1805 # check len(buf) instead of len(data) for testability
1806 if len(buf) > 2147483647:
1807 raise ValueError(
1808 "Cannot send more than 2**31-1 bytes at once."
1809 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001810
Daniel Holth079c9632019-11-17 22:45:52 -05001811 result = _lib.SSL_write(self._ssl, data, len(data))
1812 self._raise_ssl_error(self._ssl, result)
1813
1814 return result
1815
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816 write = send
1817
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001818 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001819 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001820 Send "all" data on the connection. This calls send() repeatedly until
1821 all data is sent. If an error occurs, it's impossible to tell how much
1822 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001824 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001825 :param flags: (optional) Included for compatibility with the socket
1826 API, the value is ignored
1827 :return: The number of bytes written
1828 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001829 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001830
Daniel Holth079c9632019-11-17 22:45:52 -05001831 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001832
Daniel Holth079c9632019-11-17 22:45:52 -05001833 left_to_send = len(buf)
1834 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001835
Daniel Holth079c9632019-11-17 22:45:52 -05001836 while left_to_send:
1837 # SSL_write's num arg is an int,
1838 # so we cannot send more than 2**31-1 bytes at once.
1839 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001840 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001841 )
1842 self._raise_ssl_error(self._ssl, result)
1843 total_sent += result
1844 left_to_send -= result
1845
1846 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001847
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848 def recv(self, bufsiz, flags=None):
1849 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001850 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001851
1852 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001853 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1854 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001855 :return: The string read from the Connection
1856 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001857 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001858 if flags is not None and flags & socket.MSG_PEEK:
1859 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1860 else:
1861 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001862 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001863 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001864
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001865 read = recv
1866
Cory Benfield62d10332014-06-15 10:03:41 +01001867 def recv_into(self, buffer, nbytes=None, flags=None):
1868 """
Alex Chand072cae2018-02-15 09:57:59 +00001869 Receive data on the connection and copy it directly into the provided
1870 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001871
1872 :param buffer: The buffer to copy into.
1873 :param nbytes: (optional) The maximum number of bytes to read into the
1874 buffer. If not present, defaults to the size of the buffer. If
1875 larger than the size of the buffer, is reduced to the size of the
1876 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001877 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1878 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001879 :return: The number of bytes read into the buffer.
1880 """
1881 if nbytes is None:
1882 nbytes = len(buffer)
1883 else:
1884 nbytes = min(nbytes, len(buffer))
1885
1886 # We need to create a temporary buffer. This is annoying, it would be
1887 # better if we could pass memoryviews straight into the SSL_read call,
1888 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001889 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001890 if flags is not None and flags & socket.MSG_PEEK:
1891 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1892 else:
1893 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001894 self._raise_ssl_error(self._ssl, result)
1895
1896 # This strange line is all to avoid a memory copy. The buffer protocol
1897 # should allow us to assign a CFFI buffer to the LHS of this line, but
1898 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001899 # wrap it in a memoryview.
1900 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001901
1902 return result
1903
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001904 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001905 if _lib.BIO_should_retry(bio):
1906 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001907 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001908 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001909 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001910 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001911 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001912 # TODO: This is untested. I think io_special means the socket
1913 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001914 raise ValueError("BIO_should_io_special")
1915 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001916 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001917 raise ValueError("unknown bio failure")
1918 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001919 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001920 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001921
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001922 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923 """
Alex Chand072cae2018-02-15 09:57:59 +00001924 If the Connection was created with a memory BIO, this method can be
1925 used to read bytes from the write end of that memory BIO. Many
1926 Connection methods will add bytes which must be read in this manner or
1927 the buffer will eventually fill up and the Connection will be able to
1928 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929
1930 :param bufsiz: The maximum number of bytes to read
1931 :return: The string read.
1932 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001933 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001934 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001935
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001936 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001937 raise TypeError("bufsiz must be an integer")
1938
Cory Benfielde62840e2016-11-28 12:17:08 +00001939 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001940 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001941 if result <= 0:
1942 self._handle_bio_errors(self._from_ssl, result)
1943
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001944 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001945
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001946 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947 """
Alex Chand072cae2018-02-15 09:57:59 +00001948 If the Connection was created with a memory BIO, this method can be
1949 used to add bytes to the read end of that memory BIO. The Connection
1950 can then read the bytes (for example, in response to a call to
1951 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952
1953 :param buf: The string to put into the memory BIO.
1954 :return: The number of bytes written
1955 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001956 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001957
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001958 if self._into_ssl is None:
1959 raise TypeError("Connection sock was not None")
1960
Daniel Holth079c9632019-11-17 22:45:52 -05001961 with _from_buffer(buf) as data:
1962 result = _lib.BIO_write(self._into_ssl, data, len(data))
1963 if result <= 0:
1964 self._handle_bio_errors(self._into_ssl, result)
1965 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001966
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001967 def renegotiate(self):
1968 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001969 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001970
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001971 :return: True if the renegotiation can be started, False otherwise
1972 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001974 if not self.renegotiate_pending():
1975 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1976 return True
1977 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001978
1979 def do_handshake(self):
1980 """
Alex Chand072cae2018-02-15 09:57:59 +00001981 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001982 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001983 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984
1985 :return: None.
1986 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001987 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001988 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990 def renegotiate_pending(self):
1991 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001992 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993 a renegotiation is finished.
1994
1995 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001996 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001998 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999
2000 def total_renegotiations(self):
2001 """
2002 Find out the total number of renegotiations.
2003
2004 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01002005 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002006 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002007 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002010 """
Alex Chand072cae2018-02-15 09:57:59 +00002011 Call the :meth:`connect` method of the underlying socket and set up SSL
2012 on the socket, using the :class:`Context` object supplied to this
2013 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002014
2015 :param addr: A remote address
2016 :return: What the socket's connect method returns
2017 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002018 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002019 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002021 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002022 """
Alex Chand072cae2018-02-15 09:57:59 +00002023 Call the :meth:`connect_ex` method of the underlying socket and set up
2024 SSL on the socket, using the Context object supplied to this Connection
2025 object at creation. Note that if the :meth:`connect_ex` method of the
2026 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027
2028 :param addr: A remove address
2029 :return: What the socket's connect_ex method returns
2030 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002031 connect_ex = self._socket.connect_ex
2032 self.set_connect_state()
2033 return connect_ex(addr)
2034
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035 def accept(self):
2036 """
Alex Chand072cae2018-02-15 09:57:59 +00002037 Call the :meth:`accept` method of the underlying socket and set up SSL
2038 on the returned socket, using the Context object supplied to this
2039 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002040
Alex Chand072cae2018-02-15 09:57:59 +00002041 :return: A *(conn, addr)* pair where *conn* is the new
2042 :class:`Connection` object created, and *address* is as returned by
2043 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002044 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002045 client, addr = self._socket.accept()
2046 conn = Connection(self._context, client)
2047 conn.set_accept_state()
2048 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002050 def bio_shutdown(self):
2051 """
Alex Chand072cae2018-02-15 09:57:59 +00002052 If the Connection was created with a memory BIO, this method can be
2053 used to indicate that *end of file* has been reached on the read end of
2054 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055
2056 :return: None
2057 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002058 if self._from_ssl is None:
2059 raise TypeError("Connection sock was not None")
2060
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002061 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002062
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002063 def shutdown(self):
2064 """
Alex Chand072cae2018-02-15 09:57:59 +00002065 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002066
2067 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00002068 have sent closure alerts), False otherwise (in which case you
2069 call :meth:`recv` or :meth:`send` when the connection becomes
2070 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002072 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002074 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002075 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002076 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002077 else:
2078 return False
2079
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002080 def get_cipher_list(self):
2081 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002082 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002083
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002084 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002085 """
2086 ciphers = []
2087 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002088 result = _lib.SSL_get_cipher_list(self._ssl, i)
2089 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002090 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002091 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002092 return ciphers
2093
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002094 def get_client_ca_list(self):
2095 """
2096 Get CAs whose certificates are suggested for client authentication.
2097
Alex Chand072cae2018-02-15 09:57:59 +00002098 :return: If this is a server connection, the list of certificate
2099 authorities that will be sent or has been sent to the client, as
2100 controlled by this :class:`Connection`'s :class:`Context`.
2101
2102 If this is a client connection, the list will be empty until the
2103 connection with the server is established.
2104
2105 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002107 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2108 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002109 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002110 return []
2111
2112 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002113 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2114 name = _lib.sk_X509_NAME_value(ca_names, i)
2115 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002116 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002117
2118 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002119 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002120 result.append(pyname)
2121 return result
2122
Aykee7f33452018-05-16 19:18:16 +02002123 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002124 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002125 The makefile() method is not implemented, since there is no dup
2126 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002127
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002128 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002129 """
Alex Gaynor83284952015-09-05 10:43:30 -04002130 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04002131 "Cannot make file object of OpenSSL.SSL.Connection"
2132 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002133
2134 def get_app_data(self):
2135 """
Alex Chand072cae2018-02-15 09:57:59 +00002136 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002137
2138 :return: The application data
2139 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002140 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002141
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002142 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002143 """
2144 Set application data
2145
Alex Chand072cae2018-02-15 09:57:59 +00002146 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002147 :return: None
2148 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002149 self._app_data = data
2150
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002151 def get_shutdown(self):
2152 """
Alex Chand072cae2018-02-15 09:57:59 +00002153 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002154
Alex Gaynor62da94d2015-09-05 14:37:34 -04002155 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2156 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002157 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002158 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002159
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002160 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002161 """
Alex Chand072cae2018-02-15 09:57:59 +00002162 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002163
Alex Chand072cae2018-02-15 09:57:59 +00002164 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002165 :return: None
2166 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002167 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002168 raise TypeError("state must be an integer")
2169
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002170 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002171
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002172 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002173 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002174 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002175
2176 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002177 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178 """
kjavc704a2e2015-09-07 12:12:27 +01002179 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002180
2181 def server_random(self):
2182 """
Alex Chand072cae2018-02-15 09:57:59 +00002183 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002184
2185 :return: A string representing the state
2186 """
Alex Gaynor93603062016-06-01 20:13:09 -07002187 session = _lib.SSL_get_session(self._ssl)
2188 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002189 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002190 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002191 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002192 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002193 _lib.SSL_get_server_random(self._ssl, outp, length)
2194 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002195
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196 def client_random(self):
2197 """
Alex Chand072cae2018-02-15 09:57:59 +00002198 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002199
2200 :return: A string representing the state
2201 """
Alex Gaynor93603062016-06-01 20:13:09 -07002202 session = _lib.SSL_get_session(self._ssl)
2203 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002204 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002205
2206 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002207 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002208 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002209 _lib.SSL_get_client_random(self._ssl, outp, length)
2210 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002211
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002212 def master_key(self):
2213 """
Alex Chand072cae2018-02-15 09:57:59 +00002214 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002215
2216 :return: A string representing the state
2217 """
Alex Gaynor93603062016-06-01 20:13:09 -07002218 session = _lib.SSL_get_session(self._ssl)
2219 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002220 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002221
2222 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002223 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002224 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002225 _lib.SSL_SESSION_get_master_key(session, outp, length)
2226 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002227
Paul Kehrerbdb76392017-12-01 04:54:32 +08002228 def export_keying_material(self, label, olen, context=None):
2229 """
2230 Obtain keying material for application use.
2231
Alex Chand072cae2018-02-15 09:57:59 +00002232 :param: label - a disambiguating label string as described in RFC 5705
2233 :param: olen - the length of the exported key material in bytes
2234 :param: context - a per-association context value
2235 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002236 """
2237 outp = _no_zero_allocator("unsigned char[]", olen)
2238 context_buf = _ffi.NULL
2239 context_len = 0
2240 use_context = 0
2241 if context is not None:
2242 context_buf = context
2243 context_len = len(context)
2244 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002245 success = _lib.SSL_export_keying_material(
2246 self._ssl,
2247 outp,
2248 olen,
2249 label,
2250 len(label),
2251 context_buf,
2252 context_len,
2253 use_context,
2254 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002255 _openssl_assert(success == 1)
2256 return _ffi.buffer(outp, olen)[:]
2257
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002258 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002259 """
Alex Chand072cae2018-02-15 09:57:59 +00002260 Call the :meth:`shutdown` method of the underlying socket.
2261 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002262
2263 :return: What the socket's shutdown() method returns
2264 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002265 return self._socket.shutdown(*args, **kwargs)
2266
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002267 def get_certificate(self):
2268 """
2269 Retrieve the local certificate (if any)
2270
2271 :return: The local certificate
2272 """
2273 cert = _lib.SSL_get_certificate(self._ssl)
2274 if cert != _ffi.NULL:
2275 _lib.X509_up_ref(cert)
2276 return X509._from_raw_x509_ptr(cert)
2277 return None
2278
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002279 def get_peer_certificate(self):
2280 """
2281 Retrieve the other side's certificate (if any)
2282
2283 :return: The peer's certificate
2284 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002285 cert = _lib.SSL_get_peer_certificate(self._ssl)
2286 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002287 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002288 return None
2289
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002290 def get_peer_cert_chain(self):
2291 """
2292 Retrieve the other side's certificate (if any)
2293
2294 :return: A list of X509 instances giving the peer's certificate chain,
2295 or None if it does not have one.
2296 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002297 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2298 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002299 return None
2300
2301 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002302 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002303 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002304 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002305 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002306 result.append(pycert)
2307 return result
2308
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002309 def want_read(self):
2310 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002311 Checks if more data has to be read from the transport layer to complete
2312 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002313
2314 :return: True iff more data has to be read
2315 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002316 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002317
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002318 def want_write(self):
2319 """
2320 Checks if there is data to write to the transport layer to complete an
2321 operation.
2322
2323 :return: True iff there is data to write
2324 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002325 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002326
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002327 def set_accept_state(self):
2328 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002329 Set the connection to work in server mode. The handshake will be
2330 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002331
2332 :return: None
2333 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002334 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002335
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002336 def set_connect_state(self):
2337 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002338 Set the connection to work in client mode. The handshake will be
2339 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002340
2341 :return: None
2342 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002343 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002344
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002345 def get_session(self):
2346 """
2347 Returns the Session currently used.
2348
Alex Chand072cae2018-02-15 09:57:59 +00002349 :return: An instance of :class:`OpenSSL.SSL.Session` or
2350 :obj:`None` if no session exists.
2351
2352 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002353 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002354 session = _lib.SSL_get1_session(self._ssl)
2355 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002356 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002357
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002358 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002359 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002360 return pysession
2361
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002362 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002363 """
2364 Set the session to be used when the TLS/SSL connection is established.
2365
2366 :param session: A Session instance representing the session to use.
2367 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002368
2369 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002370 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002371 if not isinstance(session, Session):
2372 raise TypeError("session must be a Session instance")
2373
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002374 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002375 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002376
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002377 def _get_finished_message(self, function):
2378 """
Alex Chand072cae2018-02-15 09:57:59 +00002379 Helper to implement :meth:`get_finished` and
2380 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002381
Alex Chand072cae2018-02-15 09:57:59 +00002382 :param function: Either :data:`SSL_get_finished`: or
2383 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002384
Alex Chand072cae2018-02-15 09:57:59 +00002385 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002386 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002387 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002388 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002389 # The OpenSSL documentation says nothing about what might happen if the
2390 # count argument given is zero. Specifically, it doesn't say whether
2391 # the output buffer may be NULL in that case or not. Inspection of the
2392 # implementation reveals that it calls memcpy() unconditionally.
2393 # Section 7.1.4, paragraph 1 of the C standard suggests that
2394 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2395 # alone desirable) behavior (though it probably does on just about
2396 # every implementation...)
2397 #
2398 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2399 # one might expect) for the initial call so as to be safe against this
2400 # potentially undefined behavior.
2401 empty = _ffi.new("char[]", 0)
2402 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002403 if size == 0:
2404 # No Finished message so far.
2405 return None
2406
Cory Benfielde62840e2016-11-28 12:17:08 +00002407 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002408 function(self._ssl, buf, size)
2409 return _ffi.buffer(buf, size)[:]
2410
Fedor Brunner5747b932014-03-05 14:22:34 +01002411 def get_finished(self):
2412 """
Alex Chand072cae2018-02-15 09:57:59 +00002413 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002414
Alex Chand072cae2018-02-15 09:57:59 +00002415 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002416 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002417 :rtype: :class:`bytes` or :class:`NoneType`
2418
2419 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002420 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002421 return self._get_finished_message(_lib.SSL_get_finished)
2422
Fedor Brunner5747b932014-03-05 14:22:34 +01002423 def get_peer_finished(self):
2424 """
Alex Chand072cae2018-02-15 09:57:59 +00002425 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002426
Alex Chand072cae2018-02-15 09:57:59 +00002427 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002428 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002429 :rtype: :class:`bytes` or :class:`NoneType`
2430
2431 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002432 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002433 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002434
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002435 def get_cipher_name(self):
2436 """
2437 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002438
Alex Chand072cae2018-02-15 09:57:59 +00002439 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002440 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002441 :rtype: :class:`unicode` or :class:`NoneType`
2442
2443 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002444 """
2445 cipher = _lib.SSL_get_current_cipher(self._ssl)
2446 if cipher == _ffi.NULL:
2447 return None
2448 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002449 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2450 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002451
2452 def get_cipher_bits(self):
2453 """
2454 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002455
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002456 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002457 or :obj:`None` if no connection has been established.
2458 :rtype: :class:`int` or :class:`NoneType`
2459
2460 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002461 """
2462 cipher = _lib.SSL_get_current_cipher(self._ssl)
2463 if cipher == _ffi.NULL:
2464 return None
2465 else:
2466 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2467
2468 def get_cipher_version(self):
2469 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002470 Obtain the protocol version of the currently used cipher.
2471
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002472 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002473 or :obj:`None` if no connection has been established.
2474 :rtype: :class:`unicode` or :class:`NoneType`
2475
2476 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002477 """
2478 cipher = _lib.SSL_get_current_cipher(self._ssl)
2479 if cipher == _ffi.NULL:
2480 return None
2481 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002482 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002483 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002484
Jim Shaverabff1882015-05-27 09:15:55 -04002485 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002486 """
Alex Chand072cae2018-02-15 09:57:59 +00002487 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002488
2489 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002490 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002491 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002492 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002493 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002494 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002495 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002496
Jim Shaver208438c2015-05-28 09:52:38 -04002497 def get_protocol_version(self):
2498 """
Alex Chand072cae2018-02-15 09:57:59 +00002499 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002500
Alex Chand072cae2018-02-15 09:57:59 +00002501 :returns: The TLS version of the current connection. For example,
2502 it will return ``0x769`` for connections made over TLS version 1.
2503 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002504 """
2505 version = _lib.SSL_version(self._ssl)
2506 return version
2507
Cory Benfield10b277f2015-04-13 17:12:42 -04002508 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002509 def get_next_proto_negotiated(self):
2510 """
2511 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002512
2513 :returns: A bytestring of the protocol name. If no protocol has been
2514 negotiated yet, returns an empty string.
2515
2516 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002517 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002518 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002519 data = _ffi.new("unsigned char **")
2520 data_len = _ffi.new("unsigned int *")
2521
2522 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2523
Cory Benfieldcd010f62014-05-15 19:00:27 +01002524 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002525
Cory Benfield7907e332015-04-13 17:18:25 -04002526 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002527 def set_alpn_protos(self, protos):
2528 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002529 Specify the client's ALPN protocol list.
2530
2531 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002532
2533 :param protos: A list of the protocols to be offered to the server.
2534 This list should be a Python list of bytestrings representing the
2535 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2536 """
2537 # Take the list of protocols and join them together, prefixing them
2538 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002539 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002540 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2541 )
2542
2543 # Build a C string from the list. We don't need to save this off
2544 # because OpenSSL immediately copies the data out.
2545 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002546 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002547
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002548 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002549 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002550 """
2551 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002552
2553 :returns: A bytestring of the protocol name. If no protocol has been
2554 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002555 """
Cory Benfield12eae892014-06-07 15:42:56 +01002556 data = _ffi.new("unsigned char **")
2557 data_len = _ffi.new("unsigned int *")
2558
2559 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2560
Cory Benfielde8e9c382015-04-11 17:33:48 -04002561 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002562 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002563
Cory Benfield12eae892014-06-07 15:42:56 +01002564 return _ffi.buffer(data[0], data_len[0])[:]
2565
Cory Benfield496652a2017-01-24 11:42:56 +00002566 def request_ocsp(self):
2567 """
2568 Called to request that the server sends stapled OCSP data, if
2569 available. If this is not called on the client side then the server
2570 will not send OCSP data. Should be used in conjunction with
2571 :meth:`Context.set_ocsp_client_callback`.
2572 """
2573 rc = _lib.SSL_set_tlsext_status_type(
2574 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2575 )
2576 _openssl_assert(rc == 1)
2577
Cory Benfield12eae892014-06-07 15:42:56 +01002578
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002579# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2580# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002581_lib.SSL_library_init()