blob: 5def0aae817140f25f76ebb55b29d846ab09d1a2 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Nicolas Karolak736c6212017-11-26 14:40:28 +010030__all__ = [
31 'OPENSSL_VERSION_NUMBER',
32 'SSLEAY_VERSION',
33 'SSLEAY_CFLAGS',
34 'SSLEAY_PLATFORM',
35 'SSLEAY_DIR',
36 'SSLEAY_BUILT_ON',
37 'SENT_SHUTDOWN',
38 'RECEIVED_SHUTDOWN',
39 'SSLv2_METHOD',
40 'SSLv3_METHOD',
41 'SSLv23_METHOD',
42 'TLSv1_METHOD',
43 'TLSv1_1_METHOD',
44 'TLSv1_2_METHOD',
45 'OP_NO_SSLv2',
46 'OP_NO_SSLv3',
47 'OP_NO_TLSv1',
48 'OP_NO_TLSv1_1',
49 'OP_NO_TLSv1_2',
50 'MODE_RELEASE_BUFFERS',
51 'OP_SINGLE_DH_USE',
52 'OP_SINGLE_ECDH_USE',
53 'OP_EPHEMERAL_RSA',
54 'OP_MICROSOFT_SESS_ID_BUG',
55 'OP_NETSCAPE_CHALLENGE_BUG',
56 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
57 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
58 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
59 'OP_MSIE_SSLV2_RSA_PADDING',
60 'OP_SSLEAY_080_CLIENT_DH_BUG',
61 'OP_TLS_D5_BUG',
62 'OP_TLS_BLOCK_PADDING_BUG',
63 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
64 'OP_CIPHER_SERVER_PREFERENCE',
65 'OP_TLS_ROLLBACK_BUG',
66 'OP_PKCS1_CHECK_1',
67 'OP_PKCS1_CHECK_2',
68 'OP_NETSCAPE_CA_DN_BUG',
69 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
70 'OP_NO_COMPRESSION',
71 'OP_NO_QUERY_MTU',
72 'OP_COOKIE_EXCHANGE',
73 'OP_NO_TICKET',
74 'OP_ALL',
75 'VERIFY_PEER',
76 'VERIFY_FAIL_IF_NO_PEER_CERT',
77 'VERIFY_CLIENT_ONCE',
78 'VERIFY_NONE',
79 'SESS_CACHE_OFF',
80 'SESS_CACHE_CLIENT',
81 'SESS_CACHE_SERVER',
82 'SESS_CACHE_BOTH',
83 'SESS_CACHE_NO_AUTO_CLEAR',
84 'SESS_CACHE_NO_INTERNAL_LOOKUP',
85 'SESS_CACHE_NO_INTERNAL_STORE',
86 'SESS_CACHE_NO_INTERNAL',
87 'SSL_ST_CONNECT',
88 'SSL_ST_ACCEPT',
89 'SSL_ST_MASK',
90 'SSL_ST_INIT',
91 'SSL_ST_BEFORE',
92 'SSL_ST_OK',
93 'SSL_ST_RENEGOTIATE',
94 'SSL_CB_LOOP',
95 'SSL_CB_EXIT',
96 'SSL_CB_READ',
97 'SSL_CB_WRITE',
98 'SSL_CB_ALERT',
99 'SSL_CB_READ_ALERT',
100 'SSL_CB_WRITE_ALERT',
101 'SSL_CB_ACCEPT_LOOP',
102 'SSL_CB_ACCEPT_EXIT',
103 'SSL_CB_CONNECT_LOOP',
104 'SSL_CB_CONNECT_EXIT',
105 'SSL_CB_HANDSHAKE_START',
106 'SSL_CB_HANDSHAKE_DONE',
107 'Error',
108 'WantReadError',
109 'WantWriteError',
110 'WantX509LookupError',
111 'ZeroReturnError',
112 'SysCallError',
113 'SSLeay_version',
114 'Session',
115 'Context',
116 'Connection'
117]
118
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500119try:
120 _memoryview = memoryview
121except NameError:
122 class _memoryview(object):
123 pass
124
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200125try:
126 _buffer = buffer
127except NameError:
128 class _buffer(object):
129 pass
130
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500131OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
132SSLEAY_VERSION = _lib.SSLEAY_VERSION
133SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
134SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
135SSLEAY_DIR = _lib.SSLEAY_DIR
136SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500138SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
139RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800140
141SSLv2_METHOD = 1
142SSLv3_METHOD = 2
143SSLv23_METHOD = 3
144TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500145TLSv1_1_METHOD = 5
146TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800147
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500148OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
149OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
150OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700151OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
152OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800153
Alex Gaynorbf012872016-06-04 13:18:39 -0700154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
Alex Gaynorbf012872016-06-04 13:18:39 -0700179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800184
Alex Gaynorc4889812015-09-04 08:43:17 -0400185OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400204if _lib.Cryptography_HAS_SSL_ST:
205 SSL_ST_INIT = _lib.SSL_ST_INIT
206 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
207 SSL_ST_OK = _lib.SSL_ST_OK
208 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800209
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500210SSL_CB_LOOP = _lib.SSL_CB_LOOP
211SSL_CB_EXIT = _lib.SSL_CB_EXIT
212SSL_CB_READ = _lib.SSL_CB_READ
213SSL_CB_WRITE = _lib.SSL_CB_WRITE
214SSL_CB_ALERT = _lib.SSL_CB_ALERT
215SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
216SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
217SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
218SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
219SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
220SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
221SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
222SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800223
Paul Kehrer55fb3412017-06-29 18:44:08 -0500224# Taken from https://golang.org/src/crypto/x509/root_linux.go
225_CERTIFICATE_FILE_LOCATIONS = [
226 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
227 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
228 "/etc/ssl/ca-bundle.pem", # OpenSUSE
229 "/etc/pki/tls/cacert.pem", # OpenELEC
230 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
231]
232
233_CERTIFICATE_PATH_LOCATIONS = [
234 "/etc/ssl/certs", # SLES10/SLES11
235]
236
Paul Kehrera92a1a72017-07-19 15:53:23 +0200237# These values are compared to output from cffi's ffi.string so they must be
238# byte strings.
239_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
240_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500241
Alex Gaynor83284952015-09-05 10:43:30 -0400242
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500244 """
245 An error occurred in an `OpenSSL.SSL` API.
246 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247
248
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500249_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100250_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251
252
253class WantReadError(Error):
254 pass
255
256
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500257class WantWriteError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class WantX509LookupError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class ZeroReturnError(Error):
266 pass
267
268
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269class SysCallError(Error):
270 pass
271
272
Cory Benfield0ea76e72015-03-22 09:05:28 +0000273class _CallbackExceptionHelper(object):
274 """
275 A base class for wrapper classes that allow for intelligent exception
276 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500277
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400278 :ivar list _problems: Any exceptions that occurred while executing in a
279 context where they could not be raised in the normal way. Typically
280 this is because OpenSSL has called into some Python code and requires a
281 return value. The exceptions are saved to be raised later when it is
282 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000283 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400284
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400285 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800286 self._problems = []
287
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400289 """
290 Raise an exception from the OpenSSL error queue or that was previously
291 captured whe running a callback.
292 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000293 if self._problems:
294 try:
295 _raise_current_error()
296 except Error:
297 pass
298 raise self._problems.pop(0)
299
300
301class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400302 """
303 Wrap a callback such that it can be used as a certificate verification
304 callback.
305 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400306
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800307 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400308 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800309
310 @wraps(callback)
311 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800312 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
313 _lib.X509_up_ref(x509)
314 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500315 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
316 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800317
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400318 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
319 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
320 connection = Connection._reverse_mapping[ssl]
321
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800322 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400323 result = callback(
324 connection, cert, error_number, error_depth, ok
325 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800326 except Exception as e:
327 self._problems.append(e)
328 return 0
329 else:
330 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500331 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800332 return 1
333 else:
334 return 0
335
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500336 self.callback = _ffi.callback(
337 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800338
339
Cory Benfield0ea76e72015-03-22 09:05:28 +0000340class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400341 """
342 Wrap a callback such that it can be used as an NPN advertisement callback.
343 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400344
Cory Benfield0ea76e72015-03-22 09:05:28 +0000345 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400346 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800347
Cory Benfield0ea76e72015-03-22 09:05:28 +0000348 @wraps(callback)
349 def wrapper(ssl, out, outlen, arg):
350 try:
351 conn = Connection._reverse_mapping[ssl]
352 protos = callback(conn)
353
354 # Join the protocols into a Python bytestring, length-prefixing
355 # each element.
356 protostr = b''.join(
357 chain.from_iterable((int2byte(len(p)), p) for p in protos)
358 )
359
360 # Save our callback arguments on the connection object. This is
361 # done to make sure that they don't get freed before OpenSSL
362 # uses them. Then, return them appropriately in the output
363 # parameters.
364 conn._npn_advertise_callback_args = [
365 _ffi.new("unsigned int *", len(protostr)),
366 _ffi.new("unsigned char[]", protostr),
367 ]
368 outlen[0] = conn._npn_advertise_callback_args[0][0]
369 out[0] = conn._npn_advertise_callback_args[1]
370 return 0
371 except Exception as e:
372 self._problems.append(e)
373 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
374
375 self.callback = _ffi.callback(
376 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
377 wrapper
378 )
379
380
381class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400382 """
383 Wrap a callback such that it can be used as an NPN selection callback.
384 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400385
Cory Benfield0ea76e72015-03-22 09:05:28 +0000386 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400387 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000388
389 @wraps(callback)
390 def wrapper(ssl, out, outlen, in_, inlen, arg):
391 try:
392 conn = Connection._reverse_mapping[ssl]
393
394 # The string passed to us is actually made up of multiple
395 # length-prefixed bytestrings. We need to split that into a
396 # list.
397 instr = _ffi.buffer(in_, inlen)[:]
398 protolist = []
399 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500400 length = indexbytes(instr, 0)
401 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000402 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500403 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000404
405 # Call the callback
406 outstr = callback(conn, protolist)
407
408 # Save our callback arguments on the connection object. This is
409 # done to make sure that they don't get freed before OpenSSL
410 # uses them. Then, return them appropriately in the output
411 # parameters.
412 conn._npn_select_callback_args = [
413 _ffi.new("unsigned char *", len(outstr)),
414 _ffi.new("unsigned char[]", outstr),
415 ]
416 outlen[0] = conn._npn_select_callback_args[0][0]
417 out[0] = conn._npn_select_callback_args[1]
418 return 0
419 except Exception as e:
420 self._problems.append(e)
421 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
422
423 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400424 ("int (*)(SSL *, unsigned char **, unsigned char *, "
425 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000426 wrapper
427 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800428
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800429
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400430class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400431 """
432 Wrap a callback such that it can be used as an ALPN selection callback.
433 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400434
Cory Benfieldf1177e72015-04-12 09:11:49 -0400435 def __init__(self, callback):
436 _CallbackExceptionHelper.__init__(self)
437
438 @wraps(callback)
439 def wrapper(ssl, out, outlen, in_, inlen, arg):
440 try:
441 conn = Connection._reverse_mapping[ssl]
442
443 # The string passed to us is made up of multiple
444 # length-prefixed bytestrings. We need to split that into a
445 # list.
446 instr = _ffi.buffer(in_, inlen)[:]
447 protolist = []
448 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400449 encoded_len = indexbytes(instr, 0)
450 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400451 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400452 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400453
454 # Call the callback
455 outstr = callback(conn, protolist)
456
457 if not isinstance(outstr, _binary_type):
458 raise TypeError("ALPN callback must return a bytestring.")
459
460 # Save our callback arguments on the connection object to make
461 # sure that they don't get freed before OpenSSL can use them.
462 # Then, return them in the appropriate output parameters.
463 conn._alpn_select_callback_args = [
464 _ffi.new("unsigned char *", len(outstr)),
465 _ffi.new("unsigned char[]", outstr),
466 ]
467 outlen[0] = conn._alpn_select_callback_args[0][0]
468 out[0] = conn._alpn_select_callback_args[1]
469 return 0
470 except Exception as e:
471 self._problems.append(e)
472 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
473
474 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400475 ("int (*)(SSL *, unsigned char **, unsigned char *, "
476 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400477 wrapper
478 )
479
480
Cory Benfield496652a2017-01-24 11:42:56 +0000481class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
482 """
483 Wrap a callback such that it can be used as an OCSP callback for the server
484 side.
485
486 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
487 ways. For servers, that callback is expected to retrieve some OCSP data and
488 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
489 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
490 is expected to check the OCSP data, and returns a negative value on error,
491 0 if the response is not acceptable, or positive if it is. These are
492 mutually exclusive return code behaviours, and they mean that we need two
493 helpers so that we always return an appropriate error code if the user's
494 code throws an exception.
495
496 Given that we have to have two helpers anyway, these helpers are a bit more
497 helpery than most: specifically, they hide a few more of the OpenSSL
498 functions so that the user has an easier time writing these callbacks.
499
500 This helper implements the server side.
501 """
502
503 def __init__(self, callback):
504 _CallbackExceptionHelper.__init__(self)
505
506 @wraps(callback)
507 def wrapper(ssl, cdata):
508 try:
509 conn = Connection._reverse_mapping[ssl]
510
511 # Extract the data if any was provided.
512 if cdata != _ffi.NULL:
513 data = _ffi.from_handle(cdata)
514 else:
515 data = None
516
517 # Call the callback.
518 ocsp_data = callback(conn, data)
519
520 if not isinstance(ocsp_data, _binary_type):
521 raise TypeError("OCSP callback must return a bytestring.")
522
523 # If the OCSP data was provided, we will pass it to OpenSSL.
524 # However, we have an early exit here: if no OCSP data was
525 # provided we will just exit out and tell OpenSSL that there
526 # is nothing to do.
527 if not ocsp_data:
528 return 3 # SSL_TLSEXT_ERR_NOACK
529
530 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
531 # private copy of this data, so we need to keep it alive, but
532 # it *does* want to free it itself if it gets replaced. This
533 # somewhat bonkers behaviour means we need to use
534 # OPENSSL_malloc directly, which is a pain in the butt to work
535 # with. It's ok for us to "leak" the memory here because
536 # OpenSSL now owns it and will free it.
537 ocsp_data_length = len(ocsp_data)
538 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
539 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
540
541 _lib.SSL_set_tlsext_status_ocsp_resp(
542 ssl, data_ptr, ocsp_data_length
543 )
544
545 return 0
546 except Exception as e:
547 self._problems.append(e)
548 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
549
550 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
551
552
553class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
554 """
555 Wrap a callback such that it can be used as an OCSP callback for the client
556 side.
557
558 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
559 ways. For servers, that callback is expected to retrieve some OCSP data and
560 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
561 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
562 is expected to check the OCSP data, and returns a negative value on error,
563 0 if the response is not acceptable, or positive if it is. These are
564 mutually exclusive return code behaviours, and they mean that we need two
565 helpers so that we always return an appropriate error code if the user's
566 code throws an exception.
567
568 Given that we have to have two helpers anyway, these helpers are a bit more
569 helpery than most: specifically, they hide a few more of the OpenSSL
570 functions so that the user has an easier time writing these callbacks.
571
572 This helper implements the client side.
573 """
574
575 def __init__(self, callback):
576 _CallbackExceptionHelper.__init__(self)
577
578 @wraps(callback)
579 def wrapper(ssl, cdata):
580 try:
581 conn = Connection._reverse_mapping[ssl]
582
583 # Extract the data if any was provided.
584 if cdata != _ffi.NULL:
585 data = _ffi.from_handle(cdata)
586 else:
587 data = None
588
589 # Get the OCSP data.
590 ocsp_ptr = _ffi.new("unsigned char **")
591 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
592 if ocsp_len < 0:
593 # No OCSP data.
594 ocsp_data = b''
595 else:
596 # Copy the OCSP data, then pass it to the callback.
597 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
598
599 valid = callback(conn, ocsp_data, data)
600
601 # Return 1 on success or 0 on error.
602 return int(bool(valid))
603
604 except Exception as e:
605 self._problems.append(e)
606 # Return negative value if an exception is hit.
607 return -1
608
609 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
610
611
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800612def _asFileDescriptor(obj):
613 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800614 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800615 meth = getattr(obj, "fileno", None)
616 if meth is not None:
617 obj = meth()
618
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800619 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800620 fd = obj
621
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800622 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800623 raise TypeError("argument must be an int, or have a fileno() method.")
624 elif fd < 0:
625 raise ValueError(
626 "file descriptor cannot be a negative integer (%i)" % (fd,))
627
628 return fd
629
630
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800631def SSLeay_version(type):
632 """
633 Return a string describing the version of OpenSSL in use.
634
Alex Chand072cae2018-02-15 09:57:59 +0000635 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800636 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500637 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638
639
Cory Benfieldef404df2016-03-29 15:32:48 +0100640def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400641 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100642 Builds a decorator that ensures that functions that rely on OpenSSL
643 functions that are not present in this build raise NotImplementedError,
644 rather than AttributeError coming out of cryptography.
645
646 :param flag: A cryptography flag that guards the functions, e.g.
647 ``Cryptography_HAS_NEXTPROTONEG``.
648 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400649 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100650 def _requires_decorator(func):
651 if not flag:
652 @wraps(func)
653 def explode(*args, **kwargs):
654 raise NotImplementedError(error)
655 return explode
656 else:
657 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400658
Cory Benfieldef404df2016-03-29 15:32:48 +0100659 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400660
661
Cory Benfieldef404df2016-03-29 15:32:48 +0100662_requires_npn = _make_requires(
663 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
664)
Cory Benfield7907e332015-04-13 17:18:25 -0400665
666
Cory Benfieldef404df2016-03-29 15:32:48 +0100667_requires_alpn = _make_requires(
668 _lib.Cryptography_HAS_ALPN, "ALPN not available"
669)
Cory Benfielde6f35882016-03-29 11:21:04 +0100670
Cory Benfielde6f35882016-03-29 11:21:04 +0100671
Cory Benfieldef404df2016-03-29 15:32:48 +0100672_requires_sni = _make_requires(
673 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
674)
Cory Benfielde6f35882016-03-29 11:21:04 +0100675
676
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800677class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000678 """
679 A class representing an SSL session. A session defines certain connection
680 parameters which may be re-used to speed up the setup of subsequent
681 connections.
682
683 .. versionadded:: 0.14
684 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800685 pass
686
687
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800688class Context(object):
689 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100690 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400691 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000692
693 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
694 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695 """
696 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800697 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500698 SSLv3_METHOD: "SSLv3_method",
699 SSLv23_METHOD: "SSLv23_method",
700 TLSv1_METHOD: "TLSv1_method",
701 TLSv1_1_METHOD: "TLSv1_1_method",
702 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400703 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500704 _methods = dict(
705 (identifier, getattr(_lib, name))
706 for (identifier, name) in _methods.items()
707 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800708
709 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500710 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800711 raise TypeError("method must be an integer")
712
713 try:
714 method_func = self._methods[method]
715 except KeyError:
716 raise ValueError("No such protocol")
717
718 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700719 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800720
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500721 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700722 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500723 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800724
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600725 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
726 # will be auto-selected. This function was added in 1.0.2 and made a
727 # noop in 1.1.0+ (where it is set automatically).
728 try:
729 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
730 _openssl_assert(res == 1)
731 except AttributeError:
732 pass
733
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800734 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800735 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800736 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800737 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800738 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800739 self._verify_callback = None
740 self._info_callback = None
741 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800742 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000743 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100744 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000745 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100746 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400747 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100748 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000749 self._ocsp_helper = None
750 self._ocsp_callback = None
751 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800752
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500753 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800754
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800755 def load_verify_locations(self, cafile, capath=None):
756 """
757 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000758 chain. Note that the certificates have to be in PEM format.
759
760 If capath is passed, it must be a directory prepared using the
761 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
762 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800763
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400764 :param cafile: In which file we can find the certificates (``bytes`` or
765 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800766 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400767 (``bytes`` or ``unicode``).
768
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769 :return: None
770 """
771 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500772 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400773 else:
774 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800775
776 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500777 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400778 else:
779 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780
Alex Gaynor62da94d2015-09-05 14:37:34 -0400781 load_result = _lib.SSL_CTX_load_verify_locations(
782 self._context, cafile, capath
783 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800784 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500785 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787 def _wrap_callback(self, callback):
788 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800789 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790 return callback(size, verify, self._passphrase_userdata)
791 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800792 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 def set_passwd_cb(self, callback, userdata=None):
795 """
Alex Chand072cae2018-02-15 09:57:59 +0000796 Set the passphrase callback. This function will be called
797 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798
Alex Chand072cae2018-02-15 09:57:59 +0000799 :param callback: The Python callback to use. This must accept three
800 positional arguments. First, an integer giving the maximum length
801 of the passphrase it may return. If the returned passphrase is
802 longer than this, it will be truncated. Second, a boolean value
803 which will be true if the user should be prompted for the
804 passphrase twice and the callback should verify that the two values
805 supplied are equal. Third, the value given as the *userdata*
806 parameter to :meth:`set_passwd_cb`. The *callback* must return
807 a byte string. If an error occurs, *callback* should return a false
808 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809 :param userdata: (optional) A Python object which will be given as
810 argument to the callback
811 :return: None
812 """
813 if not callable(callback):
814 raise TypeError("callback must be callable")
815
816 self._passphrase_helper = self._wrap_callback(callback)
817 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500818 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800819 self._context, self._passphrase_callback)
820 self._passphrase_userdata = userdata
821
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800822 def set_default_verify_paths(self):
823 """
Alex Chand072cae2018-02-15 09:57:59 +0000824 Specify that the platform provided CA certificates are to be used for
825 verification purposes. This method has some caveats related to the
826 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
827
828 * macOS will only load certificates using this method if the user has
829 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
830 in the default location.
831 * Windows will not work.
832 * manylinux1 cryptography wheels will work on most common Linux
833 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
834 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800835
836 :return: None
837 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500838 # SSL_CTX_set_default_verify_paths will attempt to load certs from
839 # both a cafile and capath that are set at compile time. However,
840 # it will first check environment variables and, if present, load
841 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500842 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400843 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500844 # After attempting to set default_verify_paths we need to know whether
845 # to go down the fallback path.
846 # First we'll check to see if any env vars have been set. If so,
847 # we won't try to do anything else because the user has set the path
848 # themselves.
849 dir_env_var = _ffi.string(
850 _lib.X509_get_default_cert_dir_env()
851 ).decode("ascii")
852 file_env_var = _ffi.string(
853 _lib.X509_get_default_cert_file_env()
854 ).decode("ascii")
855 if not self._check_env_vars_set(dir_env_var, file_env_var):
856 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
857 default_file = _ffi.string(_lib.X509_get_default_cert_file())
858 # Now we check to see if the default_dir and default_file are set
859 # to the exact values we use in our manylinux1 builds. If they are
860 # then we know to load the fallbacks
861 if (
862 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
863 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
864 ):
865 # This is manylinux1, let's load our fallback paths
866 self._fallback_default_verify_paths(
867 _CERTIFICATE_FILE_LOCATIONS,
868 _CERTIFICATE_PATH_LOCATIONS
869 )
870
871 def _check_env_vars_set(self, dir_env_var, file_env_var):
872 """
873 Check to see if the default cert dir/file environment vars are present.
874
875 :return: bool
876 """
877 return (
878 os.environ.get(file_env_var) is not None or
879 os.environ.get(dir_env_var) is not None
880 )
881
882 def _fallback_default_verify_paths(self, file_path, dir_path):
883 """
884 Default verify paths are based on the compiled version of OpenSSL.
885 However, when pyca/cryptography is compiled as a manylinux1 wheel
886 that compiled location can potentially be wrong. So, like Go, we
887 will try a predefined set of paths and attempt to load roots
888 from there.
889
890 :return: None
891 """
892 for cafile in file_path:
893 if os.path.isfile(cafile):
894 self.load_verify_locations(cafile)
895 break
896
897 for capath in dir_path:
898 if os.path.isdir(capath):
899 self.load_verify_locations(None, capath)
900 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800901
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800902 def use_certificate_chain_file(self, certfile):
903 """
Alex Chand072cae2018-02-15 09:57:59 +0000904 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400906 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000907 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400908
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 :return: None
910 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400911 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800912
Alex Gaynor62da94d2015-09-05 14:37:34 -0400913 result = _lib.SSL_CTX_use_certificate_chain_file(
914 self._context, certfile
915 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800916 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500917 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800918
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800919 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920 """
921 Load a certificate from a file
922
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400923 :param certfile: The name of the certificate file (``bytes`` or
924 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000925 :param filetype: (optional) The encoding of the file, which is either
926 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
927 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400928
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929 :return: None
930 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400931 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500932 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800933 raise TypeError("filetype must be an integer")
934
Alex Gaynor62da94d2015-09-05 14:37:34 -0400935 use_result = _lib.SSL_CTX_use_certificate_file(
936 self._context, certfile, filetype
937 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800938 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500939 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800940
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800941 def use_certificate(self, cert):
942 """
943 Load a certificate from a X509 object
944
945 :param cert: The X509 object
946 :return: None
947 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800948 if not isinstance(cert, X509):
949 raise TypeError("cert must be an X509 instance")
950
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500951 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800952 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500953 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800954
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800955 def add_extra_chain_cert(self, certobj):
956 """
957 Add certificate to chain
958
959 :param certobj: The X509 certificate object to add to the chain
960 :return: None
961 """
962 if not isinstance(certobj, X509):
963 raise TypeError("certobj must be an X509 instance")
964
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500965 copy = _lib.X509_dup(certobj._x509)
966 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500968 # TODO: This is untested.
969 _lib.X509_free(copy)
970 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800971
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800972 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500973 if self._passphrase_helper is not None:
974 self._passphrase_helper.raise_if_problem(Error)
975
976 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800977
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400978 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979 """
980 Load a private key from a file
981
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400982 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000983 :param filetype: (optional) The encoding of the file, which is either
984 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
985 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400986
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987 :return: None
988 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400989 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400991 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500993 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 raise TypeError("filetype must be an integer")
995
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500996 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997 self._context, keyfile, filetype)
998 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800999 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001000
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001 def use_privatekey(self, pkey):
1002 """
1003 Load a private key from a PKey object
1004
1005 :param pkey: The PKey object
1006 :return: None
1007 """
1008 if not isinstance(pkey, PKey):
1009 raise TypeError("pkey must be a PKey instance")
1010
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001011 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001012 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001013 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015 def check_privatekey(self):
1016 """
Alex Chand072cae2018-02-15 09:57:59 +00001017 Check if the private key (loaded with :meth:`use_privatekey`) matches
1018 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001019
Alex Chand072cae2018-02-15 09:57:59 +00001020 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001022 if not _lib.SSL_CTX_check_private_key(self._context):
1023 _raise_current_error()
1024
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025 def load_client_ca(self, cafile):
1026 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001027 Load the trusted certificates that will be sent to the client. Does
1028 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001029 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001030
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001031 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032 :return: None
1033 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001034 ca_list = _lib.SSL_load_client_CA_file(
1035 _text_to_bytes_and_warn("cafile", cafile)
1036 )
1037 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001038 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039
1040 def set_session_id(self, buf):
1041 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001042 Set the session id to *buf* within which a session can be reused for
1043 this Context object. This is needed when doing session resumption,
1044 because there is no way for a stored session to know which Context
1045 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001047 :param bytes buf: The session id.
1048
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001049 :returns: None
1050 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001051 buf = _text_to_bytes_and_warn("buf", buf)
1052 _openssl_assert(
1053 _lib.SSL_CTX_set_session_id_context(
1054 self._context,
1055 buf,
1056 len(buf),
1057 ) == 1
1058 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001059
1060 def set_session_cache_mode(self, mode):
1061 """
Alex Chand072cae2018-02-15 09:57:59 +00001062 Set the behavior of the session cache used by all connections using
1063 this Context. The previously set mode is returned. See
1064 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065
1066 :param mode: One or more of the SESS_CACHE_* flags (combine using
1067 bitwise or)
1068 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001069
1070 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001071 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001072 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 raise TypeError("mode must be an integer")
1074
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001075 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001077 def get_session_cache_mode(self):
1078 """
Alex Chand072cae2018-02-15 09:57:59 +00001079 Get the current session cache mode.
1080
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001081 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001082
1083 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001084 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087 def set_verify(self, mode, callback):
1088 """
Alex Chand072cae2018-02-15 09:57:59 +00001089 et the verification flags for this Context object to *mode* and specify
1090 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091
Alex Chand072cae2018-02-15 09:57:59 +00001092 :param mode: The verify mode, this should be one of
1093 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1094 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1095 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1096 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1097 :param callback: The Python callback to use. This should take five
1098 arguments: A Connection object, an X509 object, and three integer
1099 variables, which are in turn potential error number, error depth
1100 and return code. *callback* should return True if verification
1101 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001102 :return: None
1103
1104 See SSL_CTX_set_verify(3SSL) for further details.
1105 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001106 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107 raise TypeError("mode must be an integer")
1108
1109 if not callable(callback):
1110 raise TypeError("callback must be callable")
1111
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001112 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001113 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001114 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001115
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001116 def set_verify_depth(self, depth):
1117 """
Alex Chand072cae2018-02-15 09:57:59 +00001118 Set the maximum depth for the certificate chain verification that shall
1119 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001120
1121 :param depth: An integer specifying the verify depth
1122 :return: None
1123 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001124 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001125 raise TypeError("depth must be an integer")
1126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001127 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001128
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001129 def get_verify_mode(self):
1130 """
Alex Chand072cae2018-02-15 09:57:59 +00001131 Retrieve the Context object's verify mode, as set by
1132 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001133
1134 :return: The verify mode
1135 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001136 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001137
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001138 def get_verify_depth(self):
1139 """
Alex Chand072cae2018-02-15 09:57:59 +00001140 Retrieve the Context object's verify depth, as set by
1141 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142
1143 :return: The verify depth
1144 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001146
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147 def load_tmp_dh(self, dhfile):
1148 """
1149 Load parameters for Ephemeral Diffie-Hellman
1150
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001151 :param dhfile: The file to load EDH parameters from (``bytes`` or
1152 ``unicode``).
1153
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001154 :return: None
1155 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001156 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001157
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001158 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001160 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001162
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1164 dh = _ffi.gc(dh, _lib.DH_free)
1165 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001166
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001167 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001168 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001169 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001170
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001171 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001172 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1173 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001174
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001175 :return: None
1176 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001177 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001178
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001179 def set_cipher_list(self, cipher_list):
1180 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001181 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001183 See the OpenSSL manual for more information (e.g.
1184 :manpage:`ciphers(1)`).
1185
1186 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001187 :return: None
1188 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001189 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001190
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001191 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001192 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001193
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001194 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001195 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001196 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001197
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198 def set_client_ca_list(self, certificate_authorities):
1199 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001200 Set the list of preferred client certificate signers for this server
1201 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001202
Alex Gaynor62da94d2015-09-05 14:37:34 -04001203 This list of certificate authorities will be sent to the client when
1204 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001205
1206 :param certificate_authorities: a sequence of X509Names.
1207 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001208
1209 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001210 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001211 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001212 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001213
1214 try:
1215 for ca_name in certificate_authorities:
1216 if not isinstance(ca_name, X509Name):
1217 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001218 "client CAs must be X509Name objects, not %s "
1219 "objects" % (
1220 type(ca_name).__name__,
1221 )
1222 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001223 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001224 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001225 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001226 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001227 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001228 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001229 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001230 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001231 raise
1232
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001233 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001234
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001235 def add_client_ca(self, certificate_authority):
1236 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001237 Add the CA certificate to the list of preferred signers for this
1238 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001239
1240 The list of certificate authorities will be sent to the client when the
1241 server requests a client certificate.
1242
1243 :param certificate_authority: certificate authority's X509 certificate.
1244 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001245
1246 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001247 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001248 if not isinstance(certificate_authority, X509):
1249 raise TypeError("certificate_authority must be an X509 instance")
1250
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001251 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001252 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001253 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001254
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001255 def set_timeout(self, timeout):
1256 """
Alex Chand072cae2018-02-15 09:57:59 +00001257 Set the timeout for newly created sessions for this Context object to
1258 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1259 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001260
Alex Chand072cae2018-02-15 09:57:59 +00001261 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001262 :return: The previous session timeout
1263 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001264 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001265 raise TypeError("timeout must be an integer")
1266
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001267 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001268
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001269 def get_timeout(self):
1270 """
Alex Chand072cae2018-02-15 09:57:59 +00001271 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1272 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273
1274 :return: The session timeout
1275 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001276 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001277
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001278 def set_info_callback(self, callback):
1279 """
Alex Chand072cae2018-02-15 09:57:59 +00001280 Set the information callback to *callback*. This function will be
1281 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282
Alex Chand072cae2018-02-15 09:57:59 +00001283 :param callback: The Python callback to use. This should take three
1284 arguments: a Connection object and two integers. The first integer
1285 specifies where in the SSL handshake the function was called, and
1286 the other the return code from a (possibly failed) internal
1287 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001288 :return: None
1289 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001290 @wraps(callback)
1291 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001292 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001293 self._info_callback = _ffi.callback(
1294 "void (*)(const SSL *, int, int)", wrapper)
1295 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001296
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001297 def get_app_data(self):
1298 """
Alex Chand072cae2018-02-15 09:57:59 +00001299 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001300
1301 :return: The application data
1302 """
1303 return self._app_data
1304
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001305 def set_app_data(self, data):
1306 """
1307 Set the application data (will be returned from get_app_data())
1308
1309 :param data: Any Python object
1310 :return: None
1311 """
1312 self._app_data = data
1313
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001314 def get_cert_store(self):
1315 """
Alex Chand072cae2018-02-15 09:57:59 +00001316 Get the certificate store for the context. This can be used to add
1317 "trusted" certificates without using the
1318 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001319
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001320 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001322 store = _lib.SSL_CTX_get_cert_store(self._context)
1323 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001324 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001325 return None
1326
1327 pystore = X509Store.__new__(X509Store)
1328 pystore._store = store
1329 return pystore
1330
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001331 def set_options(self, options):
1332 """
1333 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001334 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001335
1336 :param options: The options to add.
1337 :return: The new option bitmask.
1338 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001339 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001340 raise TypeError("options must be an integer")
1341
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001342 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001343
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001344 def set_mode(self, mode):
1345 """
Alex Chand072cae2018-02-15 09:57:59 +00001346 Add modes via bitmask. Modes set before are not cleared! This method
1347 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001348
1349 :param mode: The mode to add.
1350 :return: The new mode bitmask.
1351 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001352 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001353 raise TypeError("mode must be an integer")
1354
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001355 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001356
Cory Benfielde6f35882016-03-29 11:21:04 +01001357 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358 def set_tlsext_servername_callback(self, callback):
1359 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001360 Specify a callback function to be called when clients specify a server
1361 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001362
1363 :param callback: The callback function. It will be invoked with one
1364 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001365
1366 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001367 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001368 @wraps(callback)
1369 def wrapper(ssl, alert, arg):
1370 callback(Connection._reverse_mapping[ssl])
1371 return 0
1372
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001373 self._tlsext_servername_callback = _ffi.callback(
1374 "int (*)(const SSL *, int *, void *)", wrapper)
1375 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001376 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001377
Cory Benfield10b277f2015-04-13 17:12:42 -04001378 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001379 def set_npn_advertise_callback(self, callback):
1380 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001381 Specify a callback function that will be called when offering `Next
1382 Protocol Negotiation
1383 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001384
1385 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001386 argument, the :class:`Connection` instance. It should return a
1387 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001388 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001389
1390 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001391 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001392 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1393 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001394 _lib.SSL_CTX_set_next_protos_advertised_cb(
1395 self._context, self._npn_advertise_callback, _ffi.NULL)
1396
Cory Benfield10b277f2015-04-13 17:12:42 -04001397 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001398 def set_npn_select_callback(self, callback):
1399 """
1400 Specify a callback function that will be called when a server offers
1401 Next Protocol Negotiation options.
1402
1403 :param callback: The callback function. It will be invoked with two
1404 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001405 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1406 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001407
1408 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001409 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001410 self._npn_select_helper = _NpnSelectHelper(callback)
1411 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001412 _lib.SSL_CTX_set_next_proto_select_cb(
1413 self._context, self._npn_select_callback, _ffi.NULL)
1414
Cory Benfield7907e332015-04-13 17:18:25 -04001415 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001416 def set_alpn_protos(self, protos):
1417 """
Alex Chand072cae2018-02-15 09:57:59 +00001418 Specify the protocols that the client is prepared to speak after the
1419 TLS connection has been negotiated using Application Layer Protocol
1420 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001421
1422 :param protos: A list of the protocols to be offered to the server.
1423 This list should be a Python list of bytestrings representing the
1424 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1425 """
1426 # Take the list of protocols and join them together, prefixing them
1427 # with their lengths.
1428 protostr = b''.join(
1429 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1430 )
1431
1432 # Build a C string from the list. We don't need to save this off
1433 # because OpenSSL immediately copies the data out.
1434 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001435 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001436
Cory Benfield7907e332015-04-13 17:18:25 -04001437 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001438 def set_alpn_select_callback(self, callback):
1439 """
Alex Chand072cae2018-02-15 09:57:59 +00001440 Specify a callback function that will be called on the server when a
1441 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001442
1443 :param callback: The callback function. It will be invoked with two
1444 arguments: the Connection, and a list of offered protocols as
1445 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001446 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001447 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001448 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001449 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001450 _lib.SSL_CTX_set_alpn_select_cb(
1451 self._context, self._alpn_select_callback, _ffi.NULL)
1452
Cory Benfield496652a2017-01-24 11:42:56 +00001453 def _set_ocsp_callback(self, helper, data):
1454 """
1455 This internal helper does the common work for
1456 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1457 almost all of it.
1458 """
1459 self._ocsp_helper = helper
1460 self._ocsp_callback = helper.callback
1461 if data is None:
1462 self._ocsp_data = _ffi.NULL
1463 else:
1464 self._ocsp_data = _ffi.new_handle(data)
1465
1466 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1467 self._context, self._ocsp_callback
1468 )
1469 _openssl_assert(rc == 1)
1470 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1471 _openssl_assert(rc == 1)
1472
1473 def set_ocsp_server_callback(self, callback, data=None):
1474 """
1475 Set a callback to provide OCSP data to be stapled to the TLS handshake
1476 on the server side.
1477
1478 :param callback: The callback function. It will be invoked with two
1479 arguments: the Connection, and the optional arbitrary data you have
1480 provided. The callback must return a bytestring that contains the
1481 OCSP data to staple to the handshake. If no OCSP data is available
1482 for this connection, return the empty bytestring.
1483 :param data: Some opaque data that will be passed into the callback
1484 function when called. This can be used to avoid needing to do
1485 complex data lookups or to keep track of what context is being
1486 used. This parameter is optional.
1487 """
1488 helper = _OCSPServerCallbackHelper(callback)
1489 self._set_ocsp_callback(helper, data)
1490
1491 def set_ocsp_client_callback(self, callback, data=None):
1492 """
1493 Set a callback to validate OCSP data stapled to the TLS handshake on
1494 the client side.
1495
1496 :param callback: The callback function. It will be invoked with three
1497 arguments: the Connection, a bytestring containing the stapled OCSP
1498 assertion, and the optional arbitrary data you have provided. The
1499 callback must return a boolean that indicates the result of
1500 validating the OCSP data: ``True`` if the OCSP data is valid and
1501 the certificate can be trusted, or ``False`` if either the OCSP
1502 data is invalid or the certificate has been revoked.
1503 :param data: Some opaque data that will be passed into the callback
1504 function when called. This can be used to avoid needing to do
1505 complex data lookups or to keep track of what context is being
1506 used. This parameter is optional.
1507 """
1508 helper = _OCSPClientCallbackHelper(callback)
1509 self._set_ocsp_callback(helper, data)
1510
Alex Chanc6077062016-11-18 13:53:39 +00001511
Alex Gaynor10d30832017-06-29 15:31:39 -07001512ContextType = deprecated(
1513 Context, __name__,
1514 "ContextType has been deprecated, use Context instead", DeprecationWarning
1515)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516
1517
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001518class Connection(object):
1519 """
1520 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001521 _reverse_mapping = WeakValueDictionary()
1522
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523 def __init__(self, context, socket=None):
1524 """
1525 Create a new Connection object, using the given OpenSSL.SSL.Context
1526 instance and socket.
1527
1528 :param context: An SSL Context to use for this connection
1529 :param socket: The socket to use for transport layer
1530 """
1531 if not isinstance(context, Context):
1532 raise TypeError("context must be a Context instance")
1533
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001534 ssl = _lib.SSL_new(context._context)
1535 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001536 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001537 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001539 # References to strings used for Next Protocol Negotiation. OpenSSL's
1540 # header files suggest that these might get copied at some point, but
1541 # doesn't specify when, so we store them here to make sure they don't
1542 # get freed before OpenSSL uses them.
1543 self._npn_advertise_callback_args = None
1544 self._npn_select_callback_args = None
1545
Cory Benfield12eae892014-06-07 15:42:56 +01001546 # References to strings used for Application Layer Protocol
1547 # Negotiation. These strings get copied at some point but it's well
1548 # after the callback returns, so we have to hang them somewhere to
1549 # avoid them getting freed.
1550 self._alpn_select_callback_args = None
1551
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001552 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001553
1554 if socket is None:
1555 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001556 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001557 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001558 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559
Alex Gaynora829e902016-06-04 18:16:01 -07001560 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1561 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001562
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001563 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001564 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001565 self._into_ssl = None
1566 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001568 set_result = _lib.SSL_set_fd(
1569 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001570 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001571
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 def __getattr__(self, name):
1573 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001574 Look up attributes on the wrapped socket object if they are not found
1575 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576 """
kjav0b66fa12015-09-02 11:51:26 +01001577 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001578 raise AttributeError("'%s' object has no attribute '%s'" % (
1579 self.__class__.__name__, name
1580 ))
kjav0b66fa12015-09-02 11:51:26 +01001581 else:
1582 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001583
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001585 if self._context._verify_helper is not None:
1586 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001587 if self._context._npn_advertise_helper is not None:
1588 self._context._npn_advertise_helper.raise_if_problem()
1589 if self._context._npn_select_helper is not None:
1590 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001591 if self._context._alpn_select_helper is not None:
1592 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001593 if self._context._ocsp_helper is not None:
1594 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001595
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001596 error = _lib.SSL_get_error(ssl, result)
1597 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001598 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001600 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001601 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001602 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001604 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001605 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001606 elif error == _lib.SSL_ERROR_SYSCALL:
1607 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001608 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001609 if platform == "win32":
1610 errno = _ffi.getwinerror()[0]
1611 else:
1612 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001613
1614 if errno != 0:
1615 raise SysCallError(errno, errorcode.get(errno))
1616 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001618 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001619 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001620 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001621 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001622 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001623 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001624
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625 def get_context(self):
1626 """
Alex Chand072cae2018-02-15 09:57:59 +00001627 Retrieve the :class:`Context` object associated with this
1628 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001630 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633 """
Alex Chand072cae2018-02-15 09:57:59 +00001634 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635
Alex Chand072cae2018-02-15 09:57:59 +00001636 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001637 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001638 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639 if not isinstance(context, Context):
1640 raise TypeError("context must be a Context instance")
1641
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001642 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001643 self._context = context
1644
Cory Benfielde6f35882016-03-29 11:21:04 +01001645 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001646 def get_servername(self):
1647 """
1648 Retrieve the servername extension value if provided in the client hello
1649 message, or None if there wasn't one.
1650
Alex Chand072cae2018-02-15 09:57:59 +00001651 :return: A byte string giving the server name or :data:`None`.
1652
1653 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001655 name = _lib.SSL_get_servername(
1656 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1657 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001658 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001659 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001660
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001661 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662
Cory Benfielde6f35882016-03-29 11:21:04 +01001663 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 """
1666 Set the value of the servername extension to send in the client hello.
1667
1668 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001669
1670 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672 if not isinstance(name, bytes):
1673 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001674 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675 raise TypeError("name must not contain NUL byte")
1676
1677 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001678 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001679
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001680 def pending(self):
1681 """
Alex Chand072cae2018-02-15 09:57:59 +00001682 Get the number of bytes that can be safely read from the SSL buffer
1683 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684
1685 :return: The number of bytes available in the receive buffer.
1686 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001687 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001688
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001689 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001690 """
1691 Send data on the connection. NOTE: If you get one of the WantRead,
1692 WantWrite or WantX509Lookup exceptions on this, you have to call the
1693 method again with the SAME buffer.
1694
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001695 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 :param flags: (optional) Included for compatibility with the socket
1697 API, the value is ignored
1698 :return: The number of bytes written
1699 """
Abraham Martine82326c2015-02-04 10:18:10 +00001700 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001701 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001702
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001703 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001704 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001705 if isinstance(buf, _buffer):
1706 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001707 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001708 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001709 if len(buf) > 2147483647:
1710 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001711
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001712 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001713 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001714 return result
1715 write = send
1716
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001717 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001718 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001719 Send "all" data on the connection. This calls send() repeatedly until
1720 all data is sent. If an error occurs, it's impossible to tell how much
1721 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001722
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001723 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724 :param flags: (optional) Included for compatibility with the socket
1725 API, the value is ignored
1726 :return: The number of bytes written
1727 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001728 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001729
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001730 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001731 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001732 if isinstance(buf, _buffer):
1733 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001734 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001735 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001736
1737 left_to_send = len(buf)
1738 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001740
1741 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001742 # SSL_write's num arg is an int,
1743 # so we cannot send more than 2**31-1 bytes at once.
1744 result = _lib.SSL_write(
1745 self._ssl,
1746 data + total_sent,
1747 min(left_to_send, 2147483647)
1748 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001749 self._raise_ssl_error(self._ssl, result)
1750 total_sent += result
1751 left_to_send -= result
1752
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001753 def recv(self, bufsiz, flags=None):
1754 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001755 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001756
1757 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001758 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1759 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001760 :return: The string read from the Connection
1761 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001762 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001763 if flags is not None and flags & socket.MSG_PEEK:
1764 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1765 else:
1766 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001767 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001768 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001769 read = recv
1770
Cory Benfield62d10332014-06-15 10:03:41 +01001771 def recv_into(self, buffer, nbytes=None, flags=None):
1772 """
Alex Chand072cae2018-02-15 09:57:59 +00001773 Receive data on the connection and copy it directly into the provided
1774 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001775
1776 :param buffer: The buffer to copy into.
1777 :param nbytes: (optional) The maximum number of bytes to read into the
1778 buffer. If not present, defaults to the size of the buffer. If
1779 larger than the size of the buffer, is reduced to the size of the
1780 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001781 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1782 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001783 :return: The number of bytes read into the buffer.
1784 """
1785 if nbytes is None:
1786 nbytes = len(buffer)
1787 else:
1788 nbytes = min(nbytes, len(buffer))
1789
1790 # We need to create a temporary buffer. This is annoying, it would be
1791 # better if we could pass memoryviews straight into the SSL_read call,
1792 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001793 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001794 if flags is not None and flags & socket.MSG_PEEK:
1795 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1796 else:
1797 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001798 self._raise_ssl_error(self._ssl, result)
1799
1800 # This strange line is all to avoid a memory copy. The buffer protocol
1801 # should allow us to assign a CFFI buffer to the LHS of this line, but
1802 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1803 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1804 # memoryview type.
1805 try:
1806 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1807 except NameError:
1808 buffer[:result] = _ffi.buffer(buf, result)
1809
1810 return result
1811
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001812 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001813 if _lib.BIO_should_retry(bio):
1814 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001815 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001816 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001817 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001818 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001819 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001820 # TODO: This is untested. I think io_special means the socket
1821 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001822 raise ValueError("BIO_should_io_special")
1823 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001824 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001825 raise ValueError("unknown bio failure")
1826 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001827 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001828 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001829
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001830 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001831 """
Alex Chand072cae2018-02-15 09:57:59 +00001832 If the Connection was created with a memory BIO, this method can be
1833 used to read bytes from the write end of that memory BIO. Many
1834 Connection methods will add bytes which must be read in this manner or
1835 the buffer will eventually fill up and the Connection will be able to
1836 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837
1838 :param bufsiz: The maximum number of bytes to read
1839 :return: The string read.
1840 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001841 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001842 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001843
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001844 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001845 raise TypeError("bufsiz must be an integer")
1846
Cory Benfielde62840e2016-11-28 12:17:08 +00001847 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001848 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001849 if result <= 0:
1850 self._handle_bio_errors(self._from_ssl, result)
1851
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001852 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001853
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001854 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001855 """
Alex Chand072cae2018-02-15 09:57:59 +00001856 If the Connection was created with a memory BIO, this method can be
1857 used to add bytes to the read end of that memory BIO. The Connection
1858 can then read the bytes (for example, in response to a call to
1859 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860
1861 :param buf: The string to put into the memory BIO.
1862 :return: The number of bytes written
1863 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001864 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001865
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001866 if self._into_ssl is None:
1867 raise TypeError("Connection sock was not None")
1868
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001869 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001870 if result <= 0:
1871 self._handle_bio_errors(self._into_ssl, result)
1872 return result
1873
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001874 def renegotiate(self):
1875 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001876 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001877
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001878 :return: True if the renegotiation can be started, False otherwise
1879 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001881 if not self.renegotiate_pending():
1882 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1883 return True
1884 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001885
1886 def do_handshake(self):
1887 """
Alex Chand072cae2018-02-15 09:57:59 +00001888 Perform an SSL handshake (usually called after :meth:`renegotiate` or
1889 one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
1890 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001891
1892 :return: None.
1893 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001894 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001895 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001897 def renegotiate_pending(self):
1898 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001899 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001900 a renegotiation is finished.
1901
1902 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001903 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001905 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906
1907 def total_renegotiations(self):
1908 """
1909 Find out the total number of renegotiations.
1910
1911 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001912 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001913 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001914 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 """
Alex Chand072cae2018-02-15 09:57:59 +00001918 Call the :meth:`connect` method of the underlying socket and set up SSL
1919 on the socket, using the :class:`Context` object supplied to this
1920 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921
1922 :param addr: A remote address
1923 :return: What the socket's connect method returns
1924 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001925 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001926 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001927
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001928 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929 """
Alex Chand072cae2018-02-15 09:57:59 +00001930 Call the :meth:`connect_ex` method of the underlying socket and set up
1931 SSL on the socket, using the Context object supplied to this Connection
1932 object at creation. Note that if the :meth:`connect_ex` method of the
1933 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934
1935 :param addr: A remove address
1936 :return: What the socket's connect_ex method returns
1937 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001938 connect_ex = self._socket.connect_ex
1939 self.set_connect_state()
1940 return connect_ex(addr)
1941
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001942 def accept(self):
1943 """
Alex Chand072cae2018-02-15 09:57:59 +00001944 Call the :meth:`accept` method of the underlying socket and set up SSL
1945 on the returned socket, using the Context object supplied to this
1946 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947
Alex Chand072cae2018-02-15 09:57:59 +00001948 :return: A *(conn, addr)* pair where *conn* is the new
1949 :class:`Connection` object created, and *address* is as returned by
1950 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001951 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001952 client, addr = self._socket.accept()
1953 conn = Connection(self._context, client)
1954 conn.set_accept_state()
1955 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001956
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001957 def bio_shutdown(self):
1958 """
Alex Chand072cae2018-02-15 09:57:59 +00001959 If the Connection was created with a memory BIO, this method can be
1960 used to indicate that *end of file* has been reached on the read end of
1961 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962
1963 :return: None
1964 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001965 if self._from_ssl is None:
1966 raise TypeError("Connection sock was not None")
1967
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001968 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001969
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001970 def shutdown(self):
1971 """
Alex Chand072cae2018-02-15 09:57:59 +00001972 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
1974 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001975 have sent closure alerts), False otherwise (in which case you
1976 call :meth:`recv` or :meth:`send` when the connection becomes
1977 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001978 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001979 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001981 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001983 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984 else:
1985 return False
1986
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001987 def get_cipher_list(self):
1988 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001989 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001991 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001992 """
1993 ciphers = []
1994 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001995 result = _lib.SSL_get_cipher_list(self._ssl, i)
1996 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001997 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001998 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999 return ciphers
2000
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 def get_client_ca_list(self):
2002 """
2003 Get CAs whose certificates are suggested for client authentication.
2004
Alex Chand072cae2018-02-15 09:57:59 +00002005 :return: If this is a server connection, the list of certificate
2006 authorities that will be sent or has been sent to the client, as
2007 controlled by this :class:`Connection`'s :class:`Context`.
2008
2009 If this is a client connection, the list will be empty until the
2010 connection with the server is established.
2011
2012 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002014 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2015 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002016 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002017 return []
2018
2019 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002020 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2021 name = _lib.sk_X509_NAME_value(ca_names, i)
2022 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002023 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002024
2025 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002026 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002027 result.append(pyname)
2028 return result
2029
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002030 def makefile(self):
2031 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002032 The makefile() method is not implemented, since there is no dup
2033 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002034
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002035 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036 """
Alex Gaynor83284952015-09-05 10:43:30 -04002037 raise NotImplementedError(
2038 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002039
2040 def get_app_data(self):
2041 """
Alex Chand072cae2018-02-15 09:57:59 +00002042 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002043
2044 :return: The application data
2045 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002046 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002047
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002048 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049 """
2050 Set application data
2051
Alex Chand072cae2018-02-15 09:57:59 +00002052 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002053 :return: None
2054 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002055 self._app_data = data
2056
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002057 def get_shutdown(self):
2058 """
Alex Chand072cae2018-02-15 09:57:59 +00002059 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002060
Alex Gaynor62da94d2015-09-05 14:37:34 -04002061 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2062 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002063 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002064 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002065
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002066 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002067 """
Alex Chand072cae2018-02-15 09:57:59 +00002068 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002069
Alex Chand072cae2018-02-15 09:57:59 +00002070 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071 :return: None
2072 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002073 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002074 raise TypeError("state must be an integer")
2075
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002076 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002077
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002078 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002079 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002080 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002081
2082 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002083 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002084 """
kjavc704a2e2015-09-07 12:12:27 +01002085 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086
2087 def server_random(self):
2088 """
Alex Chand072cae2018-02-15 09:57:59 +00002089 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002090
2091 :return: A string representing the state
2092 """
Alex Gaynor93603062016-06-01 20:13:09 -07002093 session = _lib.SSL_get_session(self._ssl)
2094 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002095 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002096 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2097 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002098 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002099 _lib.SSL_get_server_random(self._ssl, outp, length)
2100 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002101
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102 def client_random(self):
2103 """
Alex Chand072cae2018-02-15 09:57:59 +00002104 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002105
2106 :return: A string representing the state
2107 """
Alex Gaynor93603062016-06-01 20:13:09 -07002108 session = _lib.SSL_get_session(self._ssl)
2109 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002110 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002111
2112 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2113 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002114 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002115 _lib.SSL_get_client_random(self._ssl, outp, length)
2116 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002117
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002118 def master_key(self):
2119 """
Alex Chand072cae2018-02-15 09:57:59 +00002120 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002121
2122 :return: A string representing the state
2123 """
Alex Gaynor93603062016-06-01 20:13:09 -07002124 session = _lib.SSL_get_session(self._ssl)
2125 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002126 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002127
2128 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2129 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002130 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002131 _lib.SSL_SESSION_get_master_key(session, outp, length)
2132 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002133
Paul Kehrerbdb76392017-12-01 04:54:32 +08002134 def export_keying_material(self, label, olen, context=None):
2135 """
2136 Obtain keying material for application use.
2137
Alex Chand072cae2018-02-15 09:57:59 +00002138 :param: label - a disambiguating label string as described in RFC 5705
2139 :param: olen - the length of the exported key material in bytes
2140 :param: context - a per-association context value
2141 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002142 """
2143 outp = _no_zero_allocator("unsigned char[]", olen)
2144 context_buf = _ffi.NULL
2145 context_len = 0
2146 use_context = 0
2147 if context is not None:
2148 context_buf = context
2149 context_len = len(context)
2150 use_context = 1
2151 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2152 label, len(label),
2153 context_buf, context_len,
2154 use_context)
2155 _openssl_assert(success == 1)
2156 return _ffi.buffer(outp, olen)[:]
2157
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002158 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002159 """
Alex Chand072cae2018-02-15 09:57:59 +00002160 Call the :meth:`shutdown` method of the underlying socket.
2161 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002162
2163 :return: What the socket's shutdown() method returns
2164 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002165 return self._socket.shutdown(*args, **kwargs)
2166
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002167 def get_peer_certificate(self):
2168 """
2169 Retrieve the other side's certificate (if any)
2170
2171 :return: The peer's certificate
2172 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002173 cert = _lib.SSL_get_peer_certificate(self._ssl)
2174 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002175 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002176 return None
2177
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178 def get_peer_cert_chain(self):
2179 """
2180 Retrieve the other side's certificate (if any)
2181
2182 :return: A list of X509 instances giving the peer's certificate chain,
2183 or None if it does not have one.
2184 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002185 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2186 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002187 return None
2188
2189 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002190 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002191 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002192 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002193 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002194 result.append(pycert)
2195 return result
2196
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002197 def want_read(self):
2198 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002199 Checks if more data has to be read from the transport layer to complete
2200 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002201
2202 :return: True iff more data has to be read
2203 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002204 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002205
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002206 def want_write(self):
2207 """
2208 Checks if there is data to write to the transport layer to complete an
2209 operation.
2210
2211 :return: True iff there is data to write
2212 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002213 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002214
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002215 def set_accept_state(self):
2216 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002217 Set the connection to work in server mode. The handshake will be
2218 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002219
2220 :return: None
2221 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002222 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002223
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002224 def set_connect_state(self):
2225 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002226 Set the connection to work in client mode. The handshake will be
2227 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002228
2229 :return: None
2230 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002231 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002232
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002233 def get_session(self):
2234 """
2235 Returns the Session currently used.
2236
Alex Chand072cae2018-02-15 09:57:59 +00002237 :return: An instance of :class:`OpenSSL.SSL.Session` or
2238 :obj:`None` if no session exists.
2239
2240 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002241 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002242 session = _lib.SSL_get1_session(self._ssl)
2243 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002244 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002245
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002246 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002247 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002248 return pysession
2249
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002250 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002251 """
2252 Set the session to be used when the TLS/SSL connection is established.
2253
2254 :param session: A Session instance representing the session to use.
2255 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002256
2257 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002258 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002259 if not isinstance(session, Session):
2260 raise TypeError("session must be a Session instance")
2261
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002262 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002263 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002264 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002265
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002266 def _get_finished_message(self, function):
2267 """
Alex Chand072cae2018-02-15 09:57:59 +00002268 Helper to implement :meth:`get_finished` and
2269 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002270
Alex Chand072cae2018-02-15 09:57:59 +00002271 :param function: Either :data:`SSL_get_finished`: or
2272 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002273
Alex Chand072cae2018-02-15 09:57:59 +00002274 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002275 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002276 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002277 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002278 # The OpenSSL documentation says nothing about what might happen if the
2279 # count argument given is zero. Specifically, it doesn't say whether
2280 # the output buffer may be NULL in that case or not. Inspection of the
2281 # implementation reveals that it calls memcpy() unconditionally.
2282 # Section 7.1.4, paragraph 1 of the C standard suggests that
2283 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2284 # alone desirable) behavior (though it probably does on just about
2285 # every implementation...)
2286 #
2287 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2288 # one might expect) for the initial call so as to be safe against this
2289 # potentially undefined behavior.
2290 empty = _ffi.new("char[]", 0)
2291 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002292 if size == 0:
2293 # No Finished message so far.
2294 return None
2295
Cory Benfielde62840e2016-11-28 12:17:08 +00002296 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002297 function(self._ssl, buf, size)
2298 return _ffi.buffer(buf, size)[:]
2299
Fedor Brunner5747b932014-03-05 14:22:34 +01002300 def get_finished(self):
2301 """
Alex Chand072cae2018-02-15 09:57:59 +00002302 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002303
Alex Chand072cae2018-02-15 09:57:59 +00002304 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002305 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002306 :rtype: :class:`bytes` or :class:`NoneType`
2307
2308 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002309 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002310 return self._get_finished_message(_lib.SSL_get_finished)
2311
Fedor Brunner5747b932014-03-05 14:22:34 +01002312 def get_peer_finished(self):
2313 """
Alex Chand072cae2018-02-15 09:57:59 +00002314 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002315
Alex Chand072cae2018-02-15 09:57:59 +00002316 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002317 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002318 :rtype: :class:`bytes` or :class:`NoneType`
2319
2320 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002321 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002322 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002323
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002324 def get_cipher_name(self):
2325 """
2326 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002327
Alex Chand072cae2018-02-15 09:57:59 +00002328 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002329 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002330 :rtype: :class:`unicode` or :class:`NoneType`
2331
2332 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002333 """
2334 cipher = _lib.SSL_get_current_cipher(self._ssl)
2335 if cipher == _ffi.NULL:
2336 return None
2337 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002338 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2339 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002340
2341 def get_cipher_bits(self):
2342 """
2343 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002344
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002345 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002346 or :obj:`None` if no connection has been established.
2347 :rtype: :class:`int` or :class:`NoneType`
2348
2349 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002350 """
2351 cipher = _lib.SSL_get_current_cipher(self._ssl)
2352 if cipher == _ffi.NULL:
2353 return None
2354 else:
2355 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2356
2357 def get_cipher_version(self):
2358 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002359 Obtain the protocol version of the currently used cipher.
2360
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002361 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002362 or :obj:`None` if no connection has been established.
2363 :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:
Alex Gaynorc4889812015-09-04 08:43:17 -04002371 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002372 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002373
Jim Shaverabff1882015-05-27 09:15:55 -04002374 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002375 """
Alex Chand072cae2018-02-15 09:57:59 +00002376 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002377
2378 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002379 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002380 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002381 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002382 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002383 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002384 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002385
Jim Shaver208438c2015-05-28 09:52:38 -04002386 def get_protocol_version(self):
2387 """
Alex Chand072cae2018-02-15 09:57:59 +00002388 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002389
Alex Chand072cae2018-02-15 09:57:59 +00002390 :returns: The TLS version of the current connection. For example,
2391 it will return ``0x769`` for connections made over TLS version 1.
2392 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002393 """
2394 version = _lib.SSL_version(self._ssl)
2395 return version
2396
Cory Benfield10b277f2015-04-13 17:12:42 -04002397 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002398 def get_next_proto_negotiated(self):
2399 """
2400 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002401
2402 :returns: A bytestring of the protocol name. If no protocol has been
2403 negotiated yet, returns an empty string.
2404
2405 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002406 """
2407 data = _ffi.new("unsigned char **")
2408 data_len = _ffi.new("unsigned int *")
2409
2410 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2411
Cory Benfieldcd010f62014-05-15 19:00:27 +01002412 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002413
Cory Benfield7907e332015-04-13 17:18:25 -04002414 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002415 def set_alpn_protos(self, protos):
2416 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002417 Specify the client's ALPN protocol list.
2418
2419 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002420
2421 :param protos: A list of the protocols to be offered to the server.
2422 This list should be a Python list of bytestrings representing the
2423 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2424 """
2425 # Take the list of protocols and join them together, prefixing them
2426 # with their lengths.
2427 protostr = b''.join(
2428 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2429 )
2430
2431 # Build a C string from the list. We don't need to save this off
2432 # because OpenSSL immediately copies the data out.
2433 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002434 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002435
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002436 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002437 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002438 """
2439 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002440
2441 :returns: A bytestring of the protocol name. If no protocol has been
2442 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002443 """
Cory Benfield12eae892014-06-07 15:42:56 +01002444 data = _ffi.new("unsigned char **")
2445 data_len = _ffi.new("unsigned int *")
2446
2447 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2448
Cory Benfielde8e9c382015-04-11 17:33:48 -04002449 if not data_len:
2450 return b''
2451
Cory Benfield12eae892014-06-07 15:42:56 +01002452 return _ffi.buffer(data[0], data_len[0])[:]
2453
Cory Benfield496652a2017-01-24 11:42:56 +00002454 def request_ocsp(self):
2455 """
2456 Called to request that the server sends stapled OCSP data, if
2457 available. If this is not called on the client side then the server
2458 will not send OCSP data. Should be used in conjunction with
2459 :meth:`Context.set_ocsp_client_callback`.
2460 """
2461 rc = _lib.SSL_set_tlsext_status_type(
2462 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2463 )
2464 _openssl_assert(rc == 1)
2465
Cory Benfield12eae892014-06-07 15:42:56 +01002466
Alex Gaynor10d30832017-06-29 15:31:39 -07002467ConnectionType = deprecated(
2468 Connection, __name__,
2469 "ConnectionType has been deprecated, use Connection instead",
2470 DeprecationWarning
2471)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002472
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002473# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2474# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002475_lib.SSL_library_init()