blob: de49cf97c9978653234c39bfc1252984117accbb [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 Gaynor336d8022017-06-29 21:46:42 -07009from six import (
10 binary_type as _binary_type, integer_types as integer_types, int2byte,
11 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050012
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050013from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010014 UNSPECIFIED as _UNSPECIFIED,
15 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050016 ffi as _ffi,
17 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010018 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010019 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040020 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000022 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040023)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080024
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050026 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027
Nicolas Karolak736c6212017-11-26 14:40:28 +010028__all__ = [
29 'OPENSSL_VERSION_NUMBER',
30 'SSLEAY_VERSION',
31 'SSLEAY_CFLAGS',
32 'SSLEAY_PLATFORM',
33 'SSLEAY_DIR',
34 'SSLEAY_BUILT_ON',
35 'SENT_SHUTDOWN',
36 'RECEIVED_SHUTDOWN',
37 'SSLv2_METHOD',
38 'SSLv3_METHOD',
39 'SSLv23_METHOD',
40 'TLSv1_METHOD',
41 'TLSv1_1_METHOD',
42 'TLSv1_2_METHOD',
43 'OP_NO_SSLv2',
44 'OP_NO_SSLv3',
45 'OP_NO_TLSv1',
46 'OP_NO_TLSv1_1',
47 'OP_NO_TLSv1_2',
48 'MODE_RELEASE_BUFFERS',
49 'OP_SINGLE_DH_USE',
50 'OP_SINGLE_ECDH_USE',
51 'OP_EPHEMERAL_RSA',
52 'OP_MICROSOFT_SESS_ID_BUG',
53 'OP_NETSCAPE_CHALLENGE_BUG',
54 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
55 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
56 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
57 'OP_MSIE_SSLV2_RSA_PADDING',
58 'OP_SSLEAY_080_CLIENT_DH_BUG',
59 'OP_TLS_D5_BUG',
60 'OP_TLS_BLOCK_PADDING_BUG',
61 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
62 'OP_CIPHER_SERVER_PREFERENCE',
63 'OP_TLS_ROLLBACK_BUG',
64 'OP_PKCS1_CHECK_1',
65 'OP_PKCS1_CHECK_2',
66 'OP_NETSCAPE_CA_DN_BUG',
67 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
68 'OP_NO_COMPRESSION',
69 'OP_NO_QUERY_MTU',
70 'OP_COOKIE_EXCHANGE',
71 'OP_NO_TICKET',
72 'OP_ALL',
73 'VERIFY_PEER',
74 'VERIFY_FAIL_IF_NO_PEER_CERT',
75 'VERIFY_CLIENT_ONCE',
76 'VERIFY_NONE',
77 'SESS_CACHE_OFF',
78 'SESS_CACHE_CLIENT',
79 'SESS_CACHE_SERVER',
80 'SESS_CACHE_BOTH',
81 'SESS_CACHE_NO_AUTO_CLEAR',
82 'SESS_CACHE_NO_INTERNAL_LOOKUP',
83 'SESS_CACHE_NO_INTERNAL_STORE',
84 'SESS_CACHE_NO_INTERNAL',
85 'SSL_ST_CONNECT',
86 'SSL_ST_ACCEPT',
87 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010088 'SSL_CB_LOOP',
89 'SSL_CB_EXIT',
90 'SSL_CB_READ',
91 'SSL_CB_WRITE',
92 'SSL_CB_ALERT',
93 'SSL_CB_READ_ALERT',
94 'SSL_CB_WRITE_ALERT',
95 'SSL_CB_ACCEPT_LOOP',
96 'SSL_CB_ACCEPT_EXIT',
97 'SSL_CB_CONNECT_LOOP',
98 'SSL_CB_CONNECT_EXIT',
99 'SSL_CB_HANDSHAKE_START',
100 'SSL_CB_HANDSHAKE_DONE',
101 'Error',
102 'WantReadError',
103 'WantWriteError',
104 'WantX509LookupError',
105 'ZeroReturnError',
106 'SysCallError',
107 'SSLeay_version',
108 'Session',
109 'Context',
110 'Connection'
111]
112
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500113try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200114 _buffer = buffer
115except NameError:
116 class _buffer(object):
117 pass
118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500119OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
120SSLEAY_VERSION = _lib.SSLEAY_VERSION
121SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
122SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
123SSLEAY_DIR = _lib.SSLEAY_DIR
124SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800125
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500126SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
127RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800128
129SSLv2_METHOD = 1
130SSLv3_METHOD = 2
131SSLv23_METHOD = 3
132TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500133TLSv1_1_METHOD = 5
134TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800135
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500136OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
137OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
138OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700139OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
140OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800141
Alex Gaynorbf012872016-06-04 13:18:39 -0700142MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800143
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500144OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900145OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500146OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
147OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
148OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400149OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
150 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
151)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
153OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400154OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500155OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
156OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
157OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
158OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
159OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
160OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
161OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
162OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
163OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400164OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
165 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
166)
Alex Gaynorbf012872016-06-04 13:18:39 -0700167OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800168
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500169OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
170OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400171OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800172
Alex Gaynorc4889812015-09-04 08:43:17 -0400173OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800174
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500175VERIFY_PEER = _lib.SSL_VERIFY_PEER
176VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
177VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
178VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800179
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
181SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
182SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
183SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
184SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
185SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
186SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
187SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800188
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500189SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
190SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
191SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400192if _lib.Cryptography_HAS_SSL_ST:
193 SSL_ST_INIT = _lib.SSL_ST_INIT
194 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
195 SSL_ST_OK = _lib.SSL_ST_OK
196 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100197 __all__.extend([
198 'SSL_ST_INIT',
199 'SSL_ST_BEFORE',
200 'SSL_ST_OK',
201 'SSL_ST_RENEGOTIATE',
202 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500204SSL_CB_LOOP = _lib.SSL_CB_LOOP
205SSL_CB_EXIT = _lib.SSL_CB_EXIT
206SSL_CB_READ = _lib.SSL_CB_READ
207SSL_CB_WRITE = _lib.SSL_CB_WRITE
208SSL_CB_ALERT = _lib.SSL_CB_ALERT
209SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
210SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
211SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
212SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
213SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
214SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
215SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
216SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800217
Paul Kehrer55fb3412017-06-29 18:44:08 -0500218# Taken from https://golang.org/src/crypto/x509/root_linux.go
219_CERTIFICATE_FILE_LOCATIONS = [
220 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
221 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
222 "/etc/ssl/ca-bundle.pem", # OpenSUSE
223 "/etc/pki/tls/cacert.pem", # OpenELEC
224 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
225]
226
227_CERTIFICATE_PATH_LOCATIONS = [
228 "/etc/ssl/certs", # SLES10/SLES11
229]
230
Paul Kehrera92a1a72017-07-19 15:53:23 +0200231# These values are compared to output from cffi's ffi.string so they must be
232# byte strings.
233_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
234_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500235
Alex Gaynor83284952015-09-05 10:43:30 -0400236
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500237class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500238 """
239 An error occurred in an `OpenSSL.SSL` API.
240 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500241
242
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100244_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500245
246
247class WantReadError(Error):
248 pass
249
250
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251class WantWriteError(Error):
252 pass
253
254
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500255class WantX509LookupError(Error):
256 pass
257
258
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500259class ZeroReturnError(Error):
260 pass
261
262
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500263class SysCallError(Error):
264 pass
265
266
Cory Benfield0ea76e72015-03-22 09:05:28 +0000267class _CallbackExceptionHelper(object):
268 """
269 A base class for wrapper classes that allow for intelligent exception
270 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500271
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400272 :ivar list _problems: Any exceptions that occurred while executing in a
273 context where they could not be raised in the normal way. Typically
274 this is because OpenSSL has called into some Python code and requires a
275 return value. The exceptions are saved to be raised later when it is
276 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000277 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400278
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400279 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800280 self._problems = []
281
Cory Benfield0ea76e72015-03-22 09:05:28 +0000282 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400283 """
284 Raise an exception from the OpenSSL error queue or that was previously
285 captured whe running a callback.
286 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000287 if self._problems:
288 try:
289 _raise_current_error()
290 except Error:
291 pass
292 raise self._problems.pop(0)
293
294
295class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400296 """
297 Wrap a callback such that it can be used as a certificate verification
298 callback.
299 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400300
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800301 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400302 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800303
304 @wraps(callback)
305 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800306 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
307 _lib.X509_up_ref(x509)
308 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500309 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
310 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800311
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400312 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
313 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
314 connection = Connection._reverse_mapping[ssl]
315
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800316 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400317 result = callback(
318 connection, cert, error_number, error_depth, ok
319 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800320 except Exception as e:
321 self._problems.append(e)
322 return 0
323 else:
324 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500325 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800326 return 1
327 else:
328 return 0
329
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500330 self.callback = _ffi.callback(
331 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800332
333
Cory Benfield0ea76e72015-03-22 09:05:28 +0000334class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400335 """
336 Wrap a callback such that it can be used as an NPN advertisement callback.
337 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400338
Cory Benfield0ea76e72015-03-22 09:05:28 +0000339 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400340 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800341
Cory Benfield0ea76e72015-03-22 09:05:28 +0000342 @wraps(callback)
343 def wrapper(ssl, out, outlen, arg):
344 try:
345 conn = Connection._reverse_mapping[ssl]
346 protos = callback(conn)
347
348 # Join the protocols into a Python bytestring, length-prefixing
349 # each element.
350 protostr = b''.join(
351 chain.from_iterable((int2byte(len(p)), p) for p in protos)
352 )
353
354 # Save our callback arguments on the connection object. This is
355 # done to make sure that they don't get freed before OpenSSL
356 # uses them. Then, return them appropriately in the output
357 # parameters.
358 conn._npn_advertise_callback_args = [
359 _ffi.new("unsigned int *", len(protostr)),
360 _ffi.new("unsigned char[]", protostr),
361 ]
362 outlen[0] = conn._npn_advertise_callback_args[0][0]
363 out[0] = conn._npn_advertise_callback_args[1]
364 return 0
365 except Exception as e:
366 self._problems.append(e)
367 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
368
369 self.callback = _ffi.callback(
370 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
371 wrapper
372 )
373
374
375class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400376 """
377 Wrap a callback such that it can be used as an NPN selection callback.
378 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400379
Cory Benfield0ea76e72015-03-22 09:05:28 +0000380 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400381 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000382
383 @wraps(callback)
384 def wrapper(ssl, out, outlen, in_, inlen, arg):
385 try:
386 conn = Connection._reverse_mapping[ssl]
387
388 # The string passed to us is actually made up of multiple
389 # length-prefixed bytestrings. We need to split that into a
390 # list.
391 instr = _ffi.buffer(in_, inlen)[:]
392 protolist = []
393 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500394 length = indexbytes(instr, 0)
395 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000396 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500397 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000398
399 # Call the callback
400 outstr = callback(conn, protolist)
401
402 # Save our callback arguments on the connection object. This is
403 # done to make sure that they don't get freed before OpenSSL
404 # uses them. Then, return them appropriately in the output
405 # parameters.
406 conn._npn_select_callback_args = [
407 _ffi.new("unsigned char *", len(outstr)),
408 _ffi.new("unsigned char[]", outstr),
409 ]
410 outlen[0] = conn._npn_select_callback_args[0][0]
411 out[0] = conn._npn_select_callback_args[1]
412 return 0
413 except Exception as e:
414 self._problems.append(e)
415 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
416
417 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400418 ("int (*)(SSL *, unsigned char **, unsigned char *, "
419 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000420 wrapper
421 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800422
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800423
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400424class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400425 """
426 Wrap a callback such that it can be used as an ALPN selection callback.
427 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400428
Cory Benfieldf1177e72015-04-12 09:11:49 -0400429 def __init__(self, callback):
430 _CallbackExceptionHelper.__init__(self)
431
432 @wraps(callback)
433 def wrapper(ssl, out, outlen, in_, inlen, arg):
434 try:
435 conn = Connection._reverse_mapping[ssl]
436
437 # The string passed to us is made up of multiple
438 # length-prefixed bytestrings. We need to split that into a
439 # list.
440 instr = _ffi.buffer(in_, inlen)[:]
441 protolist = []
442 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400443 encoded_len = indexbytes(instr, 0)
444 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400445 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400446 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400447
448 # Call the callback
449 outstr = callback(conn, protolist)
450
451 if not isinstance(outstr, _binary_type):
452 raise TypeError("ALPN callback must return a bytestring.")
453
454 # Save our callback arguments on the connection object to make
455 # sure that they don't get freed before OpenSSL can use them.
456 # Then, return them in the appropriate output parameters.
457 conn._alpn_select_callback_args = [
458 _ffi.new("unsigned char *", len(outstr)),
459 _ffi.new("unsigned char[]", outstr),
460 ]
461 outlen[0] = conn._alpn_select_callback_args[0][0]
462 out[0] = conn._alpn_select_callback_args[1]
463 return 0
464 except Exception as e:
465 self._problems.append(e)
466 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
467
468 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400469 ("int (*)(SSL *, unsigned char **, unsigned char *, "
470 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400471 wrapper
472 )
473
474
Cory Benfield496652a2017-01-24 11:42:56 +0000475class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
476 """
477 Wrap a callback such that it can be used as an OCSP callback for the server
478 side.
479
480 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
481 ways. For servers, that callback is expected to retrieve some OCSP data and
482 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
483 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
484 is expected to check the OCSP data, and returns a negative value on error,
485 0 if the response is not acceptable, or positive if it is. These are
486 mutually exclusive return code behaviours, and they mean that we need two
487 helpers so that we always return an appropriate error code if the user's
488 code throws an exception.
489
490 Given that we have to have two helpers anyway, these helpers are a bit more
491 helpery than most: specifically, they hide a few more of the OpenSSL
492 functions so that the user has an easier time writing these callbacks.
493
494 This helper implements the server side.
495 """
496
497 def __init__(self, callback):
498 _CallbackExceptionHelper.__init__(self)
499
500 @wraps(callback)
501 def wrapper(ssl, cdata):
502 try:
503 conn = Connection._reverse_mapping[ssl]
504
505 # Extract the data if any was provided.
506 if cdata != _ffi.NULL:
507 data = _ffi.from_handle(cdata)
508 else:
509 data = None
510
511 # Call the callback.
512 ocsp_data = callback(conn, data)
513
514 if not isinstance(ocsp_data, _binary_type):
515 raise TypeError("OCSP callback must return a bytestring.")
516
517 # If the OCSP data was provided, we will pass it to OpenSSL.
518 # However, we have an early exit here: if no OCSP data was
519 # provided we will just exit out and tell OpenSSL that there
520 # is nothing to do.
521 if not ocsp_data:
522 return 3 # SSL_TLSEXT_ERR_NOACK
523
David Benjamin7ac5f272018-05-21 21:24:04 -0400524 # OpenSSL takes ownership of this data and expects it to have
525 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000526 ocsp_data_length = len(ocsp_data)
527 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
528 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
529
530 _lib.SSL_set_tlsext_status_ocsp_resp(
531 ssl, data_ptr, ocsp_data_length
532 )
533
534 return 0
535 except Exception as e:
536 self._problems.append(e)
537 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
538
539 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
540
541
542class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
543 """
544 Wrap a callback such that it can be used as an OCSP callback for the client
545 side.
546
547 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
548 ways. For servers, that callback is expected to retrieve some OCSP data and
549 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
550 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
551 is expected to check the OCSP data, and returns a negative value on error,
552 0 if the response is not acceptable, or positive if it is. These are
553 mutually exclusive return code behaviours, and they mean that we need two
554 helpers so that we always return an appropriate error code if the user's
555 code throws an exception.
556
557 Given that we have to have two helpers anyway, these helpers are a bit more
558 helpery than most: specifically, they hide a few more of the OpenSSL
559 functions so that the user has an easier time writing these callbacks.
560
561 This helper implements the client side.
562 """
563
564 def __init__(self, callback):
565 _CallbackExceptionHelper.__init__(self)
566
567 @wraps(callback)
568 def wrapper(ssl, cdata):
569 try:
570 conn = Connection._reverse_mapping[ssl]
571
572 # Extract the data if any was provided.
573 if cdata != _ffi.NULL:
574 data = _ffi.from_handle(cdata)
575 else:
576 data = None
577
578 # Get the OCSP data.
579 ocsp_ptr = _ffi.new("unsigned char **")
580 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
581 if ocsp_len < 0:
582 # No OCSP data.
583 ocsp_data = b''
584 else:
585 # Copy the OCSP data, then pass it to the callback.
586 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
587
588 valid = callback(conn, ocsp_data, data)
589
590 # Return 1 on success or 0 on error.
591 return int(bool(valid))
592
593 except Exception as e:
594 self._problems.append(e)
595 # Return negative value if an exception is hit.
596 return -1
597
598 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
599
600
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800601def _asFileDescriptor(obj):
602 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800603 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800604 meth = getattr(obj, "fileno", None)
605 if meth is not None:
606 obj = meth()
607
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800608 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800609 fd = obj
610
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800611 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800612 raise TypeError("argument must be an int, or have a fileno() method.")
613 elif fd < 0:
614 raise ValueError(
615 "file descriptor cannot be a negative integer (%i)" % (fd,))
616
617 return fd
618
619
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800620def SSLeay_version(type):
621 """
622 Return a string describing the version of OpenSSL in use.
623
Alex Chand072cae2018-02-15 09:57:59 +0000624 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800625 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500626 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800627
628
Cory Benfieldef404df2016-03-29 15:32:48 +0100629def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400630 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100631 Builds a decorator that ensures that functions that rely on OpenSSL
632 functions that are not present in this build raise NotImplementedError,
633 rather than AttributeError coming out of cryptography.
634
635 :param flag: A cryptography flag that guards the functions, e.g.
636 ``Cryptography_HAS_NEXTPROTONEG``.
637 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400638 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100639 def _requires_decorator(func):
640 if not flag:
641 @wraps(func)
642 def explode(*args, **kwargs):
643 raise NotImplementedError(error)
644 return explode
645 else:
646 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400647
Cory Benfieldef404df2016-03-29 15:32:48 +0100648 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400649
650
Cory Benfieldef404df2016-03-29 15:32:48 +0100651_requires_npn = _make_requires(
652 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
653)
Cory Benfield7907e332015-04-13 17:18:25 -0400654
655
Cory Benfieldef404df2016-03-29 15:32:48 +0100656_requires_alpn = _make_requires(
657 _lib.Cryptography_HAS_ALPN, "ALPN not available"
658)
Cory Benfielde6f35882016-03-29 11:21:04 +0100659
Cory Benfielde6f35882016-03-29 11:21:04 +0100660
Cory Benfieldef404df2016-03-29 15:32:48 +0100661_requires_sni = _make_requires(
662 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
663)
Cory Benfielde6f35882016-03-29 11:21:04 +0100664
665
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800666class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000667 """
668 A class representing an SSL session. A session defines certain connection
669 parameters which may be re-used to speed up the setup of subsequent
670 connections.
671
672 .. versionadded:: 0.14
673 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800674 pass
675
676
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800677class Context(object):
678 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100679 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400680 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000681
682 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
683 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684 """
685 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800686 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500687 SSLv3_METHOD: "SSLv3_method",
688 SSLv23_METHOD: "SSLv23_method",
689 TLSv1_METHOD: "TLSv1_method",
690 TLSv1_1_METHOD: "TLSv1_1_method",
691 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400692 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500693 _methods = dict(
694 (identifier, getattr(_lib, name))
695 for (identifier, name) in _methods.items()
696 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697
698 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500699 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800700 raise TypeError("method must be an integer")
701
702 try:
703 method_func = self._methods[method]
704 except KeyError:
705 raise ValueError("No such protocol")
706
707 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700708 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800709
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500710 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700711 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500712 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600714 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
715 # will be auto-selected. This function was added in 1.0.2 and made a
716 # noop in 1.1.0+ (where it is set automatically).
717 try:
718 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
719 _openssl_assert(res == 1)
720 except AttributeError:
721 pass
722
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800723 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800724 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800725 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800726 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800727 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728 self._verify_callback = None
729 self._info_callback = None
730 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800731 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000732 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100733 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000734 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100735 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400736 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100737 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000738 self._ocsp_helper = None
739 self._ocsp_callback = None
740 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500742 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800743
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744 def load_verify_locations(self, cafile, capath=None):
745 """
746 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000747 chain. Note that the certificates have to be in PEM format.
748
749 If capath is passed, it must be a directory prepared using the
750 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
751 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800752
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400753 :param cafile: In which file we can find the certificates (``bytes`` or
754 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800755 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400756 (``bytes`` or ``unicode``).
757
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758 :return: None
759 """
760 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500761 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400762 else:
763 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800764
765 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500766 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400767 else:
768 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769
Alex Gaynor62da94d2015-09-05 14:37:34 -0400770 load_result = _lib.SSL_CTX_load_verify_locations(
771 self._context, cafile, capath
772 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800773 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500774 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800775
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776 def _wrap_callback(self, callback):
777 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800778 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800779 return callback(size, verify, self._passphrase_userdata)
780 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800781 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def set_passwd_cb(self, callback, userdata=None):
784 """
Alex Chand072cae2018-02-15 09:57:59 +0000785 Set the passphrase callback. This function will be called
786 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787
Alex Chand072cae2018-02-15 09:57:59 +0000788 :param callback: The Python callback to use. This must accept three
789 positional arguments. First, an integer giving the maximum length
790 of the passphrase it may return. If the returned passphrase is
791 longer than this, it will be truncated. Second, a boolean value
792 which will be true if the user should be prompted for the
793 passphrase twice and the callback should verify that the two values
794 supplied are equal. Third, the value given as the *userdata*
795 parameter to :meth:`set_passwd_cb`. The *callback* must return
796 a byte string. If an error occurs, *callback* should return a false
797 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798 :param userdata: (optional) A Python object which will be given as
799 argument to the callback
800 :return: None
801 """
802 if not callable(callback):
803 raise TypeError("callback must be callable")
804
805 self._passphrase_helper = self._wrap_callback(callback)
806 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500807 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800808 self._context, self._passphrase_callback)
809 self._passphrase_userdata = userdata
810
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800811 def set_default_verify_paths(self):
812 """
Alex Chand072cae2018-02-15 09:57:59 +0000813 Specify that the platform provided CA certificates are to be used for
814 verification purposes. This method has some caveats related to the
815 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
816
817 * macOS will only load certificates using this method if the user has
818 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
819 in the default location.
820 * Windows will not work.
821 * manylinux1 cryptography wheels will work on most common Linux
822 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
823 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800824
825 :return: None
826 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500827 # SSL_CTX_set_default_verify_paths will attempt to load certs from
828 # both a cafile and capath that are set at compile time. However,
829 # it will first check environment variables and, if present, load
830 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500831 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400832 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500833 # After attempting to set default_verify_paths we need to know whether
834 # to go down the fallback path.
835 # First we'll check to see if any env vars have been set. If so,
836 # we won't try to do anything else because the user has set the path
837 # themselves.
838 dir_env_var = _ffi.string(
839 _lib.X509_get_default_cert_dir_env()
840 ).decode("ascii")
841 file_env_var = _ffi.string(
842 _lib.X509_get_default_cert_file_env()
843 ).decode("ascii")
844 if not self._check_env_vars_set(dir_env_var, file_env_var):
845 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
846 default_file = _ffi.string(_lib.X509_get_default_cert_file())
847 # Now we check to see if the default_dir and default_file are set
848 # to the exact values we use in our manylinux1 builds. If they are
849 # then we know to load the fallbacks
850 if (
851 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
852 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
853 ):
854 # This is manylinux1, let's load our fallback paths
855 self._fallback_default_verify_paths(
856 _CERTIFICATE_FILE_LOCATIONS,
857 _CERTIFICATE_PATH_LOCATIONS
858 )
859
860 def _check_env_vars_set(self, dir_env_var, file_env_var):
861 """
862 Check to see if the default cert dir/file environment vars are present.
863
864 :return: bool
865 """
866 return (
867 os.environ.get(file_env_var) is not None or
868 os.environ.get(dir_env_var) is not None
869 )
870
871 def _fallback_default_verify_paths(self, file_path, dir_path):
872 """
873 Default verify paths are based on the compiled version of OpenSSL.
874 However, when pyca/cryptography is compiled as a manylinux1 wheel
875 that compiled location can potentially be wrong. So, like Go, we
876 will try a predefined set of paths and attempt to load roots
877 from there.
878
879 :return: None
880 """
881 for cafile in file_path:
882 if os.path.isfile(cafile):
883 self.load_verify_locations(cafile)
884 break
885
886 for capath in dir_path:
887 if os.path.isdir(capath):
888 self.load_verify_locations(None, capath)
889 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800890
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891 def use_certificate_chain_file(self, certfile):
892 """
Alex Chand072cae2018-02-15 09:57:59 +0000893 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800894
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400895 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000896 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400897
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 :return: None
899 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400900 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800901
Alex Gaynor62da94d2015-09-05 14:37:34 -0400902 result = _lib.SSL_CTX_use_certificate_chain_file(
903 self._context, certfile
904 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800905 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500906 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800907
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800908 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 """
910 Load a certificate from a file
911
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400912 :param certfile: The name of the certificate file (``bytes`` or
913 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000914 :param filetype: (optional) The encoding of the file, which is either
915 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
916 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400917
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800918 :return: None
919 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400920 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500921 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800922 raise TypeError("filetype must be an integer")
923
Alex Gaynor62da94d2015-09-05 14:37:34 -0400924 use_result = _lib.SSL_CTX_use_certificate_file(
925 self._context, certfile, filetype
926 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800927 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500928 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800929
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800930 def use_certificate(self, cert):
931 """
932 Load a certificate from a X509 object
933
934 :param cert: The X509 object
935 :return: None
936 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800937 if not isinstance(cert, X509):
938 raise TypeError("cert must be an X509 instance")
939
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500940 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800941 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500942 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800943
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800944 def add_extra_chain_cert(self, certobj):
945 """
946 Add certificate to chain
947
948 :param certobj: The X509 certificate object to add to the chain
949 :return: None
950 """
951 if not isinstance(certobj, X509):
952 raise TypeError("certobj must be an X509 instance")
953
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500954 copy = _lib.X509_dup(certobj._x509)
955 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800956 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500957 # TODO: This is untested.
958 _lib.X509_free(copy)
959 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800961 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500962 if self._passphrase_helper is not None:
963 self._passphrase_helper.raise_if_problem(Error)
964
965 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800966
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400967 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800968 """
969 Load a private key from a file
970
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400971 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000972 :param filetype: (optional) The encoding of the file, which is either
973 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
974 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400975
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800976 :return: None
977 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400978 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400980 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800981 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500982 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983 raise TypeError("filetype must be an integer")
984
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500985 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986 self._context, keyfile, filetype)
987 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800988 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990 def use_privatekey(self, pkey):
991 """
992 Load a private key from a PKey object
993
994 :param pkey: The PKey object
995 :return: None
996 """
997 if not isinstance(pkey, PKey):
998 raise TypeError("pkey must be a PKey instance")
999
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001000 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001002 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001004 def check_privatekey(self):
1005 """
Alex Chand072cae2018-02-15 09:57:59 +00001006 Check if the private key (loaded with :meth:`use_privatekey`) matches
1007 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001008
Alex Chand072cae2018-02-15 09:57:59 +00001009 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001011 if not _lib.SSL_CTX_check_private_key(self._context):
1012 _raise_current_error()
1013
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014 def load_client_ca(self, cafile):
1015 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001016 Load the trusted certificates that will be sent to the client. Does
1017 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001018 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001019
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001020 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021 :return: None
1022 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001023 ca_list = _lib.SSL_load_client_CA_file(
1024 _text_to_bytes_and_warn("cafile", cafile)
1025 )
1026 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001027 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028
1029 def set_session_id(self, buf):
1030 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001031 Set the session id to *buf* within which a session can be reused for
1032 this Context object. This is needed when doing session resumption,
1033 because there is no way for a stored session to know which Context
1034 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001036 :param bytes buf: The session id.
1037
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038 :returns: None
1039 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001040 buf = _text_to_bytes_and_warn("buf", buf)
1041 _openssl_assert(
1042 _lib.SSL_CTX_set_session_id_context(
1043 self._context,
1044 buf,
1045 len(buf),
1046 ) == 1
1047 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001048
1049 def set_session_cache_mode(self, mode):
1050 """
Alex Chand072cae2018-02-15 09:57:59 +00001051 Set the behavior of the session cache used by all connections using
1052 this Context. The previously set mode is returned. See
1053 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054
1055 :param mode: One or more of the SESS_CACHE_* flags (combine using
1056 bitwise or)
1057 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001058
1059 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001060 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001061 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001062 raise TypeError("mode must be an integer")
1063
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001064 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066 def get_session_cache_mode(self):
1067 """
Alex Chand072cae2018-02-15 09:57:59 +00001068 Get the current session cache mode.
1069
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001071
1072 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076 def set_verify(self, mode, callback):
1077 """
Alex Chand072cae2018-02-15 09:57:59 +00001078 et the verification flags for this Context object to *mode* and specify
1079 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001080
Alex Chand072cae2018-02-15 09:57:59 +00001081 :param mode: The verify mode, this should be one of
1082 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1083 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1084 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1085 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1086 :param callback: The Python callback to use. This should take five
1087 arguments: A Connection object, an X509 object, and three integer
1088 variables, which are in turn potential error number, error depth
1089 and return code. *callback* should return True if verification
1090 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091 :return: None
1092
1093 See SSL_CTX_set_verify(3SSL) for further details.
1094 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001095 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096 raise TypeError("mode must be an integer")
1097
1098 if not callable(callback):
1099 raise TypeError("callback must be callable")
1100
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001101 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001102 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001103 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001104
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 def set_verify_depth(self, depth):
1106 """
Alex Chand072cae2018-02-15 09:57:59 +00001107 Set the maximum depth for the certificate chain verification that shall
1108 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109
1110 :param depth: An integer specifying the verify depth
1111 :return: None
1112 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001113 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001114 raise TypeError("depth must be an integer")
1115
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001116 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001117
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001118 def get_verify_mode(self):
1119 """
Alex Chand072cae2018-02-15 09:57:59 +00001120 Retrieve the Context object's verify mode, as set by
1121 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122
1123 :return: The verify mode
1124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001125 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001126
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127 def get_verify_depth(self):
1128 """
Alex Chand072cae2018-02-15 09:57:59 +00001129 Retrieve the Context object's verify depth, as set by
1130 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001131
1132 :return: The verify depth
1133 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001134 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001135
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001136 def load_tmp_dh(self, dhfile):
1137 """
1138 Load parameters for Ephemeral Diffie-Hellman
1139
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001140 :param dhfile: The file to load EDH parameters from (``bytes`` or
1141 ``unicode``).
1142
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143 :return: None
1144 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001145 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001146
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001147 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001149 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001150 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001151
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1153 dh = _ffi.gc(dh, _lib.DH_free)
1154 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001155
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001156 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001157 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001158 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001159
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001160 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001161 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1162 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001163
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001164 :return: None
1165 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001166 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001167
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001168 def set_cipher_list(self, cipher_list):
1169 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001170 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001171
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001172 See the OpenSSL manual for more information (e.g.
1173 :manpage:`ciphers(1)`).
1174
1175 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001176 :return: None
1177 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001178 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001179
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001180 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001181 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001182
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001183 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001184 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001185 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001186 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1187 # ciphers even if you pass an invalid cipher. Applications (like
1188 # Twisted) have tests that depend on an error being raised if an
1189 # invalid cipher string is passed, but without the following check
1190 # for the TLS 1.3 specific cipher suites it would never error.
1191 tmpconn = Connection(self, None)
Mark Williamsdf2480d2019-02-14 19:30:07 -08001192 if (
1193 tmpconn.get_cipher_list() == [
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001194 'TLS_AES_256_GCM_SHA384',
1195 'TLS_CHACHA20_POLY1305_SHA256',
1196 'TLS_AES_128_GCM_SHA256'
1197 ]
Mark Williamsdf2480d2019-02-14 19:30:07 -08001198 ):
1199 raise Error(
1200 [
1201 (
1202 'SSL routines',
1203 'SSL_CTX_set_cipher_list',
1204 'no cipher match',
1205 ),
1206 ],
1207 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001208
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001209 def set_client_ca_list(self, certificate_authorities):
1210 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001211 Set the list of preferred client certificate signers for this server
1212 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001213
Alex Gaynor62da94d2015-09-05 14:37:34 -04001214 This list of certificate authorities will be sent to the client when
1215 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001216
1217 :param certificate_authorities: a sequence of X509Names.
1218 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001219
1220 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001221 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001222 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001223 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001224
1225 try:
1226 for ca_name in certificate_authorities:
1227 if not isinstance(ca_name, X509Name):
1228 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001229 "client CAs must be X509Name objects, not %s "
1230 "objects" % (
1231 type(ca_name).__name__,
1232 )
1233 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001234 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001235 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001236 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001237 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001238 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001239 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001240 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001241 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001242 raise
1243
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001244 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001245
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001246 def add_client_ca(self, certificate_authority):
1247 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001248 Add the CA certificate to the list of preferred signers for this
1249 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001250
1251 The list of certificate authorities will be sent to the client when the
1252 server requests a client certificate.
1253
1254 :param certificate_authority: certificate authority's X509 certificate.
1255 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001256
1257 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001258 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001259 if not isinstance(certificate_authority, X509):
1260 raise TypeError("certificate_authority must be an X509 instance")
1261
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001262 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001263 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001264 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001265
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001266 def set_timeout(self, timeout):
1267 """
Alex Chand072cae2018-02-15 09:57:59 +00001268 Set the timeout for newly created sessions for this Context object to
1269 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1270 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001271
Alex Chand072cae2018-02-15 09:57:59 +00001272 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273 :return: The previous session timeout
1274 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001275 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001276 raise TypeError("timeout must be an integer")
1277
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001279
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001280 def get_timeout(self):
1281 """
Alex Chand072cae2018-02-15 09:57:59 +00001282 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1283 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001284
1285 :return: The session timeout
1286 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001288
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001289 def set_info_callback(self, callback):
1290 """
Alex Chand072cae2018-02-15 09:57:59 +00001291 Set the information callback to *callback*. This function will be
1292 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001293
Alex Chand072cae2018-02-15 09:57:59 +00001294 :param callback: The Python callback to use. This should take three
1295 arguments: a Connection object and two integers. The first integer
1296 specifies where in the SSL handshake the function was called, and
1297 the other the return code from a (possibly failed) internal
1298 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001299 :return: None
1300 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001301 @wraps(callback)
1302 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001303 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001304 self._info_callback = _ffi.callback(
1305 "void (*)(const SSL *, int, int)", wrapper)
1306 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001307
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001308 def get_app_data(self):
1309 """
Alex Chand072cae2018-02-15 09:57:59 +00001310 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001311
1312 :return: The application data
1313 """
1314 return self._app_data
1315
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001316 def set_app_data(self, data):
1317 """
1318 Set the application data (will be returned from get_app_data())
1319
1320 :param data: Any Python object
1321 :return: None
1322 """
1323 self._app_data = data
1324
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001325 def get_cert_store(self):
1326 """
Alex Chand072cae2018-02-15 09:57:59 +00001327 Get the certificate store for the context. This can be used to add
1328 "trusted" certificates without using the
1329 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001330
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001331 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001332 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001333 store = _lib.SSL_CTX_get_cert_store(self._context)
1334 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001335 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001336 return None
1337
1338 pystore = X509Store.__new__(X509Store)
1339 pystore._store = store
1340 return pystore
1341
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001342 def set_options(self, options):
1343 """
1344 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001345 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001346
1347 :param options: The options to add.
1348 :return: The new option bitmask.
1349 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001350 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001351 raise TypeError("options must be an integer")
1352
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001353 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001354
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001355 def set_mode(self, mode):
1356 """
Alex Chand072cae2018-02-15 09:57:59 +00001357 Add modes via bitmask. Modes set before are not cleared! This method
1358 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001359
1360 :param mode: The mode to add.
1361 :return: The new mode bitmask.
1362 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001363 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001364 raise TypeError("mode must be an integer")
1365
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001366 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001367
Cory Benfielde6f35882016-03-29 11:21:04 +01001368 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001369 def set_tlsext_servername_callback(self, callback):
1370 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001371 Specify a callback function to be called when clients specify a server
1372 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001373
1374 :param callback: The callback function. It will be invoked with one
1375 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001376
1377 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001378 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001379 @wraps(callback)
1380 def wrapper(ssl, alert, arg):
1381 callback(Connection._reverse_mapping[ssl])
1382 return 0
1383
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001384 self._tlsext_servername_callback = _ffi.callback(
David Benjamince5c3842018-05-21 21:14:46 -04001385 "int (*)(SSL *, int *, void *)", wrapper)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001386 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001387 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001388
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001389 def set_tlsext_use_srtp(self, profiles):
1390 """
1391 Enable support for negotiating SRTP keying material.
1392
1393 :param bytes profiles: A colon delimited list of protection profile
1394 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1395 :return: None
1396 """
1397 if not isinstance(profiles, bytes):
1398 raise TypeError("profiles must be a byte string.")
1399
1400 _openssl_assert(
1401 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1402 )
1403
Cory Benfield10b277f2015-04-13 17:12:42 -04001404 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001405 def set_npn_advertise_callback(self, callback):
1406 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001407 Specify a callback function that will be called when offering `Next
1408 Protocol Negotiation
1409 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001410
1411 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001412 argument, the :class:`Connection` instance. It should return a
1413 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001414 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001415
1416 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001417 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001418 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1419 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001420 _lib.SSL_CTX_set_next_protos_advertised_cb(
1421 self._context, self._npn_advertise_callback, _ffi.NULL)
1422
Cory Benfield10b277f2015-04-13 17:12:42 -04001423 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001424 def set_npn_select_callback(self, callback):
1425 """
1426 Specify a callback function that will be called when a server offers
1427 Next Protocol Negotiation options.
1428
1429 :param callback: The callback function. It will be invoked with two
1430 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001431 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1432 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001433
1434 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001435 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001436 self._npn_select_helper = _NpnSelectHelper(callback)
1437 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001438 _lib.SSL_CTX_set_next_proto_select_cb(
1439 self._context, self._npn_select_callback, _ffi.NULL)
1440
Cory Benfield7907e332015-04-13 17:18:25 -04001441 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001442 def set_alpn_protos(self, protos):
1443 """
Alex Chand072cae2018-02-15 09:57:59 +00001444 Specify the protocols that the client is prepared to speak after the
1445 TLS connection has been negotiated using Application Layer Protocol
1446 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001447
1448 :param protos: A list of the protocols to be offered to the server.
1449 This list should be a Python list of bytestrings representing the
1450 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1451 """
1452 # Take the list of protocols and join them together, prefixing them
1453 # with their lengths.
1454 protostr = b''.join(
1455 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1456 )
1457
1458 # Build a C string from the list. We don't need to save this off
1459 # because OpenSSL immediately copies the data out.
1460 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001461 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001462
Cory Benfield7907e332015-04-13 17:18:25 -04001463 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001464 def set_alpn_select_callback(self, callback):
1465 """
Alex Chand072cae2018-02-15 09:57:59 +00001466 Specify a callback function that will be called on the server when a
1467 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001468
1469 :param callback: The callback function. It will be invoked with two
1470 arguments: the Connection, and a list of offered protocols as
1471 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001472 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001473 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001474 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001475 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001476 _lib.SSL_CTX_set_alpn_select_cb(
1477 self._context, self._alpn_select_callback, _ffi.NULL)
1478
Cory Benfield496652a2017-01-24 11:42:56 +00001479 def _set_ocsp_callback(self, helper, data):
1480 """
1481 This internal helper does the common work for
1482 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1483 almost all of it.
1484 """
1485 self._ocsp_helper = helper
1486 self._ocsp_callback = helper.callback
1487 if data is None:
1488 self._ocsp_data = _ffi.NULL
1489 else:
1490 self._ocsp_data = _ffi.new_handle(data)
1491
1492 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1493 self._context, self._ocsp_callback
1494 )
1495 _openssl_assert(rc == 1)
1496 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1497 _openssl_assert(rc == 1)
1498
1499 def set_ocsp_server_callback(self, callback, data=None):
1500 """
1501 Set a callback to provide OCSP data to be stapled to the TLS handshake
1502 on the server side.
1503
1504 :param callback: The callback function. It will be invoked with two
1505 arguments: the Connection, and the optional arbitrary data you have
1506 provided. The callback must return a bytestring that contains the
1507 OCSP data to staple to the handshake. If no OCSP data is available
1508 for this connection, return the empty bytestring.
1509 :param data: Some opaque data that will be passed into the callback
1510 function when called. This can be used to avoid needing to do
1511 complex data lookups or to keep track of what context is being
1512 used. This parameter is optional.
1513 """
1514 helper = _OCSPServerCallbackHelper(callback)
1515 self._set_ocsp_callback(helper, data)
1516
1517 def set_ocsp_client_callback(self, callback, data=None):
1518 """
1519 Set a callback to validate OCSP data stapled to the TLS handshake on
1520 the client side.
1521
1522 :param callback: The callback function. It will be invoked with three
1523 arguments: the Connection, a bytestring containing the stapled OCSP
1524 assertion, and the optional arbitrary data you have provided. The
1525 callback must return a boolean that indicates the result of
1526 validating the OCSP data: ``True`` if the OCSP data is valid and
1527 the certificate can be trusted, or ``False`` if either the OCSP
1528 data is invalid or the certificate has been revoked.
1529 :param data: Some opaque data that will be passed into the callback
1530 function when called. This can be used to avoid needing to do
1531 complex data lookups or to keep track of what context is being
1532 used. This parameter is optional.
1533 """
1534 helper = _OCSPClientCallbackHelper(callback)
1535 self._set_ocsp_callback(helper, data)
1536
Alex Chanc6077062016-11-18 13:53:39 +00001537
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001538class Connection(object):
1539 """
1540 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001541 _reverse_mapping = WeakValueDictionary()
1542
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001543 def __init__(self, context, socket=None):
1544 """
1545 Create a new Connection object, using the given OpenSSL.SSL.Context
1546 instance and socket.
1547
1548 :param context: An SSL Context to use for this connection
1549 :param socket: The socket to use for transport layer
1550 """
1551 if not isinstance(context, Context):
1552 raise TypeError("context must be a Context instance")
1553
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001554 ssl = _lib.SSL_new(context._context)
1555 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001556 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1557 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1558 # even though there is still data on the underlying transport.
1559 # See https://github.com/openssl/openssl/issues/6234 for more details.
1560 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001561 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001562 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001563
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001564 # References to strings used for Next Protocol Negotiation. OpenSSL's
1565 # header files suggest that these might get copied at some point, but
1566 # doesn't specify when, so we store them here to make sure they don't
1567 # get freed before OpenSSL uses them.
1568 self._npn_advertise_callback_args = None
1569 self._npn_select_callback_args = None
1570
Cory Benfield12eae892014-06-07 15:42:56 +01001571 # References to strings used for Application Layer Protocol
1572 # Negotiation. These strings get copied at some point but it's well
1573 # after the callback returns, so we have to hang them somewhere to
1574 # avoid them getting freed.
1575 self._alpn_select_callback_args = None
1576
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578
1579 if socket is None:
1580 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001581 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001582 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001583 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001584
Alex Gaynora829e902016-06-04 18:16:01 -07001585 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1586 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001588 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001589 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001590 self._into_ssl = None
1591 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001592 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001593 set_result = _lib.SSL_set_fd(
1594 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001595 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597 def __getattr__(self, name):
1598 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001599 Look up attributes on the wrapped socket object if they are not found
1600 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001601 """
kjav0b66fa12015-09-02 11:51:26 +01001602 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001603 raise AttributeError("'%s' object has no attribute '%s'" % (
1604 self.__class__.__name__, name
1605 ))
kjav0b66fa12015-09-02 11:51:26 +01001606 else:
1607 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001609 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001610 if self._context._verify_helper is not None:
1611 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001612 if self._context._npn_advertise_helper is not None:
1613 self._context._npn_advertise_helper.raise_if_problem()
1614 if self._context._npn_select_helper is not None:
1615 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001616 if self._context._alpn_select_helper is not None:
1617 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001618 if self._context._ocsp_helper is not None:
1619 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001620
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001621 error = _lib.SSL_get_error(ssl, result)
1622 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001623 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001624 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001625 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001626 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001627 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001629 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001630 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001631 elif error == _lib.SSL_ERROR_SYSCALL:
1632 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001633 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001634 if platform == "win32":
1635 errno = _ffi.getwinerror()[0]
1636 else:
1637 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001638
1639 if errno != 0:
1640 raise SysCallError(errno, errorcode.get(errno))
1641 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001642 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001643 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001644 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001645 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001646 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001647 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001648 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001649
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650 def get_context(self):
1651 """
Alex Chand072cae2018-02-15 09:57:59 +00001652 Retrieve the :class:`Context` object associated with this
1653 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001655 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001658 """
Alex Chand072cae2018-02-15 09:57:59 +00001659 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001660
Alex Chand072cae2018-02-15 09:57:59 +00001661 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 if not isinstance(context, Context):
1665 raise TypeError("context must be a Context instance")
1666
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001667 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001668 self._context = context
1669
Cory Benfielde6f35882016-03-29 11:21:04 +01001670 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671 def get_servername(self):
1672 """
1673 Retrieve the servername extension value if provided in the client hello
1674 message, or None if there wasn't one.
1675
Alex Chand072cae2018-02-15 09:57:59 +00001676 :return: A byte string giving the server name or :data:`None`.
1677
1678 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001680 name = _lib.SSL_get_servername(
1681 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1682 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001683 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001684 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001685
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001686 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687
Cory Benfielde6f35882016-03-29 11:21:04 +01001688 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001689 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001690 """
1691 Set the value of the servername extension to send in the client hello.
1692
1693 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001694
1695 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001697 if not isinstance(name, bytes):
1698 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001699 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001700 raise TypeError("name must not contain NUL byte")
1701
1702 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001704
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705 def pending(self):
1706 """
Alex Chand072cae2018-02-15 09:57:59 +00001707 Get the number of bytes that can be safely read from the SSL buffer
1708 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001709
1710 :return: The number of bytes available in the receive buffer.
1711 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001712 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001713
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001714 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715 """
1716 Send data on the connection. NOTE: If you get one of the WantRead,
1717 WantWrite or WantX509Lookup exceptions on this, you have to call the
1718 method again with the SAME buffer.
1719
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001720 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721 :param flags: (optional) Included for compatibility with the socket
1722 API, the value is ignored
1723 :return: The number of bytes written
1724 """
Abraham Martine82326c2015-02-04 10:18:10 +00001725 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001726 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001727
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001728 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001729 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001730 if isinstance(buf, _buffer):
1731 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001732 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001733 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001734 if len(buf) > 2147483647:
1735 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001736
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001737 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001738 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001739 return result
1740 write = send
1741
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001743 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001744 Send "all" data on the connection. This calls send() repeatedly until
1745 all data is sent. If an error occurs, it's impossible to tell how much
1746 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001747
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001748 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749 :param flags: (optional) Included for compatibility with the socket
1750 API, the value is ignored
1751 :return: The number of bytes written
1752 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001753 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001754
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001755 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001756 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001757 if isinstance(buf, _buffer):
1758 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001759 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001760 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761
1762 left_to_send = len(buf)
1763 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001764 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001765
1766 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001767 # SSL_write's num arg is an int,
1768 # so we cannot send more than 2**31-1 bytes at once.
1769 result = _lib.SSL_write(
1770 self._ssl,
1771 data + total_sent,
1772 min(left_to_send, 2147483647)
1773 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001774 self._raise_ssl_error(self._ssl, result)
1775 total_sent += result
1776 left_to_send -= result
1777
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001778 def recv(self, bufsiz, flags=None):
1779 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001780 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001781
1782 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001783 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1784 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001785 :return: The string read from the Connection
1786 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001787 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001788 if flags is not None and flags & socket.MSG_PEEK:
1789 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1790 else:
1791 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001792 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001793 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 read = recv
1795
Cory Benfield62d10332014-06-15 10:03:41 +01001796 def recv_into(self, buffer, nbytes=None, flags=None):
1797 """
Alex Chand072cae2018-02-15 09:57:59 +00001798 Receive data on the connection and copy it directly into the provided
1799 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001800
1801 :param buffer: The buffer to copy into.
1802 :param nbytes: (optional) The maximum number of bytes to read into the
1803 buffer. If not present, defaults to the size of the buffer. If
1804 larger than the size of the buffer, is reduced to the size of the
1805 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001806 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1807 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001808 :return: The number of bytes read into the buffer.
1809 """
1810 if nbytes is None:
1811 nbytes = len(buffer)
1812 else:
1813 nbytes = min(nbytes, len(buffer))
1814
1815 # We need to create a temporary buffer. This is annoying, it would be
1816 # better if we could pass memoryviews straight into the SSL_read call,
1817 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001818 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001819 if flags is not None and flags & socket.MSG_PEEK:
1820 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1821 else:
1822 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001823 self._raise_ssl_error(self._ssl, result)
1824
1825 # This strange line is all to avoid a memory copy. The buffer protocol
1826 # should allow us to assign a CFFI buffer to the LHS of this line, but
1827 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001828 # wrap it in a memoryview.
1829 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001830
1831 return result
1832
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001833 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001834 if _lib.BIO_should_retry(bio):
1835 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001836 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001837 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001838 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001839 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001840 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001841 # TODO: This is untested. I think io_special means the socket
1842 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001843 raise ValueError("BIO_should_io_special")
1844 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001845 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001846 raise ValueError("unknown bio failure")
1847 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001848 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001849 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001850
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001851 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001852 """
Alex Chand072cae2018-02-15 09:57:59 +00001853 If the Connection was created with a memory BIO, this method can be
1854 used to read bytes from the write end of that memory BIO. Many
1855 Connection methods will add bytes which must be read in this manner or
1856 the buffer will eventually fill up and the Connection will be able to
1857 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001858
1859 :param bufsiz: The maximum number of bytes to read
1860 :return: The string read.
1861 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001862 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001863 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001864
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001865 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001866 raise TypeError("bufsiz must be an integer")
1867
Cory Benfielde62840e2016-11-28 12:17:08 +00001868 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001869 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001870 if result <= 0:
1871 self._handle_bio_errors(self._from_ssl, result)
1872
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001873 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001874
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001875 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001876 """
Alex Chand072cae2018-02-15 09:57:59 +00001877 If the Connection was created with a memory BIO, this method can be
1878 used to add bytes to the read end of that memory BIO. The Connection
1879 can then read the bytes (for example, in response to a call to
1880 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881
1882 :param buf: The string to put into the memory BIO.
1883 :return: The number of bytes written
1884 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001885 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001886
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001887 if self._into_ssl is None:
1888 raise TypeError("Connection sock was not None")
1889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001890 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891 if result <= 0:
1892 self._handle_bio_errors(self._into_ssl, result)
1893 return result
1894
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001895 def renegotiate(self):
1896 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001897 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001899 :return: True if the renegotiation can be started, False otherwise
1900 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001901 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001902 if not self.renegotiate_pending():
1903 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1904 return True
1905 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906
1907 def do_handshake(self):
1908 """
Alex Chand072cae2018-02-15 09:57:59 +00001909 Perform an SSL handshake (usually called after :meth:`renegotiate` or
1910 one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
1911 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912
1913 :return: None.
1914 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001915 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001918 def renegotiate_pending(self):
1919 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001920 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 a renegotiation is finished.
1922
1923 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001924 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001925 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001926 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001927
1928 def total_renegotiations(self):
1929 """
1930 Find out the total number of renegotiations.
1931
1932 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001933 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001935 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001937 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001938 """
Alex Chand072cae2018-02-15 09:57:59 +00001939 Call the :meth:`connect` method of the underlying socket and set up SSL
1940 on the socket, using the :class:`Context` object supplied to this
1941 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001942
1943 :param addr: A remote address
1944 :return: What the socket's connect method returns
1945 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001946 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001947 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001948
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001949 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001950 """
Alex Chand072cae2018-02-15 09:57:59 +00001951 Call the :meth:`connect_ex` method of the underlying socket and set up
1952 SSL on the socket, using the Context object supplied to this Connection
1953 object at creation. Note that if the :meth:`connect_ex` method of the
1954 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001955
1956 :param addr: A remove address
1957 :return: What the socket's connect_ex method returns
1958 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001959 connect_ex = self._socket.connect_ex
1960 self.set_connect_state()
1961 return connect_ex(addr)
1962
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001963 def accept(self):
1964 """
Alex Chand072cae2018-02-15 09:57:59 +00001965 Call the :meth:`accept` method of the underlying socket and set up SSL
1966 on the returned socket, using the Context object supplied to this
1967 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968
Alex Chand072cae2018-02-15 09:57:59 +00001969 :return: A *(conn, addr)* pair where *conn* is the new
1970 :class:`Connection` object created, and *address* is as returned by
1971 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001972 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001973 client, addr = self._socket.accept()
1974 conn = Connection(self._context, client)
1975 conn.set_accept_state()
1976 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001977
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001978 def bio_shutdown(self):
1979 """
Alex Chand072cae2018-02-15 09:57:59 +00001980 If the Connection was created with a memory BIO, this method can be
1981 used to indicate that *end of file* has been reached on the read end of
1982 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983
1984 :return: None
1985 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001986 if self._from_ssl is None:
1987 raise TypeError("Connection sock was not None")
1988
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001989 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001990
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001991 def shutdown(self):
1992 """
Alex Chand072cae2018-02-15 09:57:59 +00001993 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994
1995 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001996 have sent closure alerts), False otherwise (in which case you
1997 call :meth:`recv` or :meth:`send` when the connection becomes
1998 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002000 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002002 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002004 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005 else:
2006 return False
2007
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008 def get_cipher_list(self):
2009 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002010 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002012 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 """
2014 ciphers = []
2015 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002016 result = _lib.SSL_get_cipher_list(self._ssl, i)
2017 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002019 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020 return ciphers
2021
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002022 def get_client_ca_list(self):
2023 """
2024 Get CAs whose certificates are suggested for client authentication.
2025
Alex Chand072cae2018-02-15 09:57:59 +00002026 :return: If this is a server connection, the list of certificate
2027 authorities that will be sent or has been sent to the client, as
2028 controlled by this :class:`Connection`'s :class:`Context`.
2029
2030 If this is a client connection, the list will be empty until the
2031 connection with the server is established.
2032
2033 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002034 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002035 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2036 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002037 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002038 return []
2039
2040 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002041 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2042 name = _lib.sk_X509_NAME_value(ca_names, i)
2043 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002044 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002045
2046 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002047 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002048 result.append(pyname)
2049 return result
2050
Aykee7f33452018-05-16 19:18:16 +02002051 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002053 The makefile() method is not implemented, since there is no dup
2054 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002056 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002057 """
Alex Gaynor83284952015-09-05 10:43:30 -04002058 raise NotImplementedError(
2059 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002060
2061 def get_app_data(self):
2062 """
Alex Chand072cae2018-02-15 09:57:59 +00002063 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002064
2065 :return: The application data
2066 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002067 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002068
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002069 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002070 """
2071 Set application data
2072
Alex Chand072cae2018-02-15 09:57:59 +00002073 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002074 :return: None
2075 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002076 self._app_data = data
2077
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002078 def get_shutdown(self):
2079 """
Alex Chand072cae2018-02-15 09:57:59 +00002080 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002081
Alex Gaynor62da94d2015-09-05 14:37:34 -04002082 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2083 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002084 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002085 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002087 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002088 """
Alex Chand072cae2018-02-15 09:57:59 +00002089 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002090
Alex Chand072cae2018-02-15 09:57:59 +00002091 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002092 :return: None
2093 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002094 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002095 raise TypeError("state must be an integer")
2096
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002097 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002098
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002099 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002100 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002101 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
2103 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002104 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002105 """
kjavc704a2e2015-09-07 12:12:27 +01002106 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002107
2108 def server_random(self):
2109 """
Alex Chand072cae2018-02-15 09:57:59 +00002110 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002111
2112 :return: A string representing the state
2113 """
Alex Gaynor93603062016-06-01 20:13:09 -07002114 session = _lib.SSL_get_session(self._ssl)
2115 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002116 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002117 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2118 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002119 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002120 _lib.SSL_get_server_random(self._ssl, outp, length)
2121 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002122
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123 def client_random(self):
2124 """
Alex Chand072cae2018-02-15 09:57:59 +00002125 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002126
2127 :return: A string representing the state
2128 """
Alex Gaynor93603062016-06-01 20:13:09 -07002129 session = _lib.SSL_get_session(self._ssl)
2130 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002131 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002132
2133 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2134 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002135 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002136 _lib.SSL_get_client_random(self._ssl, outp, length)
2137 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002138
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002139 def master_key(self):
2140 """
Alex Chand072cae2018-02-15 09:57:59 +00002141 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002142
2143 :return: A string representing the state
2144 """
Alex Gaynor93603062016-06-01 20:13:09 -07002145 session = _lib.SSL_get_session(self._ssl)
2146 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002147 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002148
2149 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2150 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002151 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002152 _lib.SSL_SESSION_get_master_key(session, outp, length)
2153 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002154
Paul Kehrerbdb76392017-12-01 04:54:32 +08002155 def export_keying_material(self, label, olen, context=None):
2156 """
2157 Obtain keying material for application use.
2158
Alex Chand072cae2018-02-15 09:57:59 +00002159 :param: label - a disambiguating label string as described in RFC 5705
2160 :param: olen - the length of the exported key material in bytes
2161 :param: context - a per-association context value
2162 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002163 """
2164 outp = _no_zero_allocator("unsigned char[]", olen)
2165 context_buf = _ffi.NULL
2166 context_len = 0
2167 use_context = 0
2168 if context is not None:
2169 context_buf = context
2170 context_len = len(context)
2171 use_context = 1
2172 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2173 label, len(label),
2174 context_buf, context_len,
2175 use_context)
2176 _openssl_assert(success == 1)
2177 return _ffi.buffer(outp, olen)[:]
2178
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002179 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002180 """
Alex Chand072cae2018-02-15 09:57:59 +00002181 Call the :meth:`shutdown` method of the underlying socket.
2182 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002183
2184 :return: What the socket's shutdown() method returns
2185 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002186 return self._socket.shutdown(*args, **kwargs)
2187
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002188 def get_certificate(self):
2189 """
2190 Retrieve the local certificate (if any)
2191
2192 :return: The local certificate
2193 """
2194 cert = _lib.SSL_get_certificate(self._ssl)
2195 if cert != _ffi.NULL:
2196 _lib.X509_up_ref(cert)
2197 return X509._from_raw_x509_ptr(cert)
2198 return None
2199
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002200 def get_peer_certificate(self):
2201 """
2202 Retrieve the other side's certificate (if any)
2203
2204 :return: The peer's certificate
2205 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002206 cert = _lib.SSL_get_peer_certificate(self._ssl)
2207 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002208 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002209 return None
2210
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002211 def get_peer_cert_chain(self):
2212 """
2213 Retrieve the other side's certificate (if any)
2214
2215 :return: A list of X509 instances giving the peer's certificate chain,
2216 or None if it does not have one.
2217 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002218 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2219 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002220 return None
2221
2222 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002224 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002225 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002226 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002227 result.append(pycert)
2228 return result
2229
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002230 def want_read(self):
2231 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002232 Checks if more data has to be read from the transport layer to complete
2233 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002234
2235 :return: True iff more data has to be read
2236 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002237 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002238
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002239 def want_write(self):
2240 """
2241 Checks if there is data to write to the transport layer to complete an
2242 operation.
2243
2244 :return: True iff there is data to write
2245 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002246 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002247
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002248 def set_accept_state(self):
2249 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002250 Set the connection to work in server mode. The handshake will be
2251 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002252
2253 :return: None
2254 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002255 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002256
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002257 def set_connect_state(self):
2258 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002259 Set the connection to work in client mode. The handshake will be
2260 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002261
2262 :return: None
2263 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002264 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002265
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002266 def get_session(self):
2267 """
2268 Returns the Session currently used.
2269
Alex Chand072cae2018-02-15 09:57:59 +00002270 :return: An instance of :class:`OpenSSL.SSL.Session` or
2271 :obj:`None` if no session exists.
2272
2273 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002274 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002275 session = _lib.SSL_get1_session(self._ssl)
2276 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002277 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002278
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002279 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002280 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002281 return pysession
2282
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002283 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002284 """
2285 Set the session to be used when the TLS/SSL connection is established.
2286
2287 :param session: A Session instance representing the session to use.
2288 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002289
2290 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002291 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002292 if not isinstance(session, Session):
2293 raise TypeError("session must be a Session instance")
2294
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002295 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002296 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002297 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002298
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002299 def _get_finished_message(self, function):
2300 """
Alex Chand072cae2018-02-15 09:57:59 +00002301 Helper to implement :meth:`get_finished` and
2302 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002303
Alex Chand072cae2018-02-15 09:57:59 +00002304 :param function: Either :data:`SSL_get_finished`: or
2305 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002306
Alex Chand072cae2018-02-15 09:57:59 +00002307 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002308 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002309 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002310 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002311 # The OpenSSL documentation says nothing about what might happen if the
2312 # count argument given is zero. Specifically, it doesn't say whether
2313 # the output buffer may be NULL in that case or not. Inspection of the
2314 # implementation reveals that it calls memcpy() unconditionally.
2315 # Section 7.1.4, paragraph 1 of the C standard suggests that
2316 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2317 # alone desirable) behavior (though it probably does on just about
2318 # every implementation...)
2319 #
2320 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2321 # one might expect) for the initial call so as to be safe against this
2322 # potentially undefined behavior.
2323 empty = _ffi.new("char[]", 0)
2324 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002325 if size == 0:
2326 # No Finished message so far.
2327 return None
2328
Cory Benfielde62840e2016-11-28 12:17:08 +00002329 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002330 function(self._ssl, buf, size)
2331 return _ffi.buffer(buf, size)[:]
2332
Fedor Brunner5747b932014-03-05 14:22:34 +01002333 def get_finished(self):
2334 """
Alex Chand072cae2018-02-15 09:57:59 +00002335 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002336
Alex Chand072cae2018-02-15 09:57:59 +00002337 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002338 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002339 :rtype: :class:`bytes` or :class:`NoneType`
2340
2341 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002342 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002343 return self._get_finished_message(_lib.SSL_get_finished)
2344
Fedor Brunner5747b932014-03-05 14:22:34 +01002345 def get_peer_finished(self):
2346 """
Alex Chand072cae2018-02-15 09:57:59 +00002347 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002348
Alex Chand072cae2018-02-15 09:57:59 +00002349 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002350 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002351 :rtype: :class:`bytes` or :class:`NoneType`
2352
2353 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002354 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002355 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002356
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002357 def get_cipher_name(self):
2358 """
2359 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002360
Alex Chand072cae2018-02-15 09:57:59 +00002361 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002362 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002363 :rtype: :class:`unicode` or :class:`NoneType`
2364
2365 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002366 """
2367 cipher = _lib.SSL_get_current_cipher(self._ssl)
2368 if cipher == _ffi.NULL:
2369 return None
2370 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002371 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2372 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002373
2374 def get_cipher_bits(self):
2375 """
2376 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002377
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002378 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002379 or :obj:`None` if no connection has been established.
2380 :rtype: :class:`int` or :class:`NoneType`
2381
2382 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002383 """
2384 cipher = _lib.SSL_get_current_cipher(self._ssl)
2385 if cipher == _ffi.NULL:
2386 return None
2387 else:
2388 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2389
2390 def get_cipher_version(self):
2391 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002392 Obtain the protocol version of the currently used cipher.
2393
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002394 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002395 or :obj:`None` if no connection has been established.
2396 :rtype: :class:`unicode` or :class:`NoneType`
2397
2398 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002399 """
2400 cipher = _lib.SSL_get_current_cipher(self._ssl)
2401 if cipher == _ffi.NULL:
2402 return None
2403 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002404 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002405 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002406
Jim Shaverabff1882015-05-27 09:15:55 -04002407 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002408 """
Alex Chand072cae2018-02-15 09:57:59 +00002409 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002410
2411 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002412 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002413 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002414 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002415 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002416 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002417 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002418
Jim Shaver208438c2015-05-28 09:52:38 -04002419 def get_protocol_version(self):
2420 """
Alex Chand072cae2018-02-15 09:57:59 +00002421 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002422
Alex Chand072cae2018-02-15 09:57:59 +00002423 :returns: The TLS version of the current connection. For example,
2424 it will return ``0x769`` for connections made over TLS version 1.
2425 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002426 """
2427 version = _lib.SSL_version(self._ssl)
2428 return version
2429
Cory Benfield10b277f2015-04-13 17:12:42 -04002430 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002431 def get_next_proto_negotiated(self):
2432 """
2433 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002434
2435 :returns: A bytestring of the protocol name. If no protocol has been
2436 negotiated yet, returns an empty string.
2437
2438 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002439 """
2440 data = _ffi.new("unsigned char **")
2441 data_len = _ffi.new("unsigned int *")
2442
2443 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2444
Cory Benfieldcd010f62014-05-15 19:00:27 +01002445 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002446
Cory Benfield7907e332015-04-13 17:18:25 -04002447 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002448 def set_alpn_protos(self, protos):
2449 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002450 Specify the client's ALPN protocol list.
2451
2452 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002453
2454 :param protos: A list of the protocols to be offered to the server.
2455 This list should be a Python list of bytestrings representing the
2456 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2457 """
2458 # Take the list of protocols and join them together, prefixing them
2459 # with their lengths.
2460 protostr = b''.join(
2461 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2462 )
2463
2464 # Build a C string from the list. We don't need to save this off
2465 # because OpenSSL immediately copies the data out.
2466 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002467 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002468
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002469 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002470 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002471 """
2472 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002473
2474 :returns: A bytestring of the protocol name. If no protocol has been
2475 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002476 """
Cory Benfield12eae892014-06-07 15:42:56 +01002477 data = _ffi.new("unsigned char **")
2478 data_len = _ffi.new("unsigned int *")
2479
2480 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2481
Cory Benfielde8e9c382015-04-11 17:33:48 -04002482 if not data_len:
2483 return b''
2484
Cory Benfield12eae892014-06-07 15:42:56 +01002485 return _ffi.buffer(data[0], data_len[0])[:]
2486
Cory Benfield496652a2017-01-24 11:42:56 +00002487 def request_ocsp(self):
2488 """
2489 Called to request that the server sends stapled OCSP data, if
2490 available. If this is not called on the client side then the server
2491 will not send OCSP data. Should be used in conjunction with
2492 :meth:`Context.set_ocsp_client_callback`.
2493 """
2494 rc = _lib.SSL_set_tlsext_status_type(
2495 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2496 )
2497 _openssl_assert(rc == 1)
2498
Cory Benfield12eae892014-06-07 15:42:56 +01002499
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002500# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2501# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002502_lib.SSL_library_init()