blob: f3c9db0adb81a01b9e4bfbec82f65b3941a10e40 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Nicolas Karolak736c6212017-11-26 14:40:28 +010030__all__ = [
31 'OPENSSL_VERSION_NUMBER',
32 'SSLEAY_VERSION',
33 'SSLEAY_CFLAGS',
34 'SSLEAY_PLATFORM',
35 'SSLEAY_DIR',
36 'SSLEAY_BUILT_ON',
37 'SENT_SHUTDOWN',
38 'RECEIVED_SHUTDOWN',
39 'SSLv2_METHOD',
40 'SSLv3_METHOD',
41 'SSLv23_METHOD',
42 'TLSv1_METHOD',
43 'TLSv1_1_METHOD',
44 'TLSv1_2_METHOD',
45 'OP_NO_SSLv2',
46 'OP_NO_SSLv3',
47 'OP_NO_TLSv1',
48 'OP_NO_TLSv1_1',
49 'OP_NO_TLSv1_2',
50 'MODE_RELEASE_BUFFERS',
51 'OP_SINGLE_DH_USE',
52 'OP_SINGLE_ECDH_USE',
53 'OP_EPHEMERAL_RSA',
54 'OP_MICROSOFT_SESS_ID_BUG',
55 'OP_NETSCAPE_CHALLENGE_BUG',
56 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
57 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
58 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
59 'OP_MSIE_SSLV2_RSA_PADDING',
60 'OP_SSLEAY_080_CLIENT_DH_BUG',
61 'OP_TLS_D5_BUG',
62 'OP_TLS_BLOCK_PADDING_BUG',
63 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
64 'OP_CIPHER_SERVER_PREFERENCE',
65 'OP_TLS_ROLLBACK_BUG',
66 'OP_PKCS1_CHECK_1',
67 'OP_PKCS1_CHECK_2',
68 'OP_NETSCAPE_CA_DN_BUG',
69 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
70 'OP_NO_COMPRESSION',
71 'OP_NO_QUERY_MTU',
72 'OP_COOKIE_EXCHANGE',
73 'OP_NO_TICKET',
74 'OP_ALL',
75 'VERIFY_PEER',
76 'VERIFY_FAIL_IF_NO_PEER_CERT',
77 'VERIFY_CLIENT_ONCE',
78 'VERIFY_NONE',
79 'SESS_CACHE_OFF',
80 'SESS_CACHE_CLIENT',
81 'SESS_CACHE_SERVER',
82 'SESS_CACHE_BOTH',
83 'SESS_CACHE_NO_AUTO_CLEAR',
84 'SESS_CACHE_NO_INTERNAL_LOOKUP',
85 'SESS_CACHE_NO_INTERNAL_STORE',
86 'SESS_CACHE_NO_INTERNAL',
87 'SSL_ST_CONNECT',
88 'SSL_ST_ACCEPT',
89 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010090 'SSL_CB_LOOP',
91 'SSL_CB_EXIT',
92 'SSL_CB_READ',
93 'SSL_CB_WRITE',
94 'SSL_CB_ALERT',
95 'SSL_CB_READ_ALERT',
96 'SSL_CB_WRITE_ALERT',
97 'SSL_CB_ACCEPT_LOOP',
98 'SSL_CB_ACCEPT_EXIT',
99 'SSL_CB_CONNECT_LOOP',
100 'SSL_CB_CONNECT_EXIT',
101 'SSL_CB_HANDSHAKE_START',
102 'SSL_CB_HANDSHAKE_DONE',
103 'Error',
104 'WantReadError',
105 'WantWriteError',
106 'WantX509LookupError',
107 'ZeroReturnError',
108 'SysCallError',
109 'SSLeay_version',
110 'Session',
111 'Context',
112 'Connection'
113]
114
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500115try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200116 _buffer = buffer
117except NameError:
118 class _buffer(object):
119 pass
120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
122SSLEAY_VERSION = _lib.SSLEAY_VERSION
123SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
124SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
125SSLEAY_DIR = _lib.SSLEAY_DIR
126SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800127
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
129RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800130
131SSLv2_METHOD = 1
132SSLv3_METHOD = 2
133SSLv23_METHOD = 3
134TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500135TLSv1_1_METHOD = 5
136TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500138OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
139OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
140OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700141OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
142OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800143
Alex Gaynorbf012872016-06-04 13:18:39 -0700144MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800145
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500146OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900147OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500148OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
149OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
150OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400151OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
152 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
153)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500154OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
155OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400156OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500157OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
158OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
159OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
160OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
161OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
162OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
163OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
164OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
165OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400166OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
167 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
168)
Alex Gaynorbf012872016-06-04 13:18:39 -0700169OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800170
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500171OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
172OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400173OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800174
Alex Gaynorc4889812015-09-04 08:43:17 -0400175OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500177VERIFY_PEER = _lib.SSL_VERIFY_PEER
178VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
179VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
180VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800181
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500182SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
183SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
184SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
185SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
186SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
187SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
188SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
189SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800190
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500191SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
192SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
193SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400194if _lib.Cryptography_HAS_SSL_ST:
195 SSL_ST_INIT = _lib.SSL_ST_INIT
196 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
197 SSL_ST_OK = _lib.SSL_ST_OK
198 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100199 __all__.extend([
200 'SSL_ST_INIT',
201 'SSL_ST_BEFORE',
202 'SSL_ST_OK',
203 'SSL_ST_RENEGOTIATE',
204 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800205
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500206SSL_CB_LOOP = _lib.SSL_CB_LOOP
207SSL_CB_EXIT = _lib.SSL_CB_EXIT
208SSL_CB_READ = _lib.SSL_CB_READ
209SSL_CB_WRITE = _lib.SSL_CB_WRITE
210SSL_CB_ALERT = _lib.SSL_CB_ALERT
211SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
212SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
213SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
214SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
215SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
216SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
217SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
218SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800219
Paul Kehrer55fb3412017-06-29 18:44:08 -0500220# Taken from https://golang.org/src/crypto/x509/root_linux.go
221_CERTIFICATE_FILE_LOCATIONS = [
222 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
223 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
224 "/etc/ssl/ca-bundle.pem", # OpenSUSE
225 "/etc/pki/tls/cacert.pem", # OpenELEC
226 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
227]
228
229_CERTIFICATE_PATH_LOCATIONS = [
230 "/etc/ssl/certs", # SLES10/SLES11
231]
232
Paul Kehrera92a1a72017-07-19 15:53:23 +0200233# These values are compared to output from cffi's ffi.string so they must be
234# byte strings.
235_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
236_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500237
Alex Gaynor83284952015-09-05 10:43:30 -0400238
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500239class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500240 """
241 An error occurred in an `OpenSSL.SSL` API.
242 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243
244
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500245_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100246_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247
248
249class WantReadError(Error):
250 pass
251
252
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500253class WantWriteError(Error):
254 pass
255
256
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500257class WantX509LookupError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class ZeroReturnError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class SysCallError(Error):
266 pass
267
268
Cory Benfield0ea76e72015-03-22 09:05:28 +0000269class _CallbackExceptionHelper(object):
270 """
271 A base class for wrapper classes that allow for intelligent exception
272 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500273
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400274 :ivar list _problems: Any exceptions that occurred while executing in a
275 context where they could not be raised in the normal way. Typically
276 this is because OpenSSL has called into some Python code and requires a
277 return value. The exceptions are saved to be raised later when it is
278 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000279 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400280
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400281 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800282 self._problems = []
283
Cory Benfield0ea76e72015-03-22 09:05:28 +0000284 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400285 """
286 Raise an exception from the OpenSSL error queue or that was previously
287 captured whe running a callback.
288 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000289 if self._problems:
290 try:
291 _raise_current_error()
292 except Error:
293 pass
294 raise self._problems.pop(0)
295
296
297class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400298 """
299 Wrap a callback such that it can be used as a certificate verification
300 callback.
301 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400302
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800303 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400304 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800305
306 @wraps(callback)
307 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800308 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
309 _lib.X509_up_ref(x509)
310 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500311 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
312 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800313
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400314 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
315 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
316 connection = Connection._reverse_mapping[ssl]
317
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800318 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400319 result = callback(
320 connection, cert, error_number, error_depth, ok
321 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800322 except Exception as e:
323 self._problems.append(e)
324 return 0
325 else:
326 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500327 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800328 return 1
329 else:
330 return 0
331
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500332 self.callback = _ffi.callback(
333 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800334
335
Cory Benfield0ea76e72015-03-22 09:05:28 +0000336class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400337 """
338 Wrap a callback such that it can be used as an NPN advertisement callback.
339 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400340
Cory Benfield0ea76e72015-03-22 09:05:28 +0000341 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400342 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800343
Cory Benfield0ea76e72015-03-22 09:05:28 +0000344 @wraps(callback)
345 def wrapper(ssl, out, outlen, arg):
346 try:
347 conn = Connection._reverse_mapping[ssl]
348 protos = callback(conn)
349
350 # Join the protocols into a Python bytestring, length-prefixing
351 # each element.
352 protostr = b''.join(
353 chain.from_iterable((int2byte(len(p)), p) for p in protos)
354 )
355
356 # Save our callback arguments on the connection object. This is
357 # done to make sure that they don't get freed before OpenSSL
358 # uses them. Then, return them appropriately in the output
359 # parameters.
360 conn._npn_advertise_callback_args = [
361 _ffi.new("unsigned int *", len(protostr)),
362 _ffi.new("unsigned char[]", protostr),
363 ]
364 outlen[0] = conn._npn_advertise_callback_args[0][0]
365 out[0] = conn._npn_advertise_callback_args[1]
366 return 0
367 except Exception as e:
368 self._problems.append(e)
369 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
370
371 self.callback = _ffi.callback(
372 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
373 wrapper
374 )
375
376
377class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400378 """
379 Wrap a callback such that it can be used as an NPN selection callback.
380 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400381
Cory Benfield0ea76e72015-03-22 09:05:28 +0000382 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400383 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000384
385 @wraps(callback)
386 def wrapper(ssl, out, outlen, in_, inlen, arg):
387 try:
388 conn = Connection._reverse_mapping[ssl]
389
390 # The string passed to us is actually made up of multiple
391 # length-prefixed bytestrings. We need to split that into a
392 # list.
393 instr = _ffi.buffer(in_, inlen)[:]
394 protolist = []
395 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500396 length = indexbytes(instr, 0)
397 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000398 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500399 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000400
401 # Call the callback
402 outstr = callback(conn, protolist)
403
404 # Save our callback arguments on the connection object. This is
405 # done to make sure that they don't get freed before OpenSSL
406 # uses them. Then, return them appropriately in the output
407 # parameters.
408 conn._npn_select_callback_args = [
409 _ffi.new("unsigned char *", len(outstr)),
410 _ffi.new("unsigned char[]", outstr),
411 ]
412 outlen[0] = conn._npn_select_callback_args[0][0]
413 out[0] = conn._npn_select_callback_args[1]
414 return 0
415 except Exception as e:
416 self._problems.append(e)
417 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
418
419 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400420 ("int (*)(SSL *, unsigned char **, unsigned char *, "
421 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000422 wrapper
423 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800424
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800425
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400426class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400427 """
428 Wrap a callback such that it can be used as an ALPN selection callback.
429 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400430
Cory Benfieldf1177e72015-04-12 09:11:49 -0400431 def __init__(self, callback):
432 _CallbackExceptionHelper.__init__(self)
433
434 @wraps(callback)
435 def wrapper(ssl, out, outlen, in_, inlen, arg):
436 try:
437 conn = Connection._reverse_mapping[ssl]
438
439 # The string passed to us is made up of multiple
440 # length-prefixed bytestrings. We need to split that into a
441 # list.
442 instr = _ffi.buffer(in_, inlen)[:]
443 protolist = []
444 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400445 encoded_len = indexbytes(instr, 0)
446 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400447 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400448 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400449
450 # Call the callback
451 outstr = callback(conn, protolist)
452
453 if not isinstance(outstr, _binary_type):
454 raise TypeError("ALPN callback must return a bytestring.")
455
456 # Save our callback arguments on the connection object to make
457 # sure that they don't get freed before OpenSSL can use them.
458 # Then, return them in the appropriate output parameters.
459 conn._alpn_select_callback_args = [
460 _ffi.new("unsigned char *", len(outstr)),
461 _ffi.new("unsigned char[]", outstr),
462 ]
463 outlen[0] = conn._alpn_select_callback_args[0][0]
464 out[0] = conn._alpn_select_callback_args[1]
465 return 0
466 except Exception as e:
467 self._problems.append(e)
468 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
469
470 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400471 ("int (*)(SSL *, unsigned char **, unsigned char *, "
472 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400473 wrapper
474 )
475
476
Cory Benfield496652a2017-01-24 11:42:56 +0000477class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
478 """
479 Wrap a callback such that it can be used as an OCSP callback for the server
480 side.
481
482 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
483 ways. For servers, that callback is expected to retrieve some OCSP data and
484 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
485 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
486 is expected to check the OCSP data, and returns a negative value on error,
487 0 if the response is not acceptable, or positive if it is. These are
488 mutually exclusive return code behaviours, and they mean that we need two
489 helpers so that we always return an appropriate error code if the user's
490 code throws an exception.
491
492 Given that we have to have two helpers anyway, these helpers are a bit more
493 helpery than most: specifically, they hide a few more of the OpenSSL
494 functions so that the user has an easier time writing these callbacks.
495
496 This helper implements the server side.
497 """
498
499 def __init__(self, callback):
500 _CallbackExceptionHelper.__init__(self)
501
502 @wraps(callback)
503 def wrapper(ssl, cdata):
504 try:
505 conn = Connection._reverse_mapping[ssl]
506
507 # Extract the data if any was provided.
508 if cdata != _ffi.NULL:
509 data = _ffi.from_handle(cdata)
510 else:
511 data = None
512
513 # Call the callback.
514 ocsp_data = callback(conn, data)
515
516 if not isinstance(ocsp_data, _binary_type):
517 raise TypeError("OCSP callback must return a bytestring.")
518
519 # If the OCSP data was provided, we will pass it to OpenSSL.
520 # However, we have an early exit here: if no OCSP data was
521 # provided we will just exit out and tell OpenSSL that there
522 # is nothing to do.
523 if not ocsp_data:
524 return 3 # SSL_TLSEXT_ERR_NOACK
525
526 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
527 # private copy of this data, so we need to keep it alive, but
528 # it *does* want to free it itself if it gets replaced. This
529 # somewhat bonkers behaviour means we need to use
530 # OPENSSL_malloc directly, which is a pain in the butt to work
531 # with. It's ok for us to "leak" the memory here because
532 # OpenSSL now owns it and will free it.
533 ocsp_data_length = len(ocsp_data)
534 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
535 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
536
537 _lib.SSL_set_tlsext_status_ocsp_resp(
538 ssl, data_ptr, ocsp_data_length
539 )
540
541 return 0
542 except Exception as e:
543 self._problems.append(e)
544 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
545
546 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
547
548
549class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
550 """
551 Wrap a callback such that it can be used as an OCSP callback for the client
552 side.
553
554 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
555 ways. For servers, that callback is expected to retrieve some OCSP data and
556 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
557 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
558 is expected to check the OCSP data, and returns a negative value on error,
559 0 if the response is not acceptable, or positive if it is. These are
560 mutually exclusive return code behaviours, and they mean that we need two
561 helpers so that we always return an appropriate error code if the user's
562 code throws an exception.
563
564 Given that we have to have two helpers anyway, these helpers are a bit more
565 helpery than most: specifically, they hide a few more of the OpenSSL
566 functions so that the user has an easier time writing these callbacks.
567
568 This helper implements the client side.
569 """
570
571 def __init__(self, callback):
572 _CallbackExceptionHelper.__init__(self)
573
574 @wraps(callback)
575 def wrapper(ssl, cdata):
576 try:
577 conn = Connection._reverse_mapping[ssl]
578
579 # Extract the data if any was provided.
580 if cdata != _ffi.NULL:
581 data = _ffi.from_handle(cdata)
582 else:
583 data = None
584
585 # Get the OCSP data.
586 ocsp_ptr = _ffi.new("unsigned char **")
587 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
588 if ocsp_len < 0:
589 # No OCSP data.
590 ocsp_data = b''
591 else:
592 # Copy the OCSP data, then pass it to the callback.
593 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
594
595 valid = callback(conn, ocsp_data, data)
596
597 # Return 1 on success or 0 on error.
598 return int(bool(valid))
599
600 except Exception as e:
601 self._problems.append(e)
602 # Return negative value if an exception is hit.
603 return -1
604
605 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
606
607
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800608def _asFileDescriptor(obj):
609 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800610 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800611 meth = getattr(obj, "fileno", None)
612 if meth is not None:
613 obj = meth()
614
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800615 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800616 fd = obj
617
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800618 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619 raise TypeError("argument must be an int, or have a fileno() method.")
620 elif fd < 0:
621 raise ValueError(
622 "file descriptor cannot be a negative integer (%i)" % (fd,))
623
624 return fd
625
626
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800627def SSLeay_version(type):
628 """
629 Return a string describing the version of OpenSSL in use.
630
Alex Chand072cae2018-02-15 09:57:59 +0000631 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800632 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500633 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800634
635
Cory Benfieldef404df2016-03-29 15:32:48 +0100636def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400637 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100638 Builds a decorator that ensures that functions that rely on OpenSSL
639 functions that are not present in this build raise NotImplementedError,
640 rather than AttributeError coming out of cryptography.
641
642 :param flag: A cryptography flag that guards the functions, e.g.
643 ``Cryptography_HAS_NEXTPROTONEG``.
644 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400645 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100646 def _requires_decorator(func):
647 if not flag:
648 @wraps(func)
649 def explode(*args, **kwargs):
650 raise NotImplementedError(error)
651 return explode
652 else:
653 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400654
Cory Benfieldef404df2016-03-29 15:32:48 +0100655 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400656
657
Cory Benfieldef404df2016-03-29 15:32:48 +0100658_requires_npn = _make_requires(
659 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
660)
Cory Benfield7907e332015-04-13 17:18:25 -0400661
662
Cory Benfieldef404df2016-03-29 15:32:48 +0100663_requires_alpn = _make_requires(
664 _lib.Cryptography_HAS_ALPN, "ALPN not available"
665)
Cory Benfielde6f35882016-03-29 11:21:04 +0100666
Cory Benfielde6f35882016-03-29 11:21:04 +0100667
Cory Benfieldef404df2016-03-29 15:32:48 +0100668_requires_sni = _make_requires(
669 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
670)
Cory Benfielde6f35882016-03-29 11:21:04 +0100671
672
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800673class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000674 """
675 A class representing an SSL session. A session defines certain connection
676 parameters which may be re-used to speed up the setup of subsequent
677 connections.
678
679 .. versionadded:: 0.14
680 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800681 pass
682
683
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684class Context(object):
685 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100686 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400687 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000688
689 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
690 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691 """
692 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800693 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500694 SSLv3_METHOD: "SSLv3_method",
695 SSLv23_METHOD: "SSLv23_method",
696 TLSv1_METHOD: "TLSv1_method",
697 TLSv1_1_METHOD: "TLSv1_1_method",
698 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400699 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500700 _methods = dict(
701 (identifier, getattr(_lib, name))
702 for (identifier, name) in _methods.items()
703 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704
705 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500706 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707 raise TypeError("method must be an integer")
708
709 try:
710 method_func = self._methods[method]
711 except KeyError:
712 raise ValueError("No such protocol")
713
714 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700715 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700718 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500719 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800720
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600721 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
722 # will be auto-selected. This function was added in 1.0.2 and made a
723 # noop in 1.1.0+ (where it is set automatically).
724 try:
725 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
726 _openssl_assert(res == 1)
727 except AttributeError:
728 pass
729
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800731 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800732 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800733 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800734 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 self._verify_callback = None
736 self._info_callback = None
737 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000739 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100740 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000741 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100742 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400743 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100744 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000745 self._ocsp_helper = None
746 self._ocsp_callback = None
747 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500749 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800751 def load_verify_locations(self, cafile, capath=None):
752 """
753 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000754 chain. Note that the certificates have to be in PEM format.
755
756 If capath is passed, it must be a directory prepared using the
757 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
758 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800759
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400760 :param cafile: In which file we can find the certificates (``bytes`` or
761 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800762 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400763 (``bytes`` or ``unicode``).
764
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800765 :return: None
766 """
767 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500768 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400769 else:
770 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800771
772 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500773 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400774 else:
775 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776
Alex Gaynor62da94d2015-09-05 14:37:34 -0400777 load_result = _lib.SSL_CTX_load_verify_locations(
778 self._context, cafile, capath
779 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500781 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def _wrap_callback(self, callback):
784 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800785 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 return callback(size, verify, self._passphrase_userdata)
787 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800788 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790 def set_passwd_cb(self, callback, userdata=None):
791 """
Alex Chand072cae2018-02-15 09:57:59 +0000792 Set the passphrase callback. This function will be called
793 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794
Alex Chand072cae2018-02-15 09:57:59 +0000795 :param callback: The Python callback to use. This must accept three
796 positional arguments. First, an integer giving the maximum length
797 of the passphrase it may return. If the returned passphrase is
798 longer than this, it will be truncated. Second, a boolean value
799 which will be true if the user should be prompted for the
800 passphrase twice and the callback should verify that the two values
801 supplied are equal. Third, the value given as the *userdata*
802 parameter to :meth:`set_passwd_cb`. The *callback* must return
803 a byte string. If an error occurs, *callback* should return a false
804 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800805 :param userdata: (optional) A Python object which will be given as
806 argument to the callback
807 :return: None
808 """
809 if not callable(callback):
810 raise TypeError("callback must be callable")
811
812 self._passphrase_helper = self._wrap_callback(callback)
813 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500814 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815 self._context, self._passphrase_callback)
816 self._passphrase_userdata = userdata
817
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 def set_default_verify_paths(self):
819 """
Alex Chand072cae2018-02-15 09:57:59 +0000820 Specify that the platform provided CA certificates are to be used for
821 verification purposes. This method has some caveats related to the
822 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
823
824 * macOS will only load certificates using this method if the user has
825 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
826 in the default location.
827 * Windows will not work.
828 * manylinux1 cryptography wheels will work on most common Linux
829 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
830 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800831
832 :return: None
833 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500834 # SSL_CTX_set_default_verify_paths will attempt to load certs from
835 # both a cafile and capath that are set at compile time. However,
836 # it will first check environment variables and, if present, load
837 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500838 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400839 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500840 # After attempting to set default_verify_paths we need to know whether
841 # to go down the fallback path.
842 # First we'll check to see if any env vars have been set. If so,
843 # we won't try to do anything else because the user has set the path
844 # themselves.
845 dir_env_var = _ffi.string(
846 _lib.X509_get_default_cert_dir_env()
847 ).decode("ascii")
848 file_env_var = _ffi.string(
849 _lib.X509_get_default_cert_file_env()
850 ).decode("ascii")
851 if not self._check_env_vars_set(dir_env_var, file_env_var):
852 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
853 default_file = _ffi.string(_lib.X509_get_default_cert_file())
854 # Now we check to see if the default_dir and default_file are set
855 # to the exact values we use in our manylinux1 builds. If they are
856 # then we know to load the fallbacks
857 if (
858 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
859 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
860 ):
861 # This is manylinux1, let's load our fallback paths
862 self._fallback_default_verify_paths(
863 _CERTIFICATE_FILE_LOCATIONS,
864 _CERTIFICATE_PATH_LOCATIONS
865 )
866
867 def _check_env_vars_set(self, dir_env_var, file_env_var):
868 """
869 Check to see if the default cert dir/file environment vars are present.
870
871 :return: bool
872 """
873 return (
874 os.environ.get(file_env_var) is not None or
875 os.environ.get(dir_env_var) is not None
876 )
877
878 def _fallback_default_verify_paths(self, file_path, dir_path):
879 """
880 Default verify paths are based on the compiled version of OpenSSL.
881 However, when pyca/cryptography is compiled as a manylinux1 wheel
882 that compiled location can potentially be wrong. So, like Go, we
883 will try a predefined set of paths and attempt to load roots
884 from there.
885
886 :return: None
887 """
888 for cafile in file_path:
889 if os.path.isfile(cafile):
890 self.load_verify_locations(cafile)
891 break
892
893 for capath in dir_path:
894 if os.path.isdir(capath):
895 self.load_verify_locations(None, capath)
896 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800897
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 def use_certificate_chain_file(self, certfile):
899 """
Alex Chand072cae2018-02-15 09:57:59 +0000900 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800901
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400902 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000903 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400904
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905 :return: None
906 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400907 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800908
Alex Gaynor62da94d2015-09-05 14:37:34 -0400909 result = _lib.SSL_CTX_use_certificate_chain_file(
910 self._context, certfile
911 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800912 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500913 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800914
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800915 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800916 """
917 Load a certificate from a file
918
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400919 :param certfile: The name of the certificate file (``bytes`` or
920 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000921 :param filetype: (optional) The encoding of the file, which is either
922 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
923 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400924
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925 :return: None
926 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400927 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500928 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800929 raise TypeError("filetype must be an integer")
930
Alex Gaynor62da94d2015-09-05 14:37:34 -0400931 use_result = _lib.SSL_CTX_use_certificate_file(
932 self._context, certfile, filetype
933 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800934 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500935 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800936
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800937 def use_certificate(self, cert):
938 """
939 Load a certificate from a X509 object
940
941 :param cert: The X509 object
942 :return: None
943 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800944 if not isinstance(cert, X509):
945 raise TypeError("cert must be an X509 instance")
946
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500947 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800948 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500949 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800950
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951 def add_extra_chain_cert(self, certobj):
952 """
953 Add certificate to chain
954
955 :param certobj: The X509 certificate object to add to the chain
956 :return: None
957 """
958 if not isinstance(certobj, X509):
959 raise TypeError("certobj must be an X509 instance")
960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 copy = _lib.X509_dup(certobj._x509)
962 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800963 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500964 # TODO: This is untested.
965 _lib.X509_free(copy)
966 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800968 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500969 if self._passphrase_helper is not None:
970 self._passphrase_helper.raise_if_problem(Error)
971
972 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800973
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400974 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975 """
976 Load a private key from a file
977
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400978 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000979 :param filetype: (optional) The encoding of the file, which is either
980 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
981 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400982
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983 :return: None
984 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400985 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400987 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800988 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500989 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990 raise TypeError("filetype must be an integer")
991
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500992 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800993 self._context, keyfile, filetype)
994 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800995 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997 def use_privatekey(self, pkey):
998 """
999 Load a private key from a PKey object
1000
1001 :param pkey: The PKey object
1002 :return: None
1003 """
1004 if not isinstance(pkey, PKey):
1005 raise TypeError("pkey must be a PKey instance")
1006
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001007 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001008 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001009 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011 def check_privatekey(self):
1012 """
Alex Chand072cae2018-02-15 09:57:59 +00001013 Check if the private key (loaded with :meth:`use_privatekey`) matches
1014 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015
Alex Chand072cae2018-02-15 09:57:59 +00001016 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001018 if not _lib.SSL_CTX_check_private_key(self._context):
1019 _raise_current_error()
1020
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021 def load_client_ca(self, cafile):
1022 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001023 Load the trusted certificates that will be sent to the client. Does
1024 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001025 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001027 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028 :return: None
1029 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001030 ca_list = _lib.SSL_load_client_CA_file(
1031 _text_to_bytes_and_warn("cafile", cafile)
1032 )
1033 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001034 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035
1036 def set_session_id(self, buf):
1037 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001038 Set the session id to *buf* within which a session can be reused for
1039 this Context object. This is needed when doing session resumption,
1040 because there is no way for a stored session to know which Context
1041 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001043 :param bytes buf: The session id.
1044
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045 :returns: None
1046 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001047 buf = _text_to_bytes_and_warn("buf", buf)
1048 _openssl_assert(
1049 _lib.SSL_CTX_set_session_id_context(
1050 self._context,
1051 buf,
1052 len(buf),
1053 ) == 1
1054 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055
1056 def set_session_cache_mode(self, mode):
1057 """
Alex Chand072cae2018-02-15 09:57:59 +00001058 Set the behavior of the session cache used by all connections using
1059 this Context. The previously set mode is returned. See
1060 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
1062 :param mode: One or more of the SESS_CACHE_* flags (combine using
1063 bitwise or)
1064 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001065
1066 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001068 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001069 raise TypeError("mode must be an integer")
1070
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001071 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 def get_session_cache_mode(self):
1074 """
Alex Chand072cae2018-02-15 09:57:59 +00001075 Get the current session cache mode.
1076
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001077 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001078
1079 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083 def set_verify(self, mode, callback):
1084 """
Alex Chand072cae2018-02-15 09:57:59 +00001085 et the verification flags for this Context object to *mode* and specify
1086 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
Alex Chand072cae2018-02-15 09:57:59 +00001088 :param mode: The verify mode, this should be one of
1089 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1090 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1091 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1092 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1093 :param callback: The Python callback to use. This should take five
1094 arguments: A Connection object, an X509 object, and three integer
1095 variables, which are in turn potential error number, error depth
1096 and return code. *callback* should return True if verification
1097 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098 :return: None
1099
1100 See SSL_CTX_set_verify(3SSL) for further details.
1101 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001102 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001103 raise TypeError("mode must be an integer")
1104
1105 if not callable(callback):
1106 raise TypeError("callback must be callable")
1107
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001108 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001109 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001110 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001112 def set_verify_depth(self, depth):
1113 """
Alex Chand072cae2018-02-15 09:57:59 +00001114 Set the maximum depth for the certificate chain verification that shall
1115 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001116
1117 :param depth: An integer specifying the verify depth
1118 :return: None
1119 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001120 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001121 raise TypeError("depth must be an integer")
1122
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001123 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001125 def get_verify_mode(self):
1126 """
Alex Chand072cae2018-02-15 09:57:59 +00001127 Retrieve the Context object's verify mode, as set by
1128 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001129
1130 :return: The verify mode
1131 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001132 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001133
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001134 def get_verify_depth(self):
1135 """
Alex Chand072cae2018-02-15 09:57:59 +00001136 Retrieve the Context object's verify depth, as set by
1137 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138
1139 :return: The verify depth
1140 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143 def load_tmp_dh(self, dhfile):
1144 """
1145 Load parameters for Ephemeral Diffie-Hellman
1146
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001147 :param dhfile: The file to load EDH parameters from (``bytes`` or
1148 ``unicode``).
1149
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001150 :return: None
1151 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001152 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001153
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001154 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001156 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001158
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1160 dh = _ffi.gc(dh, _lib.DH_free)
1161 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001162
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001163 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001164 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001165 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001166
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001167 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001168 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1169 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001170
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001171 :return: None
1172 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001173 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001174
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001175 def set_cipher_list(self, cipher_list):
1176 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001177 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001178
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001179 See the OpenSSL manual for more information (e.g.
1180 :manpage:`ciphers(1)`).
1181
1182 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183 :return: None
1184 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001185 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001186
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001187 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001188 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001189
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001190 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001191 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001192 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001193
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001194 def set_client_ca_list(self, certificate_authorities):
1195 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001196 Set the list of preferred client certificate signers for this server
1197 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198
Alex Gaynor62da94d2015-09-05 14:37:34 -04001199 This list of certificate authorities will be sent to the client when
1200 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201
1202 :param certificate_authorities: a sequence of X509Names.
1203 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001204
1205 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001206 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001207 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001208 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001209
1210 try:
1211 for ca_name in certificate_authorities:
1212 if not isinstance(ca_name, X509Name):
1213 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001214 "client CAs must be X509Name objects, not %s "
1215 "objects" % (
1216 type(ca_name).__name__,
1217 )
1218 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001219 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001220 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001221 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001222 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001223 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001224 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001225 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001226 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001227 raise
1228
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001229 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001230
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001231 def add_client_ca(self, certificate_authority):
1232 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001233 Add the CA certificate to the list of preferred signers for this
1234 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001235
1236 The list of certificate authorities will be sent to the client when the
1237 server requests a client certificate.
1238
1239 :param certificate_authority: certificate authority's X509 certificate.
1240 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001241
1242 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001243 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001244 if not isinstance(certificate_authority, X509):
1245 raise TypeError("certificate_authority must be an X509 instance")
1246
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001247 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001248 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001249 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001250
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001251 def set_timeout(self, timeout):
1252 """
Alex Chand072cae2018-02-15 09:57:59 +00001253 Set the timeout for newly created sessions for this Context object to
1254 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1255 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001256
Alex Chand072cae2018-02-15 09:57:59 +00001257 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001258 :return: The previous session timeout
1259 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001260 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001261 raise TypeError("timeout must be an integer")
1262
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001263 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001265 def get_timeout(self):
1266 """
Alex Chand072cae2018-02-15 09:57:59 +00001267 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1268 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001269
1270 :return: The session timeout
1271 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001272 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001274 def set_info_callback(self, callback):
1275 """
Alex Chand072cae2018-02-15 09:57:59 +00001276 Set the information callback to *callback*. This function will be
1277 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001278
Alex Chand072cae2018-02-15 09:57:59 +00001279 :param callback: The Python callback to use. This should take three
1280 arguments: a Connection object and two integers. The first integer
1281 specifies where in the SSL handshake the function was called, and
1282 the other the return code from a (possibly failed) internal
1283 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001284 :return: None
1285 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001286 @wraps(callback)
1287 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001288 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001289 self._info_callback = _ffi.callback(
1290 "void (*)(const SSL *, int, int)", wrapper)
1291 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001292
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001293 def get_app_data(self):
1294 """
Alex Chand072cae2018-02-15 09:57:59 +00001295 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001296
1297 :return: The application data
1298 """
1299 return self._app_data
1300
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001301 def set_app_data(self, data):
1302 """
1303 Set the application data (will be returned from get_app_data())
1304
1305 :param data: Any Python object
1306 :return: None
1307 """
1308 self._app_data = data
1309
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001310 def get_cert_store(self):
1311 """
Alex Chand072cae2018-02-15 09:57:59 +00001312 Get the certificate store for the context. This can be used to add
1313 "trusted" certificates without using the
1314 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001315
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001316 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 store = _lib.SSL_CTX_get_cert_store(self._context)
1319 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001320 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001321 return None
1322
1323 pystore = X509Store.__new__(X509Store)
1324 pystore._store = store
1325 return pystore
1326
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001327 def set_options(self, options):
1328 """
1329 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001330 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001331
1332 :param options: The options to add.
1333 :return: The new option bitmask.
1334 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001335 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001336 raise TypeError("options must be an integer")
1337
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001338 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001339
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001340 def set_mode(self, mode):
1341 """
Alex Chand072cae2018-02-15 09:57:59 +00001342 Add modes via bitmask. Modes set before are not cleared! This method
1343 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001344
1345 :param mode: The mode to add.
1346 :return: The new mode bitmask.
1347 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001348 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001349 raise TypeError("mode must be an integer")
1350
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001352
Cory Benfielde6f35882016-03-29 11:21:04 +01001353 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001354 def set_tlsext_servername_callback(self, callback):
1355 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001356 Specify a callback function to be called when clients specify a server
1357 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358
1359 :param callback: The callback function. It will be invoked with one
1360 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001361
1362 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001363 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001364 @wraps(callback)
1365 def wrapper(ssl, alert, arg):
1366 callback(Connection._reverse_mapping[ssl])
1367 return 0
1368
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001369 self._tlsext_servername_callback = _ffi.callback(
1370 "int (*)(const SSL *, int *, void *)", wrapper)
1371 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001372 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001373
Cory Benfield10b277f2015-04-13 17:12:42 -04001374 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001375 def set_npn_advertise_callback(self, callback):
1376 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001377 Specify a callback function that will be called when offering `Next
1378 Protocol Negotiation
1379 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001380
1381 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001382 argument, the :class:`Connection` instance. It should return a
1383 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001384 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001385
1386 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001387 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001388 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1389 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001390 _lib.SSL_CTX_set_next_protos_advertised_cb(
1391 self._context, self._npn_advertise_callback, _ffi.NULL)
1392
Cory Benfield10b277f2015-04-13 17:12:42 -04001393 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001394 def set_npn_select_callback(self, callback):
1395 """
1396 Specify a callback function that will be called when a server offers
1397 Next Protocol Negotiation options.
1398
1399 :param callback: The callback function. It will be invoked with two
1400 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001401 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1402 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001403
1404 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001405 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001406 self._npn_select_helper = _NpnSelectHelper(callback)
1407 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001408 _lib.SSL_CTX_set_next_proto_select_cb(
1409 self._context, self._npn_select_callback, _ffi.NULL)
1410
Cory Benfield7907e332015-04-13 17:18:25 -04001411 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001412 def set_alpn_protos(self, protos):
1413 """
Alex Chand072cae2018-02-15 09:57:59 +00001414 Specify the protocols that the client is prepared to speak after the
1415 TLS connection has been negotiated using Application Layer Protocol
1416 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001417
1418 :param protos: A list of the protocols to be offered to the server.
1419 This list should be a Python list of bytestrings representing the
1420 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1421 """
1422 # Take the list of protocols and join them together, prefixing them
1423 # with their lengths.
1424 protostr = b''.join(
1425 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1426 )
1427
1428 # Build a C string from the list. We don't need to save this off
1429 # because OpenSSL immediately copies the data out.
1430 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001431 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001432
Cory Benfield7907e332015-04-13 17:18:25 -04001433 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001434 def set_alpn_select_callback(self, callback):
1435 """
Alex Chand072cae2018-02-15 09:57:59 +00001436 Specify a callback function that will be called on the server when a
1437 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001438
1439 :param callback: The callback function. It will be invoked with two
1440 arguments: the Connection, and a list of offered protocols as
1441 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001442 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001443 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001444 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001445 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001446 _lib.SSL_CTX_set_alpn_select_cb(
1447 self._context, self._alpn_select_callback, _ffi.NULL)
1448
Cory Benfield496652a2017-01-24 11:42:56 +00001449 def _set_ocsp_callback(self, helper, data):
1450 """
1451 This internal helper does the common work for
1452 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1453 almost all of it.
1454 """
1455 self._ocsp_helper = helper
1456 self._ocsp_callback = helper.callback
1457 if data is None:
1458 self._ocsp_data = _ffi.NULL
1459 else:
1460 self._ocsp_data = _ffi.new_handle(data)
1461
1462 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1463 self._context, self._ocsp_callback
1464 )
1465 _openssl_assert(rc == 1)
1466 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1467 _openssl_assert(rc == 1)
1468
1469 def set_ocsp_server_callback(self, callback, data=None):
1470 """
1471 Set a callback to provide OCSP data to be stapled to the TLS handshake
1472 on the server side.
1473
1474 :param callback: The callback function. It will be invoked with two
1475 arguments: the Connection, and the optional arbitrary data you have
1476 provided. The callback must return a bytestring that contains the
1477 OCSP data to staple to the handshake. If no OCSP data is available
1478 for this connection, return the empty bytestring.
1479 :param data: Some opaque data that will be passed into the callback
1480 function when called. This can be used to avoid needing to do
1481 complex data lookups or to keep track of what context is being
1482 used. This parameter is optional.
1483 """
1484 helper = _OCSPServerCallbackHelper(callback)
1485 self._set_ocsp_callback(helper, data)
1486
1487 def set_ocsp_client_callback(self, callback, data=None):
1488 """
1489 Set a callback to validate OCSP data stapled to the TLS handshake on
1490 the client side.
1491
1492 :param callback: The callback function. It will be invoked with three
1493 arguments: the Connection, a bytestring containing the stapled OCSP
1494 assertion, and the optional arbitrary data you have provided. The
1495 callback must return a boolean that indicates the result of
1496 validating the OCSP data: ``True`` if the OCSP data is valid and
1497 the certificate can be trusted, or ``False`` if either the OCSP
1498 data is invalid or the certificate has been revoked.
1499 :param data: Some opaque data that will be passed into the callback
1500 function when called. This can be used to avoid needing to do
1501 complex data lookups or to keep track of what context is being
1502 used. This parameter is optional.
1503 """
1504 helper = _OCSPClientCallbackHelper(callback)
1505 self._set_ocsp_callback(helper, data)
1506
Alex Chanc6077062016-11-18 13:53:39 +00001507
Alex Gaynor10d30832017-06-29 15:31:39 -07001508ContextType = deprecated(
1509 Context, __name__,
1510 "ContextType has been deprecated, use Context instead", DeprecationWarning
1511)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512
1513
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514class Connection(object):
1515 """
1516 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001517 _reverse_mapping = WeakValueDictionary()
1518
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001519 def __init__(self, context, socket=None):
1520 """
1521 Create a new Connection object, using the given OpenSSL.SSL.Context
1522 instance and socket.
1523
1524 :param context: An SSL Context to use for this connection
1525 :param socket: The socket to use for transport layer
1526 """
1527 if not isinstance(context, Context):
1528 raise TypeError("context must be a Context instance")
1529
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001530 ssl = _lib.SSL_new(context._context)
1531 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001532 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001533 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001534
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001535 # References to strings used for Next Protocol Negotiation. OpenSSL's
1536 # header files suggest that these might get copied at some point, but
1537 # doesn't specify when, so we store them here to make sure they don't
1538 # get freed before OpenSSL uses them.
1539 self._npn_advertise_callback_args = None
1540 self._npn_select_callback_args = None
1541
Cory Benfield12eae892014-06-07 15:42:56 +01001542 # References to strings used for Application Layer Protocol
1543 # Negotiation. These strings get copied at some point but it's well
1544 # after the callback returns, so we have to hang them somewhere to
1545 # avoid them getting freed.
1546 self._alpn_select_callback_args = None
1547
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001548 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001549
1550 if socket is None:
1551 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001552 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001553 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001554 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001555
Alex Gaynora829e902016-06-04 18:16:01 -07001556 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1557 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001558
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001559 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001560 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001561 self._into_ssl = None
1562 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001563 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001564 set_result = _lib.SSL_set_fd(
1565 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001566 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001568 def __getattr__(self, name):
1569 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001570 Look up attributes on the wrapped socket object if they are not found
1571 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
kjav0b66fa12015-09-02 11:51:26 +01001573 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001574 raise AttributeError("'%s' object has no attribute '%s'" % (
1575 self.__class__.__name__, name
1576 ))
kjav0b66fa12015-09-02 11:51:26 +01001577 else:
1578 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001581 if self._context._verify_helper is not None:
1582 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001583 if self._context._npn_advertise_helper is not None:
1584 self._context._npn_advertise_helper.raise_if_problem()
1585 if self._context._npn_select_helper is not None:
1586 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001587 if self._context._alpn_select_helper is not None:
1588 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001589 if self._context._ocsp_helper is not None:
1590 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001591
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001592 error = _lib.SSL_get_error(ssl, result)
1593 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001595 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001596 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001597 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001598 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001600 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001601 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001602 elif error == _lib.SSL_ERROR_SYSCALL:
1603 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001605 if platform == "win32":
1606 errno = _ffi.getwinerror()[0]
1607 else:
1608 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001609
1610 if errno != 0:
1611 raise SysCallError(errno, errorcode.get(errno))
1612 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001614 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001615 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001616 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001617 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001618 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001619 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001621 def get_context(self):
1622 """
Alex Chand072cae2018-02-15 09:57:59 +00001623 Retrieve the :class:`Context` object associated with this
1624 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001626 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001627
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001628 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629 """
Alex Chand072cae2018-02-15 09:57:59 +00001630 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
Alex Chand072cae2018-02-15 09:57:59 +00001632 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001633 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001634 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635 if not isinstance(context, Context):
1636 raise TypeError("context must be a Context instance")
1637
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001638 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639 self._context = context
1640
Cory Benfielde6f35882016-03-29 11:21:04 +01001641 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001642 def get_servername(self):
1643 """
1644 Retrieve the servername extension value if provided in the client hello
1645 message, or None if there wasn't one.
1646
Alex Chand072cae2018-02-15 09:57:59 +00001647 :return: A byte string giving the server name or :data:`None`.
1648
1649 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001651 name = _lib.SSL_get_servername(
1652 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1653 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001654 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001655 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001657 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658
Cory Benfielde6f35882016-03-29 11:21:04 +01001659 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001660 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661 """
1662 Set the value of the servername extension to send in the client hello.
1663
1664 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001665
1666 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001667 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001668 if not isinstance(name, bytes):
1669 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001670 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671 raise TypeError("name must not contain NUL byte")
1672
1673 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001674 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001676 def pending(self):
1677 """
Alex Chand072cae2018-02-15 09:57:59 +00001678 Get the number of bytes that can be safely read from the SSL buffer
1679 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001680
1681 :return: The number of bytes available in the receive buffer.
1682 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001683 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001685 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 """
1687 Send data on the connection. NOTE: If you get one of the WantRead,
1688 WantWrite or WantX509Lookup exceptions on this, you have to call the
1689 method again with the SAME buffer.
1690
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001691 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001692 :param flags: (optional) Included for compatibility with the socket
1693 API, the value is ignored
1694 :return: The number of bytes written
1695 """
Abraham Martine82326c2015-02-04 10:18:10 +00001696 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001697 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001698
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001699 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001700 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001701 if isinstance(buf, _buffer):
1702 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001703 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001704 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001705 if len(buf) > 2147483647:
1706 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001708 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710 return result
1711 write = send
1712
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001713 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001714 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001715 Send "all" data on the connection. This calls send() repeatedly until
1716 all data is sent. If an error occurs, it's impossible to tell how much
1717 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001718
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001719 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001720 :param flags: (optional) Included for compatibility with the socket
1721 API, the value is ignored
1722 :return: The number of bytes written
1723 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001724 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001725
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001726 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001727 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001728 if isinstance(buf, _buffer):
1729 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001730 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001731 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001732
1733 left_to_send = len(buf)
1734 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001735 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001736
1737 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001738 # SSL_write's num arg is an int,
1739 # so we cannot send more than 2**31-1 bytes at once.
1740 result = _lib.SSL_write(
1741 self._ssl,
1742 data + total_sent,
1743 min(left_to_send, 2147483647)
1744 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745 self._raise_ssl_error(self._ssl, result)
1746 total_sent += result
1747 left_to_send -= result
1748
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749 def recv(self, bufsiz, flags=None):
1750 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001751 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001752
1753 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001754 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1755 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001756 :return: The string read from the Connection
1757 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001758 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001759 if flags is not None and flags & socket.MSG_PEEK:
1760 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1761 else:
1762 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001763 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001764 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001765 read = recv
1766
Cory Benfield62d10332014-06-15 10:03:41 +01001767 def recv_into(self, buffer, nbytes=None, flags=None):
1768 """
Alex Chand072cae2018-02-15 09:57:59 +00001769 Receive data on the connection and copy it directly into the provided
1770 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001771
1772 :param buffer: The buffer to copy into.
1773 :param nbytes: (optional) The maximum number of bytes to read into the
1774 buffer. If not present, defaults to the size of the buffer. If
1775 larger than the size of the buffer, is reduced to the size of the
1776 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001777 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1778 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001779 :return: The number of bytes read into the buffer.
1780 """
1781 if nbytes is None:
1782 nbytes = len(buffer)
1783 else:
1784 nbytes = min(nbytes, len(buffer))
1785
1786 # We need to create a temporary buffer. This is annoying, it would be
1787 # better if we could pass memoryviews straight into the SSL_read call,
1788 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001789 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001790 if flags is not None and flags & socket.MSG_PEEK:
1791 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1792 else:
1793 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001794 self._raise_ssl_error(self._ssl, result)
1795
1796 # This strange line is all to avoid a memory copy. The buffer protocol
1797 # should allow us to assign a CFFI buffer to the LHS of this line, but
1798 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001799 # wrap it in a memoryview.
1800 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001801
1802 return result
1803
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001804 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001805 if _lib.BIO_should_retry(bio):
1806 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001807 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001808 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001809 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001810 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001811 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001812 # TODO: This is untested. I think io_special means the socket
1813 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001814 raise ValueError("BIO_should_io_special")
1815 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001816 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001817 raise ValueError("unknown bio failure")
1818 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001819 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001820 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001821
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001822 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823 """
Alex Chand072cae2018-02-15 09:57:59 +00001824 If the Connection was created with a memory BIO, this method can be
1825 used to read bytes from the write end of that memory BIO. Many
1826 Connection methods will add bytes which must be read in this manner or
1827 the buffer will eventually fill up and the Connection will be able to
1828 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001829
1830 :param bufsiz: The maximum number of bytes to read
1831 :return: The string read.
1832 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001833 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001834 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001835
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001836 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001837 raise TypeError("bufsiz must be an integer")
1838
Cory Benfielde62840e2016-11-28 12:17:08 +00001839 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001840 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001841 if result <= 0:
1842 self._handle_bio_errors(self._from_ssl, result)
1843
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001844 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001845
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001846 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001847 """
Alex Chand072cae2018-02-15 09:57:59 +00001848 If the Connection was created with a memory BIO, this method can be
1849 used to add bytes to the read end of that memory BIO. The Connection
1850 can then read the bytes (for example, in response to a call to
1851 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001852
1853 :param buf: The string to put into the memory BIO.
1854 :return: The number of bytes written
1855 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001856 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001857
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001858 if self._into_ssl is None:
1859 raise TypeError("Connection sock was not None")
1860
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001861 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001862 if result <= 0:
1863 self._handle_bio_errors(self._into_ssl, result)
1864 return result
1865
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866 def renegotiate(self):
1867 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001868 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001869
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001870 :return: True if the renegotiation can be started, False otherwise
1871 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001872 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001873 if not self.renegotiate_pending():
1874 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1875 return True
1876 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001877
1878 def do_handshake(self):
1879 """
Alex Chand072cae2018-02-15 09:57:59 +00001880 Perform an SSL handshake (usually called after :meth:`renegotiate` or
1881 one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
1882 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001883
1884 :return: None.
1885 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001887 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001888
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889 def renegotiate_pending(self):
1890 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001891 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001892 a renegotiation is finished.
1893
1894 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001895 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001897 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898
1899 def total_renegotiations(self):
1900 """
1901 Find out the total number of renegotiations.
1902
1903 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001904 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001905 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001906 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001907
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001908 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001909 """
Alex Chand072cae2018-02-15 09:57:59 +00001910 Call the :meth:`connect` method of the underlying socket and set up SSL
1911 on the socket, using the :class:`Context` object supplied to this
1912 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913
1914 :param addr: A remote address
1915 :return: What the socket's connect method returns
1916 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001917 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001918 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001919
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001920 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 """
Alex Chand072cae2018-02-15 09:57:59 +00001922 Call the :meth:`connect_ex` method of the underlying socket and set up
1923 SSL on the socket, using the Context object supplied to this Connection
1924 object at creation. Note that if the :meth:`connect_ex` method of the
1925 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926
1927 :param addr: A remove address
1928 :return: What the socket's connect_ex method returns
1929 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001930 connect_ex = self._socket.connect_ex
1931 self.set_connect_state()
1932 return connect_ex(addr)
1933
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934 def accept(self):
1935 """
Alex Chand072cae2018-02-15 09:57:59 +00001936 Call the :meth:`accept` method of the underlying socket and set up SSL
1937 on the returned socket, using the Context object supplied to this
1938 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939
Alex Chand072cae2018-02-15 09:57:59 +00001940 :return: A *(conn, addr)* pair where *conn* is the new
1941 :class:`Connection` object created, and *address* is as returned by
1942 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001944 client, addr = self._socket.accept()
1945 conn = Connection(self._context, client)
1946 conn.set_accept_state()
1947 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001948
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001949 def bio_shutdown(self):
1950 """
Alex Chand072cae2018-02-15 09:57:59 +00001951 If the Connection was created with a memory BIO, this method can be
1952 used to indicate that *end of file* has been reached on the read end of
1953 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001954
1955 :return: None
1956 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957 if self._from_ssl is None:
1958 raise TypeError("Connection sock was not None")
1959
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001961
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962 def shutdown(self):
1963 """
Alex Chand072cae2018-02-15 09:57:59 +00001964 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001965
1966 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001967 have sent closure alerts), False otherwise (in which case you
1968 call :meth:`recv` or :meth:`send` when the connection becomes
1969 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001970 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001971 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001972 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001973 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001974 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001975 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001976 else:
1977 return False
1978
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001979 def get_cipher_list(self):
1980 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001981 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001983 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984 """
1985 ciphers = []
1986 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001987 result = _lib.SSL_get_cipher_list(self._ssl, i)
1988 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001990 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001991 return ciphers
1992
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993 def get_client_ca_list(self):
1994 """
1995 Get CAs whose certificates are suggested for client authentication.
1996
Alex Chand072cae2018-02-15 09:57:59 +00001997 :return: If this is a server connection, the list of certificate
1998 authorities that will be sent or has been sent to the client, as
1999 controlled by this :class:`Connection`'s :class:`Context`.
2000
2001 If this is a client connection, the list will be empty until the
2002 connection with the server is established.
2003
2004 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002006 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2007 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002008 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 return []
2010
2011 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002012 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2013 name = _lib.sk_X509_NAME_value(ca_names, i)
2014 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002015 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002016
2017 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002018 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002019 result.append(pyname)
2020 return result
2021
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002022 def makefile(self):
2023 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002024 The makefile() method is not implemented, since there is no dup
2025 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002026
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002027 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002028 """
Alex Gaynor83284952015-09-05 10:43:30 -04002029 raise NotImplementedError(
2030 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002031
2032 def get_app_data(self):
2033 """
Alex Chand072cae2018-02-15 09:57:59 +00002034 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035
2036 :return: The application data
2037 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002038 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002039
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002040 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002041 """
2042 Set application data
2043
Alex Chand072cae2018-02-15 09:57:59 +00002044 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002045 :return: None
2046 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002047 self._app_data = data
2048
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049 def get_shutdown(self):
2050 """
Alex Chand072cae2018-02-15 09:57:59 +00002051 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052
Alex Gaynor62da94d2015-09-05 14:37:34 -04002053 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2054 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002056 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002057
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002058 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002059 """
Alex Chand072cae2018-02-15 09:57:59 +00002060 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002061
Alex Chand072cae2018-02-15 09:57:59 +00002062 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002063 :return: None
2064 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002065 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002066 raise TypeError("state must be an integer")
2067
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002068 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002069
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002070 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002072 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073
2074 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002075 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002076 """
kjavc704a2e2015-09-07 12:12:27 +01002077 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002078
2079 def server_random(self):
2080 """
Alex Chand072cae2018-02-15 09:57:59 +00002081 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002082
2083 :return: A string representing the state
2084 """
Alex Gaynor93603062016-06-01 20:13:09 -07002085 session = _lib.SSL_get_session(self._ssl)
2086 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002087 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002088 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2089 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002090 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002091 _lib.SSL_get_server_random(self._ssl, outp, length)
2092 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002093
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002094 def client_random(self):
2095 """
Alex Chand072cae2018-02-15 09:57:59 +00002096 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002097
2098 :return: A string representing the state
2099 """
Alex Gaynor93603062016-06-01 20:13:09 -07002100 session = _lib.SSL_get_session(self._ssl)
2101 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002102 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002103
2104 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2105 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002106 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002107 _lib.SSL_get_client_random(self._ssl, outp, length)
2108 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002109
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110 def master_key(self):
2111 """
Alex Chand072cae2018-02-15 09:57:59 +00002112 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002113
2114 :return: A string representing the state
2115 """
Alex Gaynor93603062016-06-01 20:13:09 -07002116 session = _lib.SSL_get_session(self._ssl)
2117 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002118 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002119
2120 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2121 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002122 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002123 _lib.SSL_SESSION_get_master_key(session, outp, length)
2124 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002125
Paul Kehrerbdb76392017-12-01 04:54:32 +08002126 def export_keying_material(self, label, olen, context=None):
2127 """
2128 Obtain keying material for application use.
2129
Alex Chand072cae2018-02-15 09:57:59 +00002130 :param: label - a disambiguating label string as described in RFC 5705
2131 :param: olen - the length of the exported key material in bytes
2132 :param: context - a per-association context value
2133 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002134 """
2135 outp = _no_zero_allocator("unsigned char[]", olen)
2136 context_buf = _ffi.NULL
2137 context_len = 0
2138 use_context = 0
2139 if context is not None:
2140 context_buf = context
2141 context_len = len(context)
2142 use_context = 1
2143 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2144 label, len(label),
2145 context_buf, context_len,
2146 use_context)
2147 _openssl_assert(success == 1)
2148 return _ffi.buffer(outp, olen)[:]
2149
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002150 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002151 """
Alex Chand072cae2018-02-15 09:57:59 +00002152 Call the :meth:`shutdown` method of the underlying socket.
2153 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002154
2155 :return: What the socket's shutdown() method returns
2156 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002157 return self._socket.shutdown(*args, **kwargs)
2158
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002159 def get_peer_certificate(self):
2160 """
2161 Retrieve the other side's certificate (if any)
2162
2163 :return: The peer's certificate
2164 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002165 cert = _lib.SSL_get_peer_certificate(self._ssl)
2166 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002167 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002168 return None
2169
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002170 def get_peer_cert_chain(self):
2171 """
2172 Retrieve the other side's certificate (if any)
2173
2174 :return: A list of X509 instances giving the peer's certificate chain,
2175 or None if it does not have one.
2176 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002177 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2178 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002179 return None
2180
2181 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002182 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002183 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002184 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002185 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002186 result.append(pycert)
2187 return result
2188
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002189 def want_read(self):
2190 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002191 Checks if more data has to be read from the transport layer to complete
2192 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002193
2194 :return: True iff more data has to be read
2195 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002196 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002197
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002198 def want_write(self):
2199 """
2200 Checks if there is data to write to the transport layer to complete an
2201 operation.
2202
2203 :return: True iff there is data to write
2204 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002205 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002206
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002207 def set_accept_state(self):
2208 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002209 Set the connection to work in server mode. The handshake will be
2210 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002211
2212 :return: None
2213 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002214 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002215
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002216 def set_connect_state(self):
2217 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002218 Set the connection to work in client mode. The handshake will be
2219 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002220
2221 :return: None
2222 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002224
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002225 def get_session(self):
2226 """
2227 Returns the Session currently used.
2228
Alex Chand072cae2018-02-15 09:57:59 +00002229 :return: An instance of :class:`OpenSSL.SSL.Session` or
2230 :obj:`None` if no session exists.
2231
2232 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002233 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002234 session = _lib.SSL_get1_session(self._ssl)
2235 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002236 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002237
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002238 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002239 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002240 return pysession
2241
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002242 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002243 """
2244 Set the session to be used when the TLS/SSL connection is established.
2245
2246 :param session: A Session instance representing the session to use.
2247 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002248
2249 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002250 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002251 if not isinstance(session, Session):
2252 raise TypeError("session must be a Session instance")
2253
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002254 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002255 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002256 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002257
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002258 def _get_finished_message(self, function):
2259 """
Alex Chand072cae2018-02-15 09:57:59 +00002260 Helper to implement :meth:`get_finished` and
2261 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002262
Alex Chand072cae2018-02-15 09:57:59 +00002263 :param function: Either :data:`SSL_get_finished`: or
2264 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002265
Alex Chand072cae2018-02-15 09:57:59 +00002266 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002267 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002268 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002269 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002270 # The OpenSSL documentation says nothing about what might happen if the
2271 # count argument given is zero. Specifically, it doesn't say whether
2272 # the output buffer may be NULL in that case or not. Inspection of the
2273 # implementation reveals that it calls memcpy() unconditionally.
2274 # Section 7.1.4, paragraph 1 of the C standard suggests that
2275 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2276 # alone desirable) behavior (though it probably does on just about
2277 # every implementation...)
2278 #
2279 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2280 # one might expect) for the initial call so as to be safe against this
2281 # potentially undefined behavior.
2282 empty = _ffi.new("char[]", 0)
2283 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002284 if size == 0:
2285 # No Finished message so far.
2286 return None
2287
Cory Benfielde62840e2016-11-28 12:17:08 +00002288 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002289 function(self._ssl, buf, size)
2290 return _ffi.buffer(buf, size)[:]
2291
Fedor Brunner5747b932014-03-05 14:22:34 +01002292 def get_finished(self):
2293 """
Alex Chand072cae2018-02-15 09:57:59 +00002294 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002295
Alex Chand072cae2018-02-15 09:57:59 +00002296 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002297 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002298 :rtype: :class:`bytes` or :class:`NoneType`
2299
2300 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002301 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002302 return self._get_finished_message(_lib.SSL_get_finished)
2303
Fedor Brunner5747b932014-03-05 14:22:34 +01002304 def get_peer_finished(self):
2305 """
Alex Chand072cae2018-02-15 09:57:59 +00002306 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002307
Alex Chand072cae2018-02-15 09:57:59 +00002308 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002309 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002310 :rtype: :class:`bytes` or :class:`NoneType`
2311
2312 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002313 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002314 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002315
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002316 def get_cipher_name(self):
2317 """
2318 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002319
Alex Chand072cae2018-02-15 09:57:59 +00002320 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002321 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002322 :rtype: :class:`unicode` or :class:`NoneType`
2323
2324 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002325 """
2326 cipher = _lib.SSL_get_current_cipher(self._ssl)
2327 if cipher == _ffi.NULL:
2328 return None
2329 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002330 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2331 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002332
2333 def get_cipher_bits(self):
2334 """
2335 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002336
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002337 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002338 or :obj:`None` if no connection has been established.
2339 :rtype: :class:`int` or :class:`NoneType`
2340
2341 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002342 """
2343 cipher = _lib.SSL_get_current_cipher(self._ssl)
2344 if cipher == _ffi.NULL:
2345 return None
2346 else:
2347 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2348
2349 def get_cipher_version(self):
2350 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002351 Obtain the protocol version of the currently used cipher.
2352
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002353 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002354 or :obj:`None` if no connection has been established.
2355 :rtype: :class:`unicode` or :class:`NoneType`
2356
2357 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002358 """
2359 cipher = _lib.SSL_get_current_cipher(self._ssl)
2360 if cipher == _ffi.NULL:
2361 return None
2362 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002363 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002364 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002365
Jim Shaverabff1882015-05-27 09:15:55 -04002366 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002367 """
Alex Chand072cae2018-02-15 09:57:59 +00002368 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002369
2370 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002371 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002372 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002373 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002374 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002375 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002376 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002377
Jim Shaver208438c2015-05-28 09:52:38 -04002378 def get_protocol_version(self):
2379 """
Alex Chand072cae2018-02-15 09:57:59 +00002380 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002381
Alex Chand072cae2018-02-15 09:57:59 +00002382 :returns: The TLS version of the current connection. For example,
2383 it will return ``0x769`` for connections made over TLS version 1.
2384 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002385 """
2386 version = _lib.SSL_version(self._ssl)
2387 return version
2388
Cory Benfield10b277f2015-04-13 17:12:42 -04002389 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002390 def get_next_proto_negotiated(self):
2391 """
2392 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002393
2394 :returns: A bytestring of the protocol name. If no protocol has been
2395 negotiated yet, returns an empty string.
2396
2397 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002398 """
2399 data = _ffi.new("unsigned char **")
2400 data_len = _ffi.new("unsigned int *")
2401
2402 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2403
Cory Benfieldcd010f62014-05-15 19:00:27 +01002404 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002405
Cory Benfield7907e332015-04-13 17:18:25 -04002406 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002407 def set_alpn_protos(self, protos):
2408 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002409 Specify the client's ALPN protocol list.
2410
2411 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002412
2413 :param protos: A list of the protocols to be offered to the server.
2414 This list should be a Python list of bytestrings representing the
2415 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2416 """
2417 # Take the list of protocols and join them together, prefixing them
2418 # with their lengths.
2419 protostr = b''.join(
2420 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2421 )
2422
2423 # Build a C string from the list. We don't need to save this off
2424 # because OpenSSL immediately copies the data out.
2425 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002426 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002427
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002428 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002429 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002430 """
2431 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002432
2433 :returns: A bytestring of the protocol name. If no protocol has been
2434 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002435 """
Cory Benfield12eae892014-06-07 15:42:56 +01002436 data = _ffi.new("unsigned char **")
2437 data_len = _ffi.new("unsigned int *")
2438
2439 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2440
Cory Benfielde8e9c382015-04-11 17:33:48 -04002441 if not data_len:
2442 return b''
2443
Cory Benfield12eae892014-06-07 15:42:56 +01002444 return _ffi.buffer(data[0], data_len[0])[:]
2445
Cory Benfield496652a2017-01-24 11:42:56 +00002446 def request_ocsp(self):
2447 """
2448 Called to request that the server sends stapled OCSP data, if
2449 available. If this is not called on the client side then the server
2450 will not send OCSP data. Should be used in conjunction with
2451 :meth:`Context.set_ocsp_client_callback`.
2452 """
2453 rc = _lib.SSL_set_tlsext_status_type(
2454 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2455 )
2456 _openssl_assert(rc == 1)
2457
Cory Benfield12eae892014-06-07 15:42:56 +01002458
Alex Gaynor10d30832017-06-29 15:31:39 -07002459ConnectionType = deprecated(
2460 Connection, __name__,
2461 "ConnectionType has been deprecated, use Connection instead",
2462 DeprecationWarning
2463)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002464
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002465# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2466# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002467_lib.SSL_library_init()