blob: b4b308f4ac3b7507fe3fea30c076906b6a96c442 [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
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800699class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000700 """
701 A class representing an SSL session. A session defines certain connection
702 parameters which may be re-used to speed up the setup of subsequent
703 connections.
704
705 .. versionadded:: 0.14
706 """
Alex Gaynor03737182020-07-23 20:40:46 -0400707
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800708 pass
709
710
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800711class Context(object):
712 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100713 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400714 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000715
716 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
717 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718 """
Alex Gaynor03737182020-07-23 20:40:46 -0400719
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800720 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800721 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500722 SSLv3_METHOD: "SSLv3_method",
723 SSLv23_METHOD: "SSLv23_method",
724 TLSv1_METHOD: "TLSv1_method",
725 TLSv1_1_METHOD: "TLSv1_1_method",
726 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400727 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500728 _methods = dict(
729 (identifier, getattr(_lib, name))
730 for (identifier, name) in _methods.items()
Alex Gaynor03737182020-07-23 20:40:46 -0400731 if getattr(_lib, name, None) is not None
732 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800733
734 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500735 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800736 raise TypeError("method must be an integer")
737
738 try:
739 method_func = self._methods[method]
740 except KeyError:
741 raise ValueError("No such protocol")
742
743 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700744 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800745
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700747 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500748 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800749
Alex Gaynor77debda2020-04-07 13:40:59 -0400750 # Set SSL_CTX_set_ecdh_auto so that the ECDH curve will be
751 # auto-selected. This function was added in 1.0.2 and made a noop in
752 # 1.1.0+ (where it is set automatically).
753 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
754 _openssl_assert(res == 1)
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600755
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800757 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800759 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800760 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761 self._verify_callback = None
762 self._info_callback = None
763 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800764 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000765 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100766 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000767 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100768 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400769 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100770 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000771 self._ocsp_helper = None
772 self._ocsp_callback = None
773 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800774
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500775 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777 def load_verify_locations(self, cafile, capath=None):
778 """
779 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000780 chain. Note that the certificates have to be in PEM format.
781
782 If capath is passed, it must be a directory prepared using the
783 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
784 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400786 :param cafile: In which file we can find the certificates (``bytes`` or
787 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400789 (``bytes`` or ``unicode``).
790
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791 :return: None
792 """
793 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500794 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400795 else:
796 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800797
798 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500799 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400800 else:
801 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800802
Alex Gaynor62da94d2015-09-05 14:37:34 -0400803 load_result = _lib.SSL_CTX_load_verify_locations(
804 self._context, cafile, capath
805 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800806 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500807 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800808
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809 def _wrap_callback(self, callback):
810 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800811 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800812 return callback(size, verify, self._passphrase_userdata)
Alex Gaynor03737182020-07-23 20:40:46 -0400813
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814 return _PassphraseHelper(
Alex Gaynor03737182020-07-23 20:40:46 -0400815 FILETYPE_PEM, wrapper, more_args=True, truncate=True
816 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 def set_passwd_cb(self, callback, userdata=None):
819 """
Alex Chand072cae2018-02-15 09:57:59 +0000820 Set the passphrase callback. This function will be called
821 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800822
Alex Chand072cae2018-02-15 09:57:59 +0000823 :param callback: The Python callback to use. This must accept three
824 positional arguments. First, an integer giving the maximum length
825 of the passphrase it may return. If the returned passphrase is
826 longer than this, it will be truncated. Second, a boolean value
827 which will be true if the user should be prompted for the
828 passphrase twice and the callback should verify that the two values
829 supplied are equal. Third, the value given as the *userdata*
830 parameter to :meth:`set_passwd_cb`. The *callback* must return
831 a byte string. If an error occurs, *callback* should return a false
832 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800833 :param userdata: (optional) A Python object which will be given as
834 argument to the callback
835 :return: None
836 """
837 if not callable(callback):
838 raise TypeError("callback must be callable")
839
840 self._passphrase_helper = self._wrap_callback(callback)
841 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500842 _lib.SSL_CTX_set_default_passwd_cb(
Alex Gaynor03737182020-07-23 20:40:46 -0400843 self._context, self._passphrase_callback
844 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845 self._passphrase_userdata = userdata
846
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800847 def set_default_verify_paths(self):
848 """
Alex Chand072cae2018-02-15 09:57:59 +0000849 Specify that the platform provided CA certificates are to be used for
850 verification purposes. This method has some caveats related to the
851 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
852
853 * macOS will only load certificates using this method if the user has
854 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
855 in the default location.
856 * Windows will not work.
857 * manylinux1 cryptography wheels will work on most common Linux
858 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
859 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800860
861 :return: None
862 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500863 # SSL_CTX_set_default_verify_paths will attempt to load certs from
864 # both a cafile and capath that are set at compile time. However,
865 # it will first check environment variables and, if present, load
866 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500867 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400868 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500869 # After attempting to set default_verify_paths we need to know whether
870 # to go down the fallback path.
871 # First we'll check to see if any env vars have been set. If so,
872 # we won't try to do anything else because the user has set the path
873 # themselves.
Alex Gaynor03737182020-07-23 20:40:46 -0400874 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
875 "ascii"
876 )
Paul Kehrer55fb3412017-06-29 18:44:08 -0500877 file_env_var = _ffi.string(
878 _lib.X509_get_default_cert_file_env()
879 ).decode("ascii")
880 if not self._check_env_vars_set(dir_env_var, file_env_var):
881 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
882 default_file = _ffi.string(_lib.X509_get_default_cert_file())
883 # Now we check to see if the default_dir and default_file are set
884 # to the exact values we use in our manylinux1 builds. If they are
885 # then we know to load the fallbacks
886 if (
Alex Gaynor03737182020-07-23 20:40:46 -0400887 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR
888 and default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
Paul Kehrer55fb3412017-06-29 18:44:08 -0500889 ):
890 # This is manylinux1, let's load our fallback paths
891 self._fallback_default_verify_paths(
Alex Gaynor03737182020-07-23 20:40:46 -0400892 _CERTIFICATE_FILE_LOCATIONS, _CERTIFICATE_PATH_LOCATIONS
Paul Kehrer55fb3412017-06-29 18:44:08 -0500893 )
894
895 def _check_env_vars_set(self, dir_env_var, file_env_var):
896 """
897 Check to see if the default cert dir/file environment vars are present.
898
899 :return: bool
900 """
901 return (
Alex Gaynor03737182020-07-23 20:40:46 -0400902 os.environ.get(file_env_var) is not None
903 or os.environ.get(dir_env_var) is not None
Paul Kehrer55fb3412017-06-29 18:44:08 -0500904 )
905
906 def _fallback_default_verify_paths(self, file_path, dir_path):
907 """
908 Default verify paths are based on the compiled version of OpenSSL.
909 However, when pyca/cryptography is compiled as a manylinux1 wheel
910 that compiled location can potentially be wrong. So, like Go, we
911 will try a predefined set of paths and attempt to load roots
912 from there.
913
914 :return: None
915 """
916 for cafile in file_path:
917 if os.path.isfile(cafile):
918 self.load_verify_locations(cafile)
919 break
920
921 for capath in dir_path:
922 if os.path.isdir(capath):
923 self.load_verify_locations(None, capath)
924 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800925
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800926 def use_certificate_chain_file(self, certfile):
927 """
Alex Chand072cae2018-02-15 09:57:59 +0000928 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400930 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000931 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400932
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800933 :return: None
934 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400935 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800936
Alex Gaynor62da94d2015-09-05 14:37:34 -0400937 result = _lib.SSL_CTX_use_certificate_chain_file(
938 self._context, certfile
939 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800940 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500941 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800942
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800943 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800944 """
945 Load a certificate from a file
946
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400947 :param certfile: The name of the certificate file (``bytes`` or
948 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000949 :param filetype: (optional) The encoding of the file, which is either
950 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
951 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400952
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800953 :return: None
954 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400955 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500956 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800957 raise TypeError("filetype must be an integer")
958
Alex Gaynor62da94d2015-09-05 14:37:34 -0400959 use_result = _lib.SSL_CTX_use_certificate_file(
960 self._context, certfile, filetype
961 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800962 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500963 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800964
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800965 def use_certificate(self, cert):
966 """
967 Load a certificate from a X509 object
968
969 :param cert: The X509 object
970 :return: None
971 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800972 if not isinstance(cert, X509):
973 raise TypeError("cert must be an X509 instance")
974
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500975 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800976 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500977 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800978
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979 def add_extra_chain_cert(self, certobj):
980 """
981 Add certificate to chain
982
983 :param certobj: The X509 certificate object to add to the chain
984 :return: None
985 """
986 if not isinstance(certobj, X509):
987 raise TypeError("certobj must be an X509 instance")
988
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500989 copy = _lib.X509_dup(certobj._x509)
990 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500992 # TODO: This is untested.
993 _lib.X509_free(copy)
994 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800996 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500997 if self._passphrase_helper is not None:
998 self._passphrase_helper.raise_if_problem(Error)
999
1000 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001001
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001002 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003 """
1004 Load a private key from a file
1005
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -04001006 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +00001007 :param filetype: (optional) The encoding of the file, which is either
1008 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
1009 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -04001010
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011 :return: None
1012 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -04001013 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001015 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001016 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001017 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001018 raise TypeError("filetype must be an integer")
1019
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001020 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Alex Gaynor03737182020-07-23 20:40:46 -04001021 self._context, keyfile, filetype
1022 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001023 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001024 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026 def use_privatekey(self, pkey):
1027 """
1028 Load a private key from a PKey object
1029
1030 :param pkey: The PKey object
1031 :return: None
1032 """
1033 if not isinstance(pkey, PKey):
1034 raise TypeError("pkey must be a PKey instance")
1035
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001036 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001037 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001038 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001040 def check_privatekey(self):
1041 """
Alex Chand072cae2018-02-15 09:57:59 +00001042 Check if the private key (loaded with :meth:`use_privatekey`) matches
1043 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044
Alex Chand072cae2018-02-15 09:57:59 +00001045 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001047 if not _lib.SSL_CTX_check_private_key(self._context):
1048 _raise_current_error()
1049
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001050 def load_client_ca(self, cafile):
1051 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001052 Load the trusted certificates that will be sent to the client. Does
1053 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001054 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001056 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001057 :return: None
1058 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001059 ca_list = _lib.SSL_load_client_CA_file(
1060 _text_to_bytes_and_warn("cafile", cafile)
1061 )
1062 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001063 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064
1065 def set_session_id(self, buf):
1066 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001067 Set the session id to *buf* within which a session can be reused for
1068 this Context object. This is needed when doing session resumption,
1069 because there is no way for a stored session to know which Context
1070 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001071
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001072 :param bytes buf: The session id.
1073
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001074 :returns: None
1075 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001076 buf = _text_to_bytes_and_warn("buf", buf)
1077 _openssl_assert(
Alex Gaynor03737182020-07-23 20:40:46 -04001078 _lib.SSL_CTX_set_session_id_context(self._context, buf, len(buf),)
1079 == 1
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001080 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001081
1082 def set_session_cache_mode(self, mode):
1083 """
Alex Chand072cae2018-02-15 09:57:59 +00001084 Set the behavior of the session cache used by all connections using
1085 this Context. The previously set mode is returned. See
1086 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
1088 :param mode: One or more of the SESS_CACHE_* flags (combine using
1089 bitwise or)
1090 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001091
1092 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001094 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001095 raise TypeError("mode must be an integer")
1096
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001097 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099 def get_session_cache_mode(self):
1100 """
Alex Chand072cae2018-02-15 09:57:59 +00001101 Get the current session cache mode.
1102
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001103 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001104
1105 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001106 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001108
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 def set_verify(self, mode, callback):
1110 """
Alex Chand072cae2018-02-15 09:57:59 +00001111 et the verification flags for this Context object to *mode* and specify
1112 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001113
Alex Chand072cae2018-02-15 09:57:59 +00001114 :param mode: The verify mode, this should be one of
1115 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1116 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1117 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1118 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1119 :param callback: The Python callback to use. This should take five
1120 arguments: A Connection object, an X509 object, and three integer
1121 variables, which are in turn potential error number, error depth
1122 and return code. *callback* should return True if verification
1123 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124 :return: None
1125
1126 See SSL_CTX_set_verify(3SSL) for further details.
1127 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001128 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001129 raise TypeError("mode must be an integer")
1130
1131 if not callable(callback):
1132 raise TypeError("callback must be callable")
1133
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001134 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001135 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001136 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001137
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138 def set_verify_depth(self, depth):
1139 """
Alex Chand072cae2018-02-15 09:57:59 +00001140 Set the maximum depth for the certificate chain verification that shall
1141 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
1143 :param depth: An integer specifying the verify depth
1144 :return: None
1145 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001146 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147 raise TypeError("depth must be an integer")
1148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001150
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001151 def get_verify_mode(self):
1152 """
Alex Chand072cae2018-02-15 09:57:59 +00001153 Retrieve the Context object's verify mode, as set by
1154 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001155
1156 :return: The verify mode
1157 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001158 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001159
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001160 def get_verify_depth(self):
1161 """
Alex Chand072cae2018-02-15 09:57:59 +00001162 Retrieve the Context object's verify depth, as set by
1163 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001164
1165 :return: The verify depth
1166 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001168
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001169 def load_tmp_dh(self, dhfile):
1170 """
1171 Load parameters for Ephemeral Diffie-Hellman
1172
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001173 :param dhfile: The file to load EDH parameters from (``bytes`` or
1174 ``unicode``).
1175
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001176 :return: None
1177 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001178 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001179
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001180 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001182 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001183 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001185 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1186 dh = _ffi.gc(dh, _lib.DH_free)
1187 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001188
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001189 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001190 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001191 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001192
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001193 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001194 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1195 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001196
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001197 :return: None
1198 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001199 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001200
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201 def set_cipher_list(self, cipher_list):
1202 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001203 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001205 See the OpenSSL manual for more information (e.g.
1206 :manpage:`ciphers(1)`).
1207
1208 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001209 :return: None
1210 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001211 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001212
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001213 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001214 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001215
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001216 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001217 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001218 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001219 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1220 # ciphers even if you pass an invalid cipher. Applications (like
1221 # Twisted) have tests that depend on an error being raised if an
1222 # invalid cipher string is passed, but without the following check
1223 # for the TLS 1.3 specific cipher suites it would never error.
1224 tmpconn = Connection(self, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001225 if tmpconn.get_cipher_list() == [
1226 "TLS_AES_256_GCM_SHA384",
1227 "TLS_CHACHA20_POLY1305_SHA256",
1228 "TLS_AES_128_GCM_SHA256",
1229 ]:
Mark Williamsdf2480d2019-02-14 19:30:07 -08001230 raise Error(
1231 [
1232 (
Alex Gaynor03737182020-07-23 20:40:46 -04001233 "SSL routines",
1234 "SSL_CTX_set_cipher_list",
1235 "no cipher match",
Mark Williamsdf2480d2019-02-14 19:30:07 -08001236 ),
1237 ],
1238 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001239
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001240 def set_client_ca_list(self, certificate_authorities):
1241 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001242 Set the list of preferred client certificate signers for this server
1243 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001244
Alex Gaynor62da94d2015-09-05 14:37:34 -04001245 This list of certificate authorities will be sent to the client when
1246 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001247
1248 :param certificate_authorities: a sequence of X509Names.
1249 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001250
1251 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001252 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001253 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001254 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001255
1256 try:
1257 for ca_name in certificate_authorities:
1258 if not isinstance(ca_name, X509Name):
1259 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001260 "client CAs must be X509Name objects, not %s "
Alex Gaynor03737182020-07-23 20:40:46 -04001261 "objects" % (type(ca_name).__name__,)
Alex Gaynor62da94d2015-09-05 14:37:34 -04001262 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001263 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001264 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001265 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001266 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001267 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001268 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001269 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001270 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001271 raise
1272
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001273 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001274
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001275 def add_client_ca(self, certificate_authority):
1276 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001277 Add the CA certificate to the list of preferred signers for this
1278 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001279
1280 The list of certificate authorities will be sent to the client when the
1281 server requests a client certificate.
1282
1283 :param certificate_authority: certificate authority's X509 certificate.
1284 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001285
1286 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001288 if not isinstance(certificate_authority, X509):
1289 raise TypeError("certificate_authority must be an X509 instance")
1290
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001291 add_result = _lib.SSL_CTX_add_client_CA(
Alex Gaynor03737182020-07-23 20:40:46 -04001292 self._context, certificate_authority._x509
1293 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001294 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001295
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296 def set_timeout(self, timeout):
1297 """
Alex Chand072cae2018-02-15 09:57:59 +00001298 Set the timeout for newly created sessions for this Context object to
1299 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1300 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001301
Alex Chand072cae2018-02-15 09:57:59 +00001302 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001303 :return: The previous session timeout
1304 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001305 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001306 raise TypeError("timeout must be an integer")
1307
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001308 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001309
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001310 def get_timeout(self):
1311 """
Alex Chand072cae2018-02-15 09:57:59 +00001312 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1313 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001314
1315 :return: The session timeout
1316 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001317 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001318
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001319 def set_info_callback(self, callback):
1320 """
Alex Chand072cae2018-02-15 09:57:59 +00001321 Set the information callback to *callback*. This function will be
1322 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001323
Alex Chand072cae2018-02-15 09:57:59 +00001324 :param callback: The Python callback to use. This should take three
1325 arguments: a Connection object and two integers. The first integer
1326 specifies where in the SSL handshake the function was called, and
1327 the other the return code from a (possibly failed) internal
1328 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001329 :return: None
1330 """
Alex Gaynor03737182020-07-23 20:40:46 -04001331
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001332 @wraps(callback)
1333 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001334 callback(Connection._reverse_mapping[ssl], where, return_code)
Alex Gaynor03737182020-07-23 20:40:46 -04001335
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001336 self._info_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001337 "void (*)(const SSL *, int, int)", wrapper
1338 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001339 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001340
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001341 def get_app_data(self):
1342 """
Alex Chand072cae2018-02-15 09:57:59 +00001343 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001344
1345 :return: The application data
1346 """
1347 return self._app_data
1348
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001349 def set_app_data(self, data):
1350 """
1351 Set the application data (will be returned from get_app_data())
1352
1353 :param data: Any Python object
1354 :return: None
1355 """
1356 self._app_data = data
1357
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358 def get_cert_store(self):
1359 """
Alex Chand072cae2018-02-15 09:57:59 +00001360 Get the certificate store for the context. This can be used to add
1361 "trusted" certificates without using the
1362 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001363
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001364 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001365 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001366 store = _lib.SSL_CTX_get_cert_store(self._context)
1367 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001368 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001369 return None
1370
1371 pystore = X509Store.__new__(X509Store)
1372 pystore._store = store
1373 return pystore
1374
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001375 def set_options(self, options):
1376 """
1377 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001378 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001379
1380 :param options: The options to add.
1381 :return: The new option bitmask.
1382 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001383 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001384 raise TypeError("options must be an integer")
1385
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001386 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001387
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001388 def set_mode(self, mode):
1389 """
Alex Chand072cae2018-02-15 09:57:59 +00001390 Add modes via bitmask. Modes set before are not cleared! This method
1391 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001392
1393 :param mode: The mode to add.
1394 :return: The new mode bitmask.
1395 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001396 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001397 raise TypeError("mode must be an integer")
1398
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001399 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001400
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001401 def set_tlsext_servername_callback(self, callback):
1402 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001403 Specify a callback function to be called when clients specify a server
1404 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001405
1406 :param callback: The callback function. It will be invoked with one
1407 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001408
1409 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001410 """
Alex Gaynor03737182020-07-23 20:40:46 -04001411
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001412 @wraps(callback)
1413 def wrapper(ssl, alert, arg):
1414 callback(Connection._reverse_mapping[ssl])
1415 return 0
1416
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001417 self._tlsext_servername_callback = _ffi.callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001418 "int (*)(SSL *, int *, void *)", wrapper
1419 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001420 _lib.SSL_CTX_set_tlsext_servername_callback(
Alex Gaynor03737182020-07-23 20:40:46 -04001421 self._context, self._tlsext_servername_callback
1422 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001423
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001424 def set_tlsext_use_srtp(self, profiles):
1425 """
1426 Enable support for negotiating SRTP keying material.
1427
1428 :param bytes profiles: A colon delimited list of protection profile
1429 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1430 :return: None
1431 """
1432 if not isinstance(profiles, bytes):
1433 raise TypeError("profiles must be a byte string.")
1434
1435 _openssl_assert(
1436 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1437 )
1438
Cory Benfield10b277f2015-04-13 17:12:42 -04001439 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001440 def set_npn_advertise_callback(self, callback):
1441 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001442 Specify a callback function that will be called when offering `Next
1443 Protocol Negotiation
1444 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001445
1446 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001447 argument, the :class:`Connection` instance. It should return a
1448 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001449 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001450
1451 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001452 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001453 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001454 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1455 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001456 _lib.SSL_CTX_set_next_protos_advertised_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001457 self._context, self._npn_advertise_callback, _ffi.NULL
1458 )
Cory Benfield84a121e2014-03-31 20:30:25 +01001459
Cory Benfield10b277f2015-04-13 17:12:42 -04001460 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001461 def set_npn_select_callback(self, callback):
1462 """
1463 Specify a callback function that will be called when a server offers
1464 Next Protocol Negotiation options.
1465
1466 :param callback: The callback function. It will be invoked with two
1467 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001468 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1469 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001470
1471 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001472 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001473 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001474 self._npn_select_helper = _NpnSelectHelper(callback)
1475 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001476 _lib.SSL_CTX_set_next_proto_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001477 self._context, self._npn_select_callback, _ffi.NULL
1478 )
Cory Benfield84a121e2014-03-31 20:30:25 +01001479
Cory Benfield7907e332015-04-13 17:18:25 -04001480 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001481 def set_alpn_protos(self, protos):
1482 """
Alex Chand072cae2018-02-15 09:57:59 +00001483 Specify the protocols that the client is prepared to speak after the
1484 TLS connection has been negotiated using Application Layer Protocol
1485 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001486
1487 :param protos: A list of the protocols to be offered to the server.
1488 This list should be a Python list of bytestrings representing the
1489 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1490 """
1491 # Take the list of protocols and join them together, prefixing them
1492 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04001493 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01001494 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1495 )
1496
1497 # Build a C string from the list. We don't need to save this off
1498 # because OpenSSL immediately copies the data out.
1499 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001500 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001501
Cory Benfield7907e332015-04-13 17:18:25 -04001502 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001503 def set_alpn_select_callback(self, callback):
1504 """
Alex Chand072cae2018-02-15 09:57:59 +00001505 Specify a callback function that will be called on the server when a
1506 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001507
1508 :param callback: The callback function. It will be invoked with two
1509 arguments: the Connection, and a list of offered protocols as
Mark Williams5d890a02019-11-17 19:56:26 -08001510 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It can return
1511 one of those bytestrings to indicate the chosen protocol, the
1512 empty bytestring to terminate the TLS connection, or the
1513 :py:obj:`NO_OVERLAPPING_PROTOCOLS` to indicate that no offered
1514 protocol was selected, but that the connection should not be
1515 aborted.
Cory Benfield12eae892014-06-07 15:42:56 +01001516 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001517 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001518 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001519 _lib.SSL_CTX_set_alpn_select_cb(
Alex Gaynor03737182020-07-23 20:40:46 -04001520 self._context, self._alpn_select_callback, _ffi.NULL
1521 )
Cory Benfield12eae892014-06-07 15:42:56 +01001522
Cory Benfield496652a2017-01-24 11:42:56 +00001523 def _set_ocsp_callback(self, helper, data):
1524 """
1525 This internal helper does the common work for
1526 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1527 almost all of it.
1528 """
1529 self._ocsp_helper = helper
1530 self._ocsp_callback = helper.callback
1531 if data is None:
1532 self._ocsp_data = _ffi.NULL
1533 else:
1534 self._ocsp_data = _ffi.new_handle(data)
1535
1536 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1537 self._context, self._ocsp_callback
1538 )
1539 _openssl_assert(rc == 1)
1540 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1541 _openssl_assert(rc == 1)
1542
1543 def set_ocsp_server_callback(self, callback, data=None):
1544 """
1545 Set a callback to provide OCSP data to be stapled to the TLS handshake
1546 on the server side.
1547
1548 :param callback: The callback function. It will be invoked with two
1549 arguments: the Connection, and the optional arbitrary data you have
1550 provided. The callback must return a bytestring that contains the
1551 OCSP data to staple to the handshake. If no OCSP data is available
1552 for this connection, return the empty bytestring.
1553 :param data: Some opaque data that will be passed into the callback
1554 function when called. This can be used to avoid needing to do
1555 complex data lookups or to keep track of what context is being
1556 used. This parameter is optional.
1557 """
1558 helper = _OCSPServerCallbackHelper(callback)
1559 self._set_ocsp_callback(helper, data)
1560
1561 def set_ocsp_client_callback(self, callback, data=None):
1562 """
1563 Set a callback to validate OCSP data stapled to the TLS handshake on
1564 the client side.
1565
1566 :param callback: The callback function. It will be invoked with three
1567 arguments: the Connection, a bytestring containing the stapled OCSP
1568 assertion, and the optional arbitrary data you have provided. The
1569 callback must return a boolean that indicates the result of
1570 validating the OCSP data: ``True`` if the OCSP data is valid and
1571 the certificate can be trusted, or ``False`` if either the OCSP
1572 data is invalid or the certificate has been revoked.
1573 :param data: Some opaque data that will be passed into the callback
1574 function when called. This can be used to avoid needing to do
1575 complex data lookups or to keep track of what context is being
1576 used. This parameter is optional.
1577 """
1578 helper = _OCSPClientCallbackHelper(callback)
1579 self._set_ocsp_callback(helper, data)
1580
Alex Chanc6077062016-11-18 13:53:39 +00001581
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001582class Connection(object):
1583 """
1584 """
Alex Gaynor03737182020-07-23 20:40:46 -04001585
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 _reverse_mapping = WeakValueDictionary()
1587
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 def __init__(self, context, socket=None):
1589 """
1590 Create a new Connection object, using the given OpenSSL.SSL.Context
1591 instance and socket.
1592
1593 :param context: An SSL Context to use for this connection
1594 :param socket: The socket to use for transport layer
1595 """
1596 if not isinstance(context, Context):
1597 raise TypeError("context must be a Context instance")
1598
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 ssl = _lib.SSL_new(context._context)
1600 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001601 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1602 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1603 # even though there is still data on the underlying transport.
1604 # See https://github.com/openssl/openssl/issues/6234 for more details.
1605 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001606 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001607 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001608
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001609 # References to strings used for Next Protocol Negotiation. OpenSSL's
1610 # header files suggest that these might get copied at some point, but
1611 # doesn't specify when, so we store them here to make sure they don't
1612 # get freed before OpenSSL uses them.
1613 self._npn_advertise_callback_args = None
1614 self._npn_select_callback_args = None
1615
Cory Benfield12eae892014-06-07 15:42:56 +01001616 # References to strings used for Application Layer Protocol
1617 # Negotiation. These strings get copied at some point but it's well
1618 # after the callback returns, so we have to hang them somewhere to
1619 # avoid them getting freed.
1620 self._alpn_select_callback_args = None
1621
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001622 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001623
1624 if socket is None:
1625 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001626 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001627 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001628 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629
Alex Gaynora829e902016-06-04 18:16:01 -07001630 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1631 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001632
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001633 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001634 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635 self._into_ssl = None
1636 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001638 set_result = _lib.SSL_set_fd(
Alex Gaynor03737182020-07-23 20:40:46 -04001639 self._ssl, _asFileDescriptor(self._socket)
1640 )
Alex Gaynor09f19f52016-07-03 09:54:09 -04001641 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001642
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001643 def __getattr__(self, name):
1644 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001645 Look up attributes on the wrapped socket object if they are not found
1646 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001647 """
kjav0b66fa12015-09-02 11:51:26 +01001648 if self._socket is None:
Alex Gaynor03737182020-07-23 20:40:46 -04001649 raise AttributeError(
1650 "'%s' object has no attribute '%s'"
1651 % (self.__class__.__name__, name)
1652 )
kjav0b66fa12015-09-02 11:51:26 +01001653 else:
1654 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001657 if self._context._verify_helper is not None:
1658 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001659 if self._context._npn_advertise_helper is not None:
1660 self._context._npn_advertise_helper.raise_if_problem()
1661 if self._context._npn_select_helper is not None:
1662 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001663 if self._context._alpn_select_helper is not None:
1664 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001665 if self._context._ocsp_helper is not None:
1666 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001667
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001668 error = _lib.SSL_get_error(ssl, result)
1669 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001671 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001672 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001673 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001675 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001676 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001677 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001678 elif error == _lib.SSL_ERROR_SYSCALL:
1679 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001680 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001681 if platform == "win32":
1682 errno = _ffi.getwinerror()[0]
1683 else:
1684 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001685
1686 if errno != 0:
1687 raise SysCallError(errno, errorcode.get(errno))
1688 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001689 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001690 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001691 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001692 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001693 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001694 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001695 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697 def get_context(self):
1698 """
Alex Chand072cae2018-02-15 09:57:59 +00001699 Retrieve the :class:`Context` object associated with this
1700 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001702 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001703
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001704 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705 """
Alex Chand072cae2018-02-15 09:57:59 +00001706 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001707
Alex Chand072cae2018-02-15 09:57:59 +00001708 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001711 if not isinstance(context, Context):
1712 raise TypeError("context must be a Context instance")
1713
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001714 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001715 self._context = context
1716
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001717 def get_servername(self):
1718 """
1719 Retrieve the servername extension value if provided in the client hello
1720 message, or None if there wasn't one.
1721
Alex Chand072cae2018-02-15 09:57:59 +00001722 :return: A byte string giving the server name or :data:`None`.
1723
1724 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001726 name = _lib.SSL_get_servername(
1727 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1728 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001729 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001730 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001731
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001732 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001733
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001734 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001735 """
1736 Set the value of the servername extension to send in the client hello.
1737
1738 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001739
1740 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001741 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 if not isinstance(name, bytes):
1743 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001744 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745 raise TypeError("name must not contain NUL byte")
1746
1747 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001749
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001750 def pending(self):
1751 """
Alex Chand072cae2018-02-15 09:57:59 +00001752 Get the number of bytes that can be safely read from the SSL buffer
1753 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001754
1755 :return: The number of bytes available in the receive buffer.
1756 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001757 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001758
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001759 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001760 """
1761 Send data on the connection. NOTE: If you get one of the WantRead,
1762 WantWrite or WantX509Lookup exceptions on this, you have to call the
1763 method again with the SAME buffer.
1764
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001765 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001766 :param flags: (optional) Included for compatibility with the socket
1767 API, the value is ignored
1768 :return: The number of bytes written
1769 """
Abraham Martine82326c2015-02-04 10:18:10 +00001770 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001771 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001772
Daniel Holth079c9632019-11-17 22:45:52 -05001773 with _from_buffer(buf) as data:
1774 # check len(buf) instead of len(data) for testability
1775 if len(buf) > 2147483647:
1776 raise ValueError(
1777 "Cannot send more than 2**31-1 bytes at once."
1778 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001779
Daniel Holth079c9632019-11-17 22:45:52 -05001780 result = _lib.SSL_write(self._ssl, data, len(data))
1781 self._raise_ssl_error(self._ssl, result)
1782
1783 return result
1784
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001785 write = send
1786
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001787 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001788 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001789 Send "all" data on the connection. This calls send() repeatedly until
1790 all data is sent. If an error occurs, it's impossible to tell how much
1791 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001793 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 :param flags: (optional) Included for compatibility with the socket
1795 API, the value is ignored
1796 :return: The number of bytes written
1797 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001798 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001799
Daniel Holth079c9632019-11-17 22:45:52 -05001800 with _from_buffer(buf) as data:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001801
Daniel Holth079c9632019-11-17 22:45:52 -05001802 left_to_send = len(buf)
1803 total_sent = 0
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001804
Daniel Holth079c9632019-11-17 22:45:52 -05001805 while left_to_send:
1806 # SSL_write's num arg is an int,
1807 # so we cannot send more than 2**31-1 bytes at once.
1808 result = _lib.SSL_write(
Alex Gaynor03737182020-07-23 20:40:46 -04001809 self._ssl, data + total_sent, min(left_to_send, 2147483647)
Daniel Holth079c9632019-11-17 22:45:52 -05001810 )
1811 self._raise_ssl_error(self._ssl, result)
1812 total_sent += result
1813 left_to_send -= result
1814
1815 return total_sent
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001816
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001817 def recv(self, bufsiz, flags=None):
1818 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001819 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001820
1821 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001822 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1823 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001824 :return: The string read from the Connection
1825 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001826 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001827 if flags is not None and flags & socket.MSG_PEEK:
1828 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1829 else:
1830 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001831 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001832 return _ffi.buffer(buf, result)[:]
Alex Gaynor03737182020-07-23 20:40:46 -04001833
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001834 read = recv
1835
Cory Benfield62d10332014-06-15 10:03:41 +01001836 def recv_into(self, buffer, nbytes=None, flags=None):
1837 """
Alex Chand072cae2018-02-15 09:57:59 +00001838 Receive data on the connection and copy it directly into the provided
1839 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001840
1841 :param buffer: The buffer to copy into.
1842 :param nbytes: (optional) The maximum number of bytes to read into the
1843 buffer. If not present, defaults to the size of the buffer. If
1844 larger than the size of the buffer, is reduced to the size of the
1845 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001846 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1847 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001848 :return: The number of bytes read into the buffer.
1849 """
1850 if nbytes is None:
1851 nbytes = len(buffer)
1852 else:
1853 nbytes = min(nbytes, len(buffer))
1854
1855 # We need to create a temporary buffer. This is annoying, it would be
1856 # better if we could pass memoryviews straight into the SSL_read call,
1857 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001858 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001859 if flags is not None and flags & socket.MSG_PEEK:
1860 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1861 else:
1862 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001863 self._raise_ssl_error(self._ssl, result)
1864
1865 # This strange line is all to avoid a memory copy. The buffer protocol
1866 # should allow us to assign a CFFI buffer to the LHS of this line, but
1867 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001868 # wrap it in a memoryview.
1869 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001870
1871 return result
1872
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001873 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001874 if _lib.BIO_should_retry(bio):
1875 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001876 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001877 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001878 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001879 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001880 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001881 # TODO: This is untested. I think io_special means the socket
1882 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001883 raise ValueError("BIO_should_io_special")
1884 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001885 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001886 raise ValueError("unknown bio failure")
1887 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001888 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001889 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001890
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001892 """
Alex Chand072cae2018-02-15 09:57:59 +00001893 If the Connection was created with a memory BIO, this method can be
1894 used to read bytes from the write end of that memory BIO. Many
1895 Connection methods will add bytes which must be read in this manner or
1896 the buffer will eventually fill up and the Connection will be able to
1897 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898
1899 :param bufsiz: The maximum number of bytes to read
1900 :return: The string read.
1901 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001902 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001903 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001905 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001906 raise TypeError("bufsiz must be an integer")
1907
Cory Benfielde62840e2016-11-28 12:17:08 +00001908 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001909 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001910 if result <= 0:
1911 self._handle_bio_errors(self._from_ssl, result)
1912
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001913 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001914
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001915 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916 """
Alex Chand072cae2018-02-15 09:57:59 +00001917 If the Connection was created with a memory BIO, this method can be
1918 used to add bytes to the read end of that memory BIO. The Connection
1919 can then read the bytes (for example, in response to a call to
1920 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921
1922 :param buf: The string to put into the memory BIO.
1923 :return: The number of bytes written
1924 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001925 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001926
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001927 if self._into_ssl is None:
1928 raise TypeError("Connection sock was not None")
1929
Daniel Holth079c9632019-11-17 22:45:52 -05001930 with _from_buffer(buf) as data:
1931 result = _lib.BIO_write(self._into_ssl, data, len(data))
1932 if result <= 0:
1933 self._handle_bio_errors(self._into_ssl, result)
1934 return result
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001935
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936 def renegotiate(self):
1937 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001938 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001940 :return: True if the renegotiation can be started, False otherwise
1941 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001942 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001943 if not self.renegotiate_pending():
1944 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1945 return True
1946 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947
1948 def do_handshake(self):
1949 """
Alex Chand072cae2018-02-15 09:57:59 +00001950 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001951 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001952 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001953
1954 :return: None.
1955 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001956 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001959 def renegotiate_pending(self):
1960 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001961 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962 a renegotiation is finished.
1963
1964 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001965 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001967 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968
1969 def total_renegotiations(self):
1970 """
1971 Find out the total number of renegotiations.
1972
1973 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001974 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001975 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001976 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001977
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001978 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001979 """
Alex Chand072cae2018-02-15 09:57:59 +00001980 Call the :meth:`connect` method of the underlying socket and set up SSL
1981 on the socket, using the :class:`Context` object supplied to this
1982 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983
1984 :param addr: A remote address
1985 :return: What the socket's connect method returns
1986 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001987 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001988 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001990 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001991 """
Alex Chand072cae2018-02-15 09:57:59 +00001992 Call the :meth:`connect_ex` method of the underlying socket and set up
1993 SSL on the socket, using the Context object supplied to this Connection
1994 object at creation. Note that if the :meth:`connect_ex` method of the
1995 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001996
1997 :param addr: A remove address
1998 :return: What the socket's connect_ex method returns
1999 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000 connect_ex = self._socket.connect_ex
2001 self.set_connect_state()
2002 return connect_ex(addr)
2003
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 def accept(self):
2005 """
Alex Chand072cae2018-02-15 09:57:59 +00002006 Call the :meth:`accept` method of the underlying socket and set up SSL
2007 on the returned socket, using the Context object supplied to this
2008 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002009
Alex Chand072cae2018-02-15 09:57:59 +00002010 :return: A *(conn, addr)* pair where *conn* is the new
2011 :class:`Connection` object created, and *address* is as returned by
2012 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002014 client, addr = self._socket.accept()
2015 conn = Connection(self._context, client)
2016 conn.set_accept_state()
2017 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019 def bio_shutdown(self):
2020 """
Alex Chand072cae2018-02-15 09:57:59 +00002021 If the Connection was created with a memory BIO, this method can be
2022 used to indicate that *end of file* has been reached on the read end of
2023 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024
2025 :return: None
2026 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002027 if self._from_ssl is None:
2028 raise TypeError("Connection sock was not None")
2029
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002030 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002031
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002032 def shutdown(self):
2033 """
Alex Chand072cae2018-02-15 09:57:59 +00002034 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035
2036 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00002037 have sent closure alerts), False otherwise (in which case you
2038 call :meth:`recv` or :meth:`send` when the connection becomes
2039 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002040 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002041 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002042 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002043 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002044 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002045 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002046 else:
2047 return False
2048
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049 def get_cipher_list(self):
2050 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002051 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002053 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002054 """
2055 ciphers = []
2056 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002057 result = _lib.SSL_get_cipher_list(self._ssl, i)
2058 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002059 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002060 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002061 return ciphers
2062
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002063 def get_client_ca_list(self):
2064 """
2065 Get CAs whose certificates are suggested for client authentication.
2066
Alex Chand072cae2018-02-15 09:57:59 +00002067 :return: If this is a server connection, the list of certificate
2068 authorities that will be sent or has been sent to the client, as
2069 controlled by this :class:`Connection`'s :class:`Context`.
2070
2071 If this is a client connection, the list will be empty until the
2072 connection with the server is established.
2073
2074 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002075 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002076 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2077 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002078 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002079 return []
2080
2081 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002082 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2083 name = _lib.sk_X509_NAME_value(ca_names, i)
2084 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002085 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002086
2087 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002088 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002089 result.append(pyname)
2090 return result
2091
Aykee7f33452018-05-16 19:18:16 +02002092 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002093 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002094 The makefile() method is not implemented, since there is no dup
2095 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002096
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002097 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002098 """
Alex Gaynor83284952015-09-05 10:43:30 -04002099 raise NotImplementedError(
Alex Gaynor03737182020-07-23 20:40:46 -04002100 "Cannot make file object of OpenSSL.SSL.Connection"
2101 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
2103 def get_app_data(self):
2104 """
Alex Chand072cae2018-02-15 09:57:59 +00002105 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106
2107 :return: The application data
2108 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002109 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002111 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002112 """
2113 Set application data
2114
Alex Chand072cae2018-02-15 09:57:59 +00002115 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002116 :return: None
2117 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002118 self._app_data = data
2119
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002120 def get_shutdown(self):
2121 """
Alex Chand072cae2018-02-15 09:57:59 +00002122 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123
Alex Gaynor62da94d2015-09-05 14:37:34 -04002124 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2125 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002126 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002127 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002128
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002129 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002130 """
Alex Chand072cae2018-02-15 09:57:59 +00002131 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002132
Alex Chand072cae2018-02-15 09:57:59 +00002133 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002134 :return: None
2135 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002136 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002137 raise TypeError("state must be an integer")
2138
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002139 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002140
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002141 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002142 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002143 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002144
2145 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002146 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002147 """
kjavc704a2e2015-09-07 12:12:27 +01002148 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002149
2150 def server_random(self):
2151 """
Alex Chand072cae2018-02-15 09:57:59 +00002152 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002153
2154 :return: A string representing the state
2155 """
Alex Gaynor93603062016-06-01 20:13:09 -07002156 session = _lib.SSL_get_session(self._ssl)
2157 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002158 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002159 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002160 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002161 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002162 _lib.SSL_get_server_random(self._ssl, outp, length)
2163 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002164
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002165 def client_random(self):
2166 """
Alex Chand072cae2018-02-15 09:57:59 +00002167 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002168
2169 :return: A string representing the state
2170 """
Alex Gaynor93603062016-06-01 20:13:09 -07002171 session = _lib.SSL_get_session(self._ssl)
2172 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002173 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002174
2175 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002176 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002177 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002178 _lib.SSL_get_client_random(self._ssl, outp, length)
2179 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002180
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002181 def master_key(self):
2182 """
Alex Chand072cae2018-02-15 09:57:59 +00002183 Retrieve the value of the master key for this session.
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
2191 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
Adrián Chaves98c57be2020-03-31 16:14:50 +02002192 _openssl_assert(length > 0)
Cory Benfielde62840e2016-11-28 12:17:08 +00002193 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002194 _lib.SSL_SESSION_get_master_key(session, outp, length)
2195 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002196
Paul Kehrerbdb76392017-12-01 04:54:32 +08002197 def export_keying_material(self, label, olen, context=None):
2198 """
2199 Obtain keying material for application use.
2200
Alex Chand072cae2018-02-15 09:57:59 +00002201 :param: label - a disambiguating label string as described in RFC 5705
2202 :param: olen - the length of the exported key material in bytes
2203 :param: context - a per-association context value
2204 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002205 """
2206 outp = _no_zero_allocator("unsigned char[]", olen)
2207 context_buf = _ffi.NULL
2208 context_len = 0
2209 use_context = 0
2210 if context is not None:
2211 context_buf = context
2212 context_len = len(context)
2213 use_context = 1
Alex Gaynor03737182020-07-23 20:40:46 -04002214 success = _lib.SSL_export_keying_material(
2215 self._ssl,
2216 outp,
2217 olen,
2218 label,
2219 len(label),
2220 context_buf,
2221 context_len,
2222 use_context,
2223 )
Paul Kehrerbdb76392017-12-01 04:54:32 +08002224 _openssl_assert(success == 1)
2225 return _ffi.buffer(outp, olen)[:]
2226
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002227 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002228 """
Alex Chand072cae2018-02-15 09:57:59 +00002229 Call the :meth:`shutdown` method of the underlying socket.
2230 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002231
2232 :return: What the socket's shutdown() method returns
2233 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002234 return self._socket.shutdown(*args, **kwargs)
2235
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002236 def get_certificate(self):
2237 """
2238 Retrieve the local certificate (if any)
2239
2240 :return: The local certificate
2241 """
2242 cert = _lib.SSL_get_certificate(self._ssl)
2243 if cert != _ffi.NULL:
2244 _lib.X509_up_ref(cert)
2245 return X509._from_raw_x509_ptr(cert)
2246 return None
2247
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002248 def get_peer_certificate(self):
2249 """
2250 Retrieve the other side's certificate (if any)
2251
2252 :return: The peer's certificate
2253 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002254 cert = _lib.SSL_get_peer_certificate(self._ssl)
2255 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002256 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002257 return None
2258
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002259 def get_peer_cert_chain(self):
2260 """
2261 Retrieve the other side's certificate (if any)
2262
2263 :return: A list of X509 instances giving the peer's certificate chain,
2264 or None if it does not have one.
2265 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002266 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2267 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002268 return None
2269
2270 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002271 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002272 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002273 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002274 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002275 result.append(pycert)
2276 return result
2277
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002278 def want_read(self):
2279 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002280 Checks if more data has to be read from the transport layer to complete
2281 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002282
2283 :return: True iff more data has to be read
2284 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002285 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002286
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002287 def want_write(self):
2288 """
2289 Checks if there is data to write to the transport layer to complete an
2290 operation.
2291
2292 :return: True iff there is data to write
2293 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002294 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002295
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002296 def set_accept_state(self):
2297 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002298 Set the connection to work in server mode. The handshake will be
2299 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002300
2301 :return: None
2302 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002303 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002304
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002305 def set_connect_state(self):
2306 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002307 Set the connection to work in client mode. The handshake will be
2308 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002309
2310 :return: None
2311 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002312 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002313
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002314 def get_session(self):
2315 """
2316 Returns the Session currently used.
2317
Alex Chand072cae2018-02-15 09:57:59 +00002318 :return: An instance of :class:`OpenSSL.SSL.Session` or
2319 :obj:`None` if no session exists.
2320
2321 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002322 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002323 session = _lib.SSL_get1_session(self._ssl)
2324 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002325 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002326
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002327 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002328 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002329 return pysession
2330
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002331 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002332 """
2333 Set the session to be used when the TLS/SSL connection is established.
2334
2335 :param session: A Session instance representing the session to use.
2336 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002337
2338 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002339 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002340 if not isinstance(session, Session):
2341 raise TypeError("session must be a Session instance")
2342
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002343 result = _lib.SSL_set_session(self._ssl, session._session)
Alex Gaynor77debda2020-04-07 13:40:59 -04002344 _openssl_assert(result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002345
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002346 def _get_finished_message(self, function):
2347 """
Alex Chand072cae2018-02-15 09:57:59 +00002348 Helper to implement :meth:`get_finished` and
2349 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002350
Alex Chand072cae2018-02-15 09:57:59 +00002351 :param function: Either :data:`SSL_get_finished`: or
2352 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002353
Alex Chand072cae2018-02-15 09:57:59 +00002354 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002355 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002356 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002357 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002358 # The OpenSSL documentation says nothing about what might happen if the
2359 # count argument given is zero. Specifically, it doesn't say whether
2360 # the output buffer may be NULL in that case or not. Inspection of the
2361 # implementation reveals that it calls memcpy() unconditionally.
2362 # Section 7.1.4, paragraph 1 of the C standard suggests that
2363 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2364 # alone desirable) behavior (though it probably does on just about
2365 # every implementation...)
2366 #
2367 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2368 # one might expect) for the initial call so as to be safe against this
2369 # potentially undefined behavior.
2370 empty = _ffi.new("char[]", 0)
2371 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002372 if size == 0:
2373 # No Finished message so far.
2374 return None
2375
Cory Benfielde62840e2016-11-28 12:17:08 +00002376 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002377 function(self._ssl, buf, size)
2378 return _ffi.buffer(buf, size)[:]
2379
Fedor Brunner5747b932014-03-05 14:22:34 +01002380 def get_finished(self):
2381 """
Alex Chand072cae2018-02-15 09:57:59 +00002382 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002383
Alex Chand072cae2018-02-15 09:57:59 +00002384 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002385 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002386 :rtype: :class:`bytes` or :class:`NoneType`
2387
2388 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002389 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002390 return self._get_finished_message(_lib.SSL_get_finished)
2391
Fedor Brunner5747b932014-03-05 14:22:34 +01002392 def get_peer_finished(self):
2393 """
Alex Chand072cae2018-02-15 09:57:59 +00002394 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002395
Alex Chand072cae2018-02-15 09:57:59 +00002396 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002397 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002398 :rtype: :class:`bytes` or :class:`NoneType`
2399
2400 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002401 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002402 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002403
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002404 def get_cipher_name(self):
2405 """
2406 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002407
Alex Chand072cae2018-02-15 09:57:59 +00002408 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002409 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002410 :rtype: :class:`unicode` or :class:`NoneType`
2411
2412 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002413 """
2414 cipher = _lib.SSL_get_current_cipher(self._ssl)
2415 if cipher == _ffi.NULL:
2416 return None
2417 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002418 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2419 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002420
2421 def get_cipher_bits(self):
2422 """
2423 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002424
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002425 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002426 or :obj:`None` if no connection has been established.
2427 :rtype: :class:`int` or :class:`NoneType`
2428
2429 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002430 """
2431 cipher = _lib.SSL_get_current_cipher(self._ssl)
2432 if cipher == _ffi.NULL:
2433 return None
2434 else:
2435 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2436
2437 def get_cipher_version(self):
2438 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002439 Obtain the protocol version of the currently used cipher.
2440
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002441 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002442 or :obj:`None` if no connection has been established.
2443 :rtype: :class:`unicode` or :class:`NoneType`
2444
2445 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002446 """
2447 cipher = _lib.SSL_get_current_cipher(self._ssl)
2448 if cipher == _ffi.NULL:
2449 return None
2450 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002451 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002452 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002453
Jim Shaverabff1882015-05-27 09:15:55 -04002454 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002455 """
Alex Chand072cae2018-02-15 09:57:59 +00002456 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002457
2458 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002459 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002460 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002461 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002462 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002463 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002464 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002465
Jim Shaver208438c2015-05-28 09:52:38 -04002466 def get_protocol_version(self):
2467 """
Alex Chand072cae2018-02-15 09:57:59 +00002468 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002469
Alex Chand072cae2018-02-15 09:57:59 +00002470 :returns: The TLS version of the current connection. For example,
2471 it will return ``0x769`` for connections made over TLS version 1.
2472 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002473 """
2474 version = _lib.SSL_version(self._ssl)
2475 return version
2476
Cory Benfield10b277f2015-04-13 17:12:42 -04002477 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002478 def get_next_proto_negotiated(self):
2479 """
2480 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002481
2482 :returns: A bytestring of the protocol name. If no protocol has been
2483 negotiated yet, returns an empty string.
2484
2485 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002486 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002487 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002488 data = _ffi.new("unsigned char **")
2489 data_len = _ffi.new("unsigned int *")
2490
2491 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2492
Cory Benfieldcd010f62014-05-15 19:00:27 +01002493 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002494
Cory Benfield7907e332015-04-13 17:18:25 -04002495 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002496 def set_alpn_protos(self, protos):
2497 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002498 Specify the client's ALPN protocol list.
2499
2500 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002501
2502 :param protos: A list of the protocols to be offered to the server.
2503 This list should be a Python list of bytestrings representing the
2504 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2505 """
2506 # Take the list of protocols and join them together, prefixing them
2507 # with their lengths.
Alex Gaynor03737182020-07-23 20:40:46 -04002508 protostr = b"".join(
Cory Benfield12eae892014-06-07 15:42:56 +01002509 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2510 )
2511
2512 # Build a C string from the list. We don't need to save this off
2513 # because OpenSSL immediately copies the data out.
2514 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002515 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002516
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002517 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002518 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002519 """
2520 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002521
2522 :returns: A bytestring of the protocol name. If no protocol has been
2523 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002524 """
Cory Benfield12eae892014-06-07 15:42:56 +01002525 data = _ffi.new("unsigned char **")
2526 data_len = _ffi.new("unsigned int *")
2527
2528 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2529
Cory Benfielde8e9c382015-04-11 17:33:48 -04002530 if not data_len:
Alex Gaynor03737182020-07-23 20:40:46 -04002531 return b""
Cory Benfielde8e9c382015-04-11 17:33:48 -04002532
Cory Benfield12eae892014-06-07 15:42:56 +01002533 return _ffi.buffer(data[0], data_len[0])[:]
2534
Cory Benfield496652a2017-01-24 11:42:56 +00002535 def request_ocsp(self):
2536 """
2537 Called to request that the server sends stapled OCSP data, if
2538 available. If this is not called on the client side then the server
2539 will not send OCSP data. Should be used in conjunction with
2540 :meth:`Context.set_ocsp_client_callback`.
2541 """
2542 rc = _lib.SSL_set_tlsext_status_type(
2543 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2544 )
2545 _openssl_assert(rc == 1)
2546
Cory Benfield12eae892014-06-07 15:42:56 +01002547
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002548# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2549# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002550_lib.SSL_library_init()