blob: b5dd442d2f396015d60a4b8ce4e0c241051b28b0 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Nicolas Karolak736c6212017-11-26 14:40:28 +010030__all__ = [
31 'OPENSSL_VERSION_NUMBER',
32 'SSLEAY_VERSION',
33 'SSLEAY_CFLAGS',
34 'SSLEAY_PLATFORM',
35 'SSLEAY_DIR',
36 'SSLEAY_BUILT_ON',
37 'SENT_SHUTDOWN',
38 'RECEIVED_SHUTDOWN',
39 'SSLv2_METHOD',
40 'SSLv3_METHOD',
41 'SSLv23_METHOD',
42 'TLSv1_METHOD',
43 'TLSv1_1_METHOD',
44 'TLSv1_2_METHOD',
45 'OP_NO_SSLv2',
46 'OP_NO_SSLv3',
47 'OP_NO_TLSv1',
48 'OP_NO_TLSv1_1',
49 'OP_NO_TLSv1_2',
50 'MODE_RELEASE_BUFFERS',
51 'OP_SINGLE_DH_USE',
52 'OP_SINGLE_ECDH_USE',
53 'OP_EPHEMERAL_RSA',
54 'OP_MICROSOFT_SESS_ID_BUG',
55 'OP_NETSCAPE_CHALLENGE_BUG',
56 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
57 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
58 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
59 'OP_MSIE_SSLV2_RSA_PADDING',
60 'OP_SSLEAY_080_CLIENT_DH_BUG',
61 'OP_TLS_D5_BUG',
62 'OP_TLS_BLOCK_PADDING_BUG',
63 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
64 'OP_CIPHER_SERVER_PREFERENCE',
65 'OP_TLS_ROLLBACK_BUG',
66 'OP_PKCS1_CHECK_1',
67 'OP_PKCS1_CHECK_2',
68 'OP_NETSCAPE_CA_DN_BUG',
69 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
70 'OP_NO_COMPRESSION',
71 'OP_NO_QUERY_MTU',
72 'OP_COOKIE_EXCHANGE',
73 'OP_NO_TICKET',
74 'OP_ALL',
75 'VERIFY_PEER',
76 'VERIFY_FAIL_IF_NO_PEER_CERT',
77 'VERIFY_CLIENT_ONCE',
78 'VERIFY_NONE',
79 'SESS_CACHE_OFF',
80 'SESS_CACHE_CLIENT',
81 'SESS_CACHE_SERVER',
82 'SESS_CACHE_BOTH',
83 'SESS_CACHE_NO_AUTO_CLEAR',
84 'SESS_CACHE_NO_INTERNAL_LOOKUP',
85 'SESS_CACHE_NO_INTERNAL_STORE',
86 'SESS_CACHE_NO_INTERNAL',
87 'SSL_ST_CONNECT',
88 'SSL_ST_ACCEPT',
89 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010090 'SSL_CB_LOOP',
91 'SSL_CB_EXIT',
92 'SSL_CB_READ',
93 'SSL_CB_WRITE',
94 'SSL_CB_ALERT',
95 'SSL_CB_READ_ALERT',
96 'SSL_CB_WRITE_ALERT',
97 'SSL_CB_ACCEPT_LOOP',
98 'SSL_CB_ACCEPT_EXIT',
99 'SSL_CB_CONNECT_LOOP',
100 'SSL_CB_CONNECT_EXIT',
101 'SSL_CB_HANDSHAKE_START',
102 'SSL_CB_HANDSHAKE_DONE',
103 'Error',
104 'WantReadError',
105 'WantWriteError',
106 'WantX509LookupError',
107 'ZeroReturnError',
108 'SysCallError',
109 'SSLeay_version',
110 'Session',
111 'Context',
112 'Connection'
113]
114
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500115try:
116 _memoryview = memoryview
117except NameError:
118 class _memoryview(object):
119 pass
120
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200121try:
122 _buffer = buffer
123except NameError:
124 class _buffer(object):
125 pass
126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500127OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
128SSLEAY_VERSION = _lib.SSLEAY_VERSION
129SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
130SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
131SSLEAY_DIR = _lib.SSLEAY_DIR
132SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
135RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800136
137SSLv2_METHOD = 1
138SSLv3_METHOD = 2
139SSLv23_METHOD = 3
140TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500141TLSv1_1_METHOD = 5
142TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800143
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500144OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
145OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
146OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700147OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
148OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800149
Alex Gaynorbf012872016-06-04 13:18:39 -0700150MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800151
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900153OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500154OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
155OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
156OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400157OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
158 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
159)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500160OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
161OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400162OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500163OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
164OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
165OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
166OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
167OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
168OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
169OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
170OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
171OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400172OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
173 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
174)
Alex Gaynorbf012872016-06-04 13:18:39 -0700175OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500177OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
178OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400179OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Alex Gaynorc4889812015-09-04 08:43:17 -0400181OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800182
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500183VERIFY_PEER = _lib.SSL_VERIFY_PEER
184VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
185VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
186VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800187
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500188SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
189SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
190SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
191SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
192SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
193SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
194SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
195SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800196
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500197SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
198SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
199SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400200if _lib.Cryptography_HAS_SSL_ST:
201 SSL_ST_INIT = _lib.SSL_ST_INIT
202 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
203 SSL_ST_OK = _lib.SSL_ST_OK
204 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100205 __all__.extend([
206 'SSL_ST_INIT',
207 'SSL_ST_BEFORE',
208 'SSL_ST_OK',
209 'SSL_ST_RENEGOTIATE',
210 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800211
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500212SSL_CB_LOOP = _lib.SSL_CB_LOOP
213SSL_CB_EXIT = _lib.SSL_CB_EXIT
214SSL_CB_READ = _lib.SSL_CB_READ
215SSL_CB_WRITE = _lib.SSL_CB_WRITE
216SSL_CB_ALERT = _lib.SSL_CB_ALERT
217SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
218SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
219SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
220SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
221SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
222SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
223SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
224SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800225
Paul Kehrer55fb3412017-06-29 18:44:08 -0500226# Taken from https://golang.org/src/crypto/x509/root_linux.go
227_CERTIFICATE_FILE_LOCATIONS = [
228 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
229 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
230 "/etc/ssl/ca-bundle.pem", # OpenSUSE
231 "/etc/pki/tls/cacert.pem", # OpenELEC
232 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
233]
234
235_CERTIFICATE_PATH_LOCATIONS = [
236 "/etc/ssl/certs", # SLES10/SLES11
237]
238
Paul Kehrera92a1a72017-07-19 15:53:23 +0200239# These values are compared to output from cffi's ffi.string so they must be
240# byte strings.
241_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
242_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500243
Alex Gaynor83284952015-09-05 10:43:30 -0400244
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500245class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500246 """
247 An error occurred in an `OpenSSL.SSL` API.
248 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500249
250
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100252_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500253
254
255class WantReadError(Error):
256 pass
257
258
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500259class WantWriteError(Error):
260 pass
261
262
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500263class WantX509LookupError(Error):
264 pass
265
266
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500267class ZeroReturnError(Error):
268 pass
269
270
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500271class SysCallError(Error):
272 pass
273
274
Cory Benfield0ea76e72015-03-22 09:05:28 +0000275class _CallbackExceptionHelper(object):
276 """
277 A base class for wrapper classes that allow for intelligent exception
278 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500279
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400280 :ivar list _problems: Any exceptions that occurred while executing in a
281 context where they could not be raised in the normal way. Typically
282 this is because OpenSSL has called into some Python code and requires a
283 return value. The exceptions are saved to be raised later when it is
284 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000285 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400286
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400287 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800288 self._problems = []
289
Cory Benfield0ea76e72015-03-22 09:05:28 +0000290 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400291 """
292 Raise an exception from the OpenSSL error queue or that was previously
293 captured whe running a callback.
294 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000295 if self._problems:
296 try:
297 _raise_current_error()
298 except Error:
299 pass
300 raise self._problems.pop(0)
301
302
303class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400304 """
305 Wrap a callback such that it can be used as a certificate verification
306 callback.
307 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400308
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800309 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400310 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800311
312 @wraps(callback)
313 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800314 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
315 _lib.X509_up_ref(x509)
316 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500317 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
318 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800319
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400320 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
321 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
322 connection = Connection._reverse_mapping[ssl]
323
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800324 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400325 result = callback(
326 connection, cert, error_number, error_depth, ok
327 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800328 except Exception as e:
329 self._problems.append(e)
330 return 0
331 else:
332 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500333 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800334 return 1
335 else:
336 return 0
337
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500338 self.callback = _ffi.callback(
339 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800340
341
Cory Benfield0ea76e72015-03-22 09:05:28 +0000342class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400343 """
344 Wrap a callback such that it can be used as an NPN advertisement callback.
345 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400346
Cory Benfield0ea76e72015-03-22 09:05:28 +0000347 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400348 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800349
Cory Benfield0ea76e72015-03-22 09:05:28 +0000350 @wraps(callback)
351 def wrapper(ssl, out, outlen, arg):
352 try:
353 conn = Connection._reverse_mapping[ssl]
354 protos = callback(conn)
355
356 # Join the protocols into a Python bytestring, length-prefixing
357 # each element.
358 protostr = b''.join(
359 chain.from_iterable((int2byte(len(p)), p) for p in protos)
360 )
361
362 # Save our callback arguments on the connection object. This is
363 # done to make sure that they don't get freed before OpenSSL
364 # uses them. Then, return them appropriately in the output
365 # parameters.
366 conn._npn_advertise_callback_args = [
367 _ffi.new("unsigned int *", len(protostr)),
368 _ffi.new("unsigned char[]", protostr),
369 ]
370 outlen[0] = conn._npn_advertise_callback_args[0][0]
371 out[0] = conn._npn_advertise_callback_args[1]
372 return 0
373 except Exception as e:
374 self._problems.append(e)
375 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
376
377 self.callback = _ffi.callback(
378 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
379 wrapper
380 )
381
382
383class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400384 """
385 Wrap a callback such that it can be used as an NPN selection callback.
386 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400387
Cory Benfield0ea76e72015-03-22 09:05:28 +0000388 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400389 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000390
391 @wraps(callback)
392 def wrapper(ssl, out, outlen, in_, inlen, arg):
393 try:
394 conn = Connection._reverse_mapping[ssl]
395
396 # The string passed to us is actually made up of multiple
397 # length-prefixed bytestrings. We need to split that into a
398 # list.
399 instr = _ffi.buffer(in_, inlen)[:]
400 protolist = []
401 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500402 length = indexbytes(instr, 0)
403 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000404 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500405 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000406
407 # Call the callback
408 outstr = callback(conn, protolist)
409
410 # Save our callback arguments on the connection object. This is
411 # done to make sure that they don't get freed before OpenSSL
412 # uses them. Then, return them appropriately in the output
413 # parameters.
414 conn._npn_select_callback_args = [
415 _ffi.new("unsigned char *", len(outstr)),
416 _ffi.new("unsigned char[]", outstr),
417 ]
418 outlen[0] = conn._npn_select_callback_args[0][0]
419 out[0] = conn._npn_select_callback_args[1]
420 return 0
421 except Exception as e:
422 self._problems.append(e)
423 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
424
425 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400426 ("int (*)(SSL *, unsigned char **, unsigned char *, "
427 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000428 wrapper
429 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800430
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800431
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400432class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400433 """
434 Wrap a callback such that it can be used as an ALPN selection callback.
435 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400436
Cory Benfieldf1177e72015-04-12 09:11:49 -0400437 def __init__(self, callback):
438 _CallbackExceptionHelper.__init__(self)
439
440 @wraps(callback)
441 def wrapper(ssl, out, outlen, in_, inlen, arg):
442 try:
443 conn = Connection._reverse_mapping[ssl]
444
445 # The string passed to us is made up of multiple
446 # length-prefixed bytestrings. We need to split that into a
447 # list.
448 instr = _ffi.buffer(in_, inlen)[:]
449 protolist = []
450 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400451 encoded_len = indexbytes(instr, 0)
452 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400453 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400454 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400455
456 # Call the callback
457 outstr = callback(conn, protolist)
458
459 if not isinstance(outstr, _binary_type):
460 raise TypeError("ALPN callback must return a bytestring.")
461
462 # Save our callback arguments on the connection object to make
463 # sure that they don't get freed before OpenSSL can use them.
464 # Then, return them in the appropriate output parameters.
465 conn._alpn_select_callback_args = [
466 _ffi.new("unsigned char *", len(outstr)),
467 _ffi.new("unsigned char[]", outstr),
468 ]
469 outlen[0] = conn._alpn_select_callback_args[0][0]
470 out[0] = conn._alpn_select_callback_args[1]
471 return 0
472 except Exception as e:
473 self._problems.append(e)
474 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
475
476 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400477 ("int (*)(SSL *, unsigned char **, unsigned char *, "
478 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400479 wrapper
480 )
481
482
Cory Benfield496652a2017-01-24 11:42:56 +0000483class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
484 """
485 Wrap a callback such that it can be used as an OCSP callback for the server
486 side.
487
488 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
489 ways. For servers, that callback is expected to retrieve some OCSP data and
490 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
491 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
492 is expected to check the OCSP data, and returns a negative value on error,
493 0 if the response is not acceptable, or positive if it is. These are
494 mutually exclusive return code behaviours, and they mean that we need two
495 helpers so that we always return an appropriate error code if the user's
496 code throws an exception.
497
498 Given that we have to have two helpers anyway, these helpers are a bit more
499 helpery than most: specifically, they hide a few more of the OpenSSL
500 functions so that the user has an easier time writing these callbacks.
501
502 This helper implements the server side.
503 """
504
505 def __init__(self, callback):
506 _CallbackExceptionHelper.__init__(self)
507
508 @wraps(callback)
509 def wrapper(ssl, cdata):
510 try:
511 conn = Connection._reverse_mapping[ssl]
512
513 # Extract the data if any was provided.
514 if cdata != _ffi.NULL:
515 data = _ffi.from_handle(cdata)
516 else:
517 data = None
518
519 # Call the callback.
520 ocsp_data = callback(conn, data)
521
522 if not isinstance(ocsp_data, _binary_type):
523 raise TypeError("OCSP callback must return a bytestring.")
524
525 # If the OCSP data was provided, we will pass it to OpenSSL.
526 # However, we have an early exit here: if no OCSP data was
527 # provided we will just exit out and tell OpenSSL that there
528 # is nothing to do.
529 if not ocsp_data:
530 return 3 # SSL_TLSEXT_ERR_NOACK
531
532 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
533 # private copy of this data, so we need to keep it alive, but
534 # it *does* want to free it itself if it gets replaced. This
535 # somewhat bonkers behaviour means we need to use
536 # OPENSSL_malloc directly, which is a pain in the butt to work
537 # with. It's ok for us to "leak" the memory here because
538 # OpenSSL now owns it and will free it.
539 ocsp_data_length = len(ocsp_data)
540 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
541 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
542
543 _lib.SSL_set_tlsext_status_ocsp_resp(
544 ssl, data_ptr, ocsp_data_length
545 )
546
547 return 0
548 except Exception as e:
549 self._problems.append(e)
550 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
551
552 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
553
554
555class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
556 """
557 Wrap a callback such that it can be used as an OCSP callback for the client
558 side.
559
560 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
561 ways. For servers, that callback is expected to retrieve some OCSP data and
562 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
563 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
564 is expected to check the OCSP data, and returns a negative value on error,
565 0 if the response is not acceptable, or positive if it is. These are
566 mutually exclusive return code behaviours, and they mean that we need two
567 helpers so that we always return an appropriate error code if the user's
568 code throws an exception.
569
570 Given that we have to have two helpers anyway, these helpers are a bit more
571 helpery than most: specifically, they hide a few more of the OpenSSL
572 functions so that the user has an easier time writing these callbacks.
573
574 This helper implements the client side.
575 """
576
577 def __init__(self, callback):
578 _CallbackExceptionHelper.__init__(self)
579
580 @wraps(callback)
581 def wrapper(ssl, cdata):
582 try:
583 conn = Connection._reverse_mapping[ssl]
584
585 # Extract the data if any was provided.
586 if cdata != _ffi.NULL:
587 data = _ffi.from_handle(cdata)
588 else:
589 data = None
590
591 # Get the OCSP data.
592 ocsp_ptr = _ffi.new("unsigned char **")
593 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
594 if ocsp_len < 0:
595 # No OCSP data.
596 ocsp_data = b''
597 else:
598 # Copy the OCSP data, then pass it to the callback.
599 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
600
601 valid = callback(conn, ocsp_data, data)
602
603 # Return 1 on success or 0 on error.
604 return int(bool(valid))
605
606 except Exception as e:
607 self._problems.append(e)
608 # Return negative value if an exception is hit.
609 return -1
610
611 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
612
613
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800614def _asFileDescriptor(obj):
615 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800616 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800617 meth = getattr(obj, "fileno", None)
618 if meth is not None:
619 obj = meth()
620
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800621 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800622 fd = obj
623
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800624 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800625 raise TypeError("argument must be an int, or have a fileno() method.")
626 elif fd < 0:
627 raise ValueError(
628 "file descriptor cannot be a negative integer (%i)" % (fd,))
629
630 return fd
631
632
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800633def SSLeay_version(type):
634 """
635 Return a string describing the version of OpenSSL in use.
636
Alex Chand072cae2018-02-15 09:57:59 +0000637 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800638 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500639 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800640
641
Cory Benfieldef404df2016-03-29 15:32:48 +0100642def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400643 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100644 Builds a decorator that ensures that functions that rely on OpenSSL
645 functions that are not present in this build raise NotImplementedError,
646 rather than AttributeError coming out of cryptography.
647
648 :param flag: A cryptography flag that guards the functions, e.g.
649 ``Cryptography_HAS_NEXTPROTONEG``.
650 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400651 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100652 def _requires_decorator(func):
653 if not flag:
654 @wraps(func)
655 def explode(*args, **kwargs):
656 raise NotImplementedError(error)
657 return explode
658 else:
659 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400660
Cory Benfieldef404df2016-03-29 15:32:48 +0100661 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400662
663
Cory Benfieldef404df2016-03-29 15:32:48 +0100664_requires_npn = _make_requires(
665 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
666)
Cory Benfield7907e332015-04-13 17:18:25 -0400667
668
Cory Benfieldef404df2016-03-29 15:32:48 +0100669_requires_alpn = _make_requires(
670 _lib.Cryptography_HAS_ALPN, "ALPN not available"
671)
Cory Benfielde6f35882016-03-29 11:21:04 +0100672
Cory Benfielde6f35882016-03-29 11:21:04 +0100673
Cory Benfieldef404df2016-03-29 15:32:48 +0100674_requires_sni = _make_requires(
675 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
676)
Cory Benfielde6f35882016-03-29 11:21:04 +0100677
678
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800679class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000680 """
681 A class representing an SSL session. A session defines certain connection
682 parameters which may be re-used to speed up the setup of subsequent
683 connections.
684
685 .. versionadded:: 0.14
686 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800687 pass
688
689
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690class Context(object):
691 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100692 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400693 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000694
695 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
696 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 """
698 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800699 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500700 SSLv3_METHOD: "SSLv3_method",
701 SSLv23_METHOD: "SSLv23_method",
702 TLSv1_METHOD: "TLSv1_method",
703 TLSv1_1_METHOD: "TLSv1_1_method",
704 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400705 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500706 _methods = dict(
707 (identifier, getattr(_lib, name))
708 for (identifier, name) in _methods.items()
709 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800710
711 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500712 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713 raise TypeError("method must be an integer")
714
715 try:
716 method_func = self._methods[method]
717 except KeyError:
718 raise ValueError("No such protocol")
719
720 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700721 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800722
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500723 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700724 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500725 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800726
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600727 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
728 # will be auto-selected. This function was added in 1.0.2 and made a
729 # noop in 1.1.0+ (where it is set automatically).
730 try:
731 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
732 _openssl_assert(res == 1)
733 except AttributeError:
734 pass
735
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800736 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800737 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800739 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800740 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 self._verify_callback = None
742 self._info_callback = None
743 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000745 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100746 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000747 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100748 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400749 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100750 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000751 self._ocsp_helper = None
752 self._ocsp_callback = None
753 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800754
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500755 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757 def load_verify_locations(self, cafile, capath=None):
758 """
759 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000760 chain. Note that the certificates have to be in PEM format.
761
762 If capath is passed, it must be a directory prepared using the
763 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
764 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800765
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400766 :param cafile: In which file we can find the certificates (``bytes`` or
767 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800768 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400769 (``bytes`` or ``unicode``).
770
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800771 :return: None
772 """
773 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500774 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400775 else:
776 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777
778 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500779 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400780 else:
781 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Alex Gaynor62da94d2015-09-05 14:37:34 -0400783 load_result = _lib.SSL_CTX_load_verify_locations(
784 self._context, cafile, capath
785 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500787 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789 def _wrap_callback(self, callback):
790 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800791 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792 return callback(size, verify, self._passphrase_userdata)
793 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800794 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800795
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800796 def set_passwd_cb(self, callback, userdata=None):
797 """
Alex Chand072cae2018-02-15 09:57:59 +0000798 Set the passphrase callback. This function will be called
799 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800
Alex Chand072cae2018-02-15 09:57:59 +0000801 :param callback: The Python callback to use. This must accept three
802 positional arguments. First, an integer giving the maximum length
803 of the passphrase it may return. If the returned passphrase is
804 longer than this, it will be truncated. Second, a boolean value
805 which will be true if the user should be prompted for the
806 passphrase twice and the callback should verify that the two values
807 supplied are equal. Third, the value given as the *userdata*
808 parameter to :meth:`set_passwd_cb`. The *callback* must return
809 a byte string. If an error occurs, *callback* should return a false
810 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800811 :param userdata: (optional) A Python object which will be given as
812 argument to the callback
813 :return: None
814 """
815 if not callable(callback):
816 raise TypeError("callback must be callable")
817
818 self._passphrase_helper = self._wrap_callback(callback)
819 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500820 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800821 self._context, self._passphrase_callback)
822 self._passphrase_userdata = userdata
823
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800824 def set_default_verify_paths(self):
825 """
Alex Chand072cae2018-02-15 09:57:59 +0000826 Specify that the platform provided CA certificates are to be used for
827 verification purposes. This method has some caveats related to the
828 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
829
830 * macOS will only load certificates using this method if the user has
831 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
832 in the default location.
833 * Windows will not work.
834 * manylinux1 cryptography wheels will work on most common Linux
835 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
836 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800837
838 :return: None
839 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500840 # SSL_CTX_set_default_verify_paths will attempt to load certs from
841 # both a cafile and capath that are set at compile time. However,
842 # it will first check environment variables and, if present, load
843 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500844 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400845 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500846 # After attempting to set default_verify_paths we need to know whether
847 # to go down the fallback path.
848 # First we'll check to see if any env vars have been set. If so,
849 # we won't try to do anything else because the user has set the path
850 # themselves.
851 dir_env_var = _ffi.string(
852 _lib.X509_get_default_cert_dir_env()
853 ).decode("ascii")
854 file_env_var = _ffi.string(
855 _lib.X509_get_default_cert_file_env()
856 ).decode("ascii")
857 if not self._check_env_vars_set(dir_env_var, file_env_var):
858 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
859 default_file = _ffi.string(_lib.X509_get_default_cert_file())
860 # Now we check to see if the default_dir and default_file are set
861 # to the exact values we use in our manylinux1 builds. If they are
862 # then we know to load the fallbacks
863 if (
864 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
865 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
866 ):
867 # This is manylinux1, let's load our fallback paths
868 self._fallback_default_verify_paths(
869 _CERTIFICATE_FILE_LOCATIONS,
870 _CERTIFICATE_PATH_LOCATIONS
871 )
872
873 def _check_env_vars_set(self, dir_env_var, file_env_var):
874 """
875 Check to see if the default cert dir/file environment vars are present.
876
877 :return: bool
878 """
879 return (
880 os.environ.get(file_env_var) is not None or
881 os.environ.get(dir_env_var) is not None
882 )
883
884 def _fallback_default_verify_paths(self, file_path, dir_path):
885 """
886 Default verify paths are based on the compiled version of OpenSSL.
887 However, when pyca/cryptography is compiled as a manylinux1 wheel
888 that compiled location can potentially be wrong. So, like Go, we
889 will try a predefined set of paths and attempt to load roots
890 from there.
891
892 :return: None
893 """
894 for cafile in file_path:
895 if os.path.isfile(cafile):
896 self.load_verify_locations(cafile)
897 break
898
899 for capath in dir_path:
900 if os.path.isdir(capath):
901 self.load_verify_locations(None, capath)
902 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800903
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800904 def use_certificate_chain_file(self, certfile):
905 """
Alex Chand072cae2018-02-15 09:57:59 +0000906 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400908 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000909 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400910
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911 :return: None
912 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400913 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800914
Alex Gaynor62da94d2015-09-05 14:37:34 -0400915 result = _lib.SSL_CTX_use_certificate_chain_file(
916 self._context, certfile
917 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800918 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500919 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800920
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800921 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 """
923 Load a certificate from a file
924
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400925 :param certfile: The name of the certificate file (``bytes`` or
926 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000927 :param filetype: (optional) The encoding of the file, which is either
928 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
929 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400930
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800931 :return: None
932 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400933 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500934 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800935 raise TypeError("filetype must be an integer")
936
Alex Gaynor62da94d2015-09-05 14:37:34 -0400937 use_result = _lib.SSL_CTX_use_certificate_file(
938 self._context, certfile, filetype
939 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800940 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500941 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800942
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943 def use_certificate(self, cert):
944 """
945 Load a certificate from a X509 object
946
947 :param cert: The X509 object
948 :return: None
949 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800950 if not isinstance(cert, X509):
951 raise TypeError("cert must be an X509 instance")
952
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500953 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800954 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500955 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800956
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800957 def add_extra_chain_cert(self, certobj):
958 """
959 Add certificate to chain
960
961 :param certobj: The X509 certificate object to add to the chain
962 :return: None
963 """
964 if not isinstance(certobj, X509):
965 raise TypeError("certobj must be an X509 instance")
966
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500967 copy = _lib.X509_dup(certobj._x509)
968 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800969 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500970 # TODO: This is untested.
971 _lib.X509_free(copy)
972 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800973
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800974 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500975 if self._passphrase_helper is not None:
976 self._passphrase_helper.raise_if_problem(Error)
977
978 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800979
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400980 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800981 """
982 Load a private key from a file
983
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400984 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000985 :param filetype: (optional) The encoding of the file, which is either
986 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
987 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400988
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 :return: None
990 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400991 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400993 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500995 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996 raise TypeError("filetype must be an integer")
997
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500998 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 self._context, keyfile, filetype)
1000 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001001 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001002
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003 def use_privatekey(self, pkey):
1004 """
1005 Load a private key from a PKey object
1006
1007 :param pkey: The PKey object
1008 :return: None
1009 """
1010 if not isinstance(pkey, PKey):
1011 raise TypeError("pkey must be a PKey instance")
1012
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001013 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001015 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001016
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017 def check_privatekey(self):
1018 """
Alex Chand072cae2018-02-15 09:57:59 +00001019 Check if the private key (loaded with :meth:`use_privatekey`) matches
1020 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021
Alex Chand072cae2018-02-15 09:57:59 +00001022 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001023 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001024 if not _lib.SSL_CTX_check_private_key(self._context):
1025 _raise_current_error()
1026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001027 def load_client_ca(self, cafile):
1028 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001029 Load the trusted certificates that will be sent to the client. Does
1030 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001031 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001033 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001034 :return: None
1035 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001036 ca_list = _lib.SSL_load_client_CA_file(
1037 _text_to_bytes_and_warn("cafile", cafile)
1038 )
1039 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001040 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041
1042 def set_session_id(self, buf):
1043 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001044 Set the session id to *buf* within which a session can be reused for
1045 this Context object. This is needed when doing session resumption,
1046 because there is no way for a stored session to know which Context
1047 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001048
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001049 :param bytes buf: The session id.
1050
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051 :returns: None
1052 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001053 buf = _text_to_bytes_and_warn("buf", buf)
1054 _openssl_assert(
1055 _lib.SSL_CTX_set_session_id_context(
1056 self._context,
1057 buf,
1058 len(buf),
1059 ) == 1
1060 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
1062 def set_session_cache_mode(self, mode):
1063 """
Alex Chand072cae2018-02-15 09:57:59 +00001064 Set the behavior of the session cache used by all connections using
1065 this Context. The previously set mode is returned. See
1066 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067
1068 :param mode: One or more of the SESS_CACHE_* flags (combine using
1069 bitwise or)
1070 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001071
1072 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001074 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075 raise TypeError("mode must be an integer")
1076
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001078
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001079 def get_session_cache_mode(self):
1080 """
Alex Chand072cae2018-02-15 09:57:59 +00001081 Get the current session cache mode.
1082
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001084
1085 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001088
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001089 def set_verify(self, mode, callback):
1090 """
Alex Chand072cae2018-02-15 09:57:59 +00001091 et the verification flags for this Context object to *mode* and specify
1092 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093
Alex Chand072cae2018-02-15 09:57:59 +00001094 :param mode: The verify mode, this should be one of
1095 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1096 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1097 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1098 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1099 :param callback: The Python callback to use. This should take five
1100 arguments: A Connection object, an X509 object, and three integer
1101 variables, which are in turn potential error number, error depth
1102 and return code. *callback* should return True if verification
1103 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001104 :return: None
1105
1106 See SSL_CTX_set_verify(3SSL) for further details.
1107 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001108 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 raise TypeError("mode must be an integer")
1110
1111 if not callable(callback):
1112 raise TypeError("callback must be callable")
1113
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001114 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001115 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001116 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001117
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001118 def set_verify_depth(self, depth):
1119 """
Alex Chand072cae2018-02-15 09:57:59 +00001120 Set the maximum depth for the certificate chain verification that shall
1121 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122
1123 :param depth: An integer specifying the verify depth
1124 :return: None
1125 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001126 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127 raise TypeError("depth must be an integer")
1128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001129 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001130
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001131 def get_verify_mode(self):
1132 """
Alex Chand072cae2018-02-15 09:57:59 +00001133 Retrieve the Context object's verify mode, as set by
1134 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001135
1136 :return: The verify mode
1137 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001138 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001139
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001140 def get_verify_depth(self):
1141 """
Alex Chand072cae2018-02-15 09:57:59 +00001142 Retrieve the Context object's verify depth, as set by
1143 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144
1145 :return: The verify depth
1146 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001147 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001148
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001149 def load_tmp_dh(self, dhfile):
1150 """
1151 Load parameters for Ephemeral Diffie-Hellman
1152
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001153 :param dhfile: The file to load EDH parameters from (``bytes`` or
1154 ``unicode``).
1155
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001156 :return: None
1157 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001158 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001159
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001160 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001162 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001164
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1166 dh = _ffi.gc(dh, _lib.DH_free)
1167 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001168
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001169 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001170 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001171 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001172
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001173 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001174 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1175 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001176
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001177 :return: None
1178 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001179 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001180
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001181 def set_cipher_list(self, cipher_list):
1182 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001183 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001185 See the OpenSSL manual for more information (e.g.
1186 :manpage:`ciphers(1)`).
1187
1188 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001189 :return: None
1190 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001191 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001192
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001193 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001194 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001195
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001196 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001197 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001198 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001199
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001200 def set_client_ca_list(self, certificate_authorities):
1201 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001202 Set the list of preferred client certificate signers for this server
1203 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204
Alex Gaynor62da94d2015-09-05 14:37:34 -04001205 This list of certificate authorities will be sent to the client when
1206 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207
1208 :param certificate_authorities: a sequence of X509Names.
1209 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001210
1211 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001212 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001213 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001214 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001215
1216 try:
1217 for ca_name in certificate_authorities:
1218 if not isinstance(ca_name, X509Name):
1219 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001220 "client CAs must be X509Name objects, not %s "
1221 "objects" % (
1222 type(ca_name).__name__,
1223 )
1224 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001225 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001226 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001227 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001228 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001229 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001230 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001231 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001232 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001233 raise
1234
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001235 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001236
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001237 def add_client_ca(self, certificate_authority):
1238 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001239 Add the CA certificate to the list of preferred signers for this
1240 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001241
1242 The list of certificate authorities will be sent to the client when the
1243 server requests a client certificate.
1244
1245 :param certificate_authority: certificate authority's X509 certificate.
1246 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001247
1248 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001249 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001250 if not isinstance(certificate_authority, X509):
1251 raise TypeError("certificate_authority must be an X509 instance")
1252
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001253 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001254 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001255 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001256
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001257 def set_timeout(self, timeout):
1258 """
Alex Chand072cae2018-02-15 09:57:59 +00001259 Set the timeout for newly created sessions for this Context object to
1260 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1261 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001262
Alex Chand072cae2018-02-15 09:57:59 +00001263 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264 :return: The previous session timeout
1265 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001266 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001267 raise TypeError("timeout must be an integer")
1268
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001269 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001270
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001271 def get_timeout(self):
1272 """
Alex Chand072cae2018-02-15 09:57:59 +00001273 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1274 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001275
1276 :return: The session timeout
1277 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001279
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001280 def set_info_callback(self, callback):
1281 """
Alex Chand072cae2018-02-15 09:57:59 +00001282 Set the information callback to *callback*. This function will be
1283 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001284
Alex Chand072cae2018-02-15 09:57:59 +00001285 :param callback: The Python callback to use. This should take three
1286 arguments: a Connection object and two integers. The first integer
1287 specifies where in the SSL handshake the function was called, and
1288 the other the return code from a (possibly failed) internal
1289 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001290 :return: None
1291 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001292 @wraps(callback)
1293 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001294 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001295 self._info_callback = _ffi.callback(
1296 "void (*)(const SSL *, int, int)", wrapper)
1297 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001298
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001299 def get_app_data(self):
1300 """
Alex Chand072cae2018-02-15 09:57:59 +00001301 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001302
1303 :return: The application data
1304 """
1305 return self._app_data
1306
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001307 def set_app_data(self, data):
1308 """
1309 Set the application data (will be returned from get_app_data())
1310
1311 :param data: Any Python object
1312 :return: None
1313 """
1314 self._app_data = data
1315
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001316 def get_cert_store(self):
1317 """
Alex Chand072cae2018-02-15 09:57:59 +00001318 Get the certificate store for the context. This can be used to add
1319 "trusted" certificates without using the
1320 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001321
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001322 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001323 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001324 store = _lib.SSL_CTX_get_cert_store(self._context)
1325 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001326 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001327 return None
1328
1329 pystore = X509Store.__new__(X509Store)
1330 pystore._store = store
1331 return pystore
1332
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001333 def set_options(self, options):
1334 """
1335 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001336 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001337
1338 :param options: The options to add.
1339 :return: The new option bitmask.
1340 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001341 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001342 raise TypeError("options must be an integer")
1343
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001344 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001345
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001346 def set_mode(self, mode):
1347 """
Alex Chand072cae2018-02-15 09:57:59 +00001348 Add modes via bitmask. Modes set before are not cleared! This method
1349 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001350
1351 :param mode: The mode to add.
1352 :return: The new mode bitmask.
1353 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001354 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001355 raise TypeError("mode must be an integer")
1356
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001357 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001358
Cory Benfielde6f35882016-03-29 11:21:04 +01001359 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001360 def set_tlsext_servername_callback(self, callback):
1361 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001362 Specify a callback function to be called when clients specify a server
1363 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001364
1365 :param callback: The callback function. It will be invoked with one
1366 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001367
1368 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001369 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001370 @wraps(callback)
1371 def wrapper(ssl, alert, arg):
1372 callback(Connection._reverse_mapping[ssl])
1373 return 0
1374
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001375 self._tlsext_servername_callback = _ffi.callback(
1376 "int (*)(const SSL *, int *, void *)", wrapper)
1377 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001378 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001379
Cory Benfield10b277f2015-04-13 17:12:42 -04001380 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001381 def set_npn_advertise_callback(self, callback):
1382 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001383 Specify a callback function that will be called when offering `Next
1384 Protocol Negotiation
1385 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001386
1387 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001388 argument, the :class:`Connection` instance. It should return a
1389 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001390 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001391
1392 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001393 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001394 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1395 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001396 _lib.SSL_CTX_set_next_protos_advertised_cb(
1397 self._context, self._npn_advertise_callback, _ffi.NULL)
1398
Cory Benfield10b277f2015-04-13 17:12:42 -04001399 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001400 def set_npn_select_callback(self, callback):
1401 """
1402 Specify a callback function that will be called when a server offers
1403 Next Protocol Negotiation options.
1404
1405 :param callback: The callback function. It will be invoked with two
1406 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001407 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1408 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001409
1410 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001411 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001412 self._npn_select_helper = _NpnSelectHelper(callback)
1413 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001414 _lib.SSL_CTX_set_next_proto_select_cb(
1415 self._context, self._npn_select_callback, _ffi.NULL)
1416
Cory Benfield7907e332015-04-13 17:18:25 -04001417 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001418 def set_alpn_protos(self, protos):
1419 """
Alex Chand072cae2018-02-15 09:57:59 +00001420 Specify the protocols that the client is prepared to speak after the
1421 TLS connection has been negotiated using Application Layer Protocol
1422 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001423
1424 :param protos: A list of the protocols to be offered to the server.
1425 This list should be a Python list of bytestrings representing the
1426 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1427 """
1428 # Take the list of protocols and join them together, prefixing them
1429 # with their lengths.
1430 protostr = b''.join(
1431 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1432 )
1433
1434 # Build a C string from the list. We don't need to save this off
1435 # because OpenSSL immediately copies the data out.
1436 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001437 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001438
Cory Benfield7907e332015-04-13 17:18:25 -04001439 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001440 def set_alpn_select_callback(self, callback):
1441 """
Alex Chand072cae2018-02-15 09:57:59 +00001442 Specify a callback function that will be called on the server when a
1443 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001444
1445 :param callback: The callback function. It will be invoked with two
1446 arguments: the Connection, and a list of offered protocols as
1447 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001448 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001449 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001450 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001451 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001452 _lib.SSL_CTX_set_alpn_select_cb(
1453 self._context, self._alpn_select_callback, _ffi.NULL)
1454
Cory Benfield496652a2017-01-24 11:42:56 +00001455 def _set_ocsp_callback(self, helper, data):
1456 """
1457 This internal helper does the common work for
1458 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1459 almost all of it.
1460 """
1461 self._ocsp_helper = helper
1462 self._ocsp_callback = helper.callback
1463 if data is None:
1464 self._ocsp_data = _ffi.NULL
1465 else:
1466 self._ocsp_data = _ffi.new_handle(data)
1467
1468 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1469 self._context, self._ocsp_callback
1470 )
1471 _openssl_assert(rc == 1)
1472 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1473 _openssl_assert(rc == 1)
1474
1475 def set_ocsp_server_callback(self, callback, data=None):
1476 """
1477 Set a callback to provide OCSP data to be stapled to the TLS handshake
1478 on the server side.
1479
1480 :param callback: The callback function. It will be invoked with two
1481 arguments: the Connection, and the optional arbitrary data you have
1482 provided. The callback must return a bytestring that contains the
1483 OCSP data to staple to the handshake. If no OCSP data is available
1484 for this connection, return the empty bytestring.
1485 :param data: Some opaque data that will be passed into the callback
1486 function when called. This can be used to avoid needing to do
1487 complex data lookups or to keep track of what context is being
1488 used. This parameter is optional.
1489 """
1490 helper = _OCSPServerCallbackHelper(callback)
1491 self._set_ocsp_callback(helper, data)
1492
1493 def set_ocsp_client_callback(self, callback, data=None):
1494 """
1495 Set a callback to validate OCSP data stapled to the TLS handshake on
1496 the client side.
1497
1498 :param callback: The callback function. It will be invoked with three
1499 arguments: the Connection, a bytestring containing the stapled OCSP
1500 assertion, and the optional arbitrary data you have provided. The
1501 callback must return a boolean that indicates the result of
1502 validating the OCSP data: ``True`` if the OCSP data is valid and
1503 the certificate can be trusted, or ``False`` if either the OCSP
1504 data is invalid or the certificate has been revoked.
1505 :param data: Some opaque data that will be passed into the callback
1506 function when called. This can be used to avoid needing to do
1507 complex data lookups or to keep track of what context is being
1508 used. This parameter is optional.
1509 """
1510 helper = _OCSPClientCallbackHelper(callback)
1511 self._set_ocsp_callback(helper, data)
1512
Alex Chanc6077062016-11-18 13:53:39 +00001513
Alex Gaynor10d30832017-06-29 15:31:39 -07001514ContextType = deprecated(
1515 Context, __name__,
1516 "ContextType has been deprecated, use Context instead", DeprecationWarning
1517)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001518
1519
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001520class Connection(object):
1521 """
1522 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001523 _reverse_mapping = WeakValueDictionary()
1524
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001525 def __init__(self, context, socket=None):
1526 """
1527 Create a new Connection object, using the given OpenSSL.SSL.Context
1528 instance and socket.
1529
1530 :param context: An SSL Context to use for this connection
1531 :param socket: The socket to use for transport layer
1532 """
1533 if not isinstance(context, Context):
1534 raise TypeError("context must be a Context instance")
1535
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001536 ssl = _lib.SSL_new(context._context)
1537 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001539 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001540
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001541 # References to strings used for Next Protocol Negotiation. OpenSSL's
1542 # header files suggest that these might get copied at some point, but
1543 # doesn't specify when, so we store them here to make sure they don't
1544 # get freed before OpenSSL uses them.
1545 self._npn_advertise_callback_args = None
1546 self._npn_select_callback_args = None
1547
Cory Benfield12eae892014-06-07 15:42:56 +01001548 # References to strings used for Application Layer Protocol
1549 # Negotiation. These strings get copied at some point but it's well
1550 # after the callback returns, so we have to hang them somewhere to
1551 # avoid them getting freed.
1552 self._alpn_select_callback_args = None
1553
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001554 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001555
1556 if socket is None:
1557 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001558 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001559 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001560 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001561
Alex Gaynora829e902016-06-04 18:16:01 -07001562 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1563 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001564
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001565 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001566 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567 self._into_ssl = None
1568 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001569 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001570 set_result = _lib.SSL_set_fd(
1571 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001572 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001573
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574 def __getattr__(self, name):
1575 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001576 Look up attributes on the wrapped socket object if they are not found
1577 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578 """
kjav0b66fa12015-09-02 11:51:26 +01001579 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001580 raise AttributeError("'%s' object has no attribute '%s'" % (
1581 self.__class__.__name__, name
1582 ))
kjav0b66fa12015-09-02 11:51:26 +01001583 else:
1584 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001587 if self._context._verify_helper is not None:
1588 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001589 if self._context._npn_advertise_helper is not None:
1590 self._context._npn_advertise_helper.raise_if_problem()
1591 if self._context._npn_select_helper is not None:
1592 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001593 if self._context._alpn_select_helper is not None:
1594 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001595 if self._context._ocsp_helper is not None:
1596 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001597
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001598 error = _lib.SSL_get_error(ssl, result)
1599 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001600 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001601 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001602 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001605 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001606 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001607 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001608 elif error == _lib.SSL_ERROR_SYSCALL:
1609 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001610 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001611 if platform == "win32":
1612 errno = _ffi.getwinerror()[0]
1613 else:
1614 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001615
1616 if errno != 0:
1617 raise SysCallError(errno, errorcode.get(errno))
1618 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001620 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001621 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001622 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001623 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001624 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001625 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001626
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001627 def get_context(self):
1628 """
Alex Chand072cae2018-02-15 09:57:59 +00001629 Retrieve the :class:`Context` object associated with this
1630 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001634 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635 """
Alex Chand072cae2018-02-15 09:57:59 +00001636 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637
Alex Chand072cae2018-02-15 09:57:59 +00001638 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001640 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001641 if not isinstance(context, Context):
1642 raise TypeError("context must be a Context instance")
1643
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001644 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001645 self._context = context
1646
Cory Benfielde6f35882016-03-29 11:21:04 +01001647 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001648 def get_servername(self):
1649 """
1650 Retrieve the servername extension value if provided in the client hello
1651 message, or None if there wasn't one.
1652
Alex Chand072cae2018-02-15 09:57:59 +00001653 :return: A byte string giving the server name or :data:`None`.
1654
1655 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001657 name = _lib.SSL_get_servername(
1658 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1659 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001660 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001661 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001663 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664
Cory Benfielde6f35882016-03-29 11:21:04 +01001665 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001667 """
1668 Set the value of the servername extension to send in the client hello.
1669
1670 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001671
1672 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674 if not isinstance(name, bytes):
1675 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001676 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001677 raise TypeError("name must not contain NUL byte")
1678
1679 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001680 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682 def pending(self):
1683 """
Alex Chand072cae2018-02-15 09:57:59 +00001684 Get the number of bytes that can be safely read from the SSL buffer
1685 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686
1687 :return: The number of bytes available in the receive buffer.
1688 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001690
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001691 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001692 """
1693 Send data on the connection. NOTE: If you get one of the WantRead,
1694 WantWrite or WantX509Lookup exceptions on this, you have to call the
1695 method again with the SAME buffer.
1696
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001697 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001698 :param flags: (optional) Included for compatibility with the socket
1699 API, the value is ignored
1700 :return: The number of bytes written
1701 """
Abraham Martine82326c2015-02-04 10:18:10 +00001702 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001703 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001704
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001705 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001706 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001707 if isinstance(buf, _buffer):
1708 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001710 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001711 if len(buf) > 2147483647:
1712 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001713
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001714 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001715 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001716 return result
1717 write = send
1718
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001719 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001720 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001721 Send "all" data on the connection. This calls send() repeatedly until
1722 all data is sent. If an error occurs, it's impossible to tell how much
1723 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001725 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 :param flags: (optional) Included for compatibility with the socket
1727 API, the value is ignored
1728 :return: The number of bytes written
1729 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001730 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001731
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001732 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001733 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001734 if isinstance(buf, _buffer):
1735 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001736 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001737 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001738
1739 left_to_send = len(buf)
1740 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001741 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742
1743 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001744 # SSL_write's num arg is an int,
1745 # so we cannot send more than 2**31-1 bytes at once.
1746 result = _lib.SSL_write(
1747 self._ssl,
1748 data + total_sent,
1749 min(left_to_send, 2147483647)
1750 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 self._raise_ssl_error(self._ssl, result)
1752 total_sent += result
1753 left_to_send -= result
1754
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001755 def recv(self, bufsiz, flags=None):
1756 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001757 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001758
1759 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001760 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1761 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001762 :return: The string read from the Connection
1763 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001764 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001765 if flags is not None and flags & socket.MSG_PEEK:
1766 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1767 else:
1768 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001769 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001770 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001771 read = recv
1772
Cory Benfield62d10332014-06-15 10:03:41 +01001773 def recv_into(self, buffer, nbytes=None, flags=None):
1774 """
Alex Chand072cae2018-02-15 09:57:59 +00001775 Receive data on the connection and copy it directly into the provided
1776 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001777
1778 :param buffer: The buffer to copy into.
1779 :param nbytes: (optional) The maximum number of bytes to read into the
1780 buffer. If not present, defaults to the size of the buffer. If
1781 larger than the size of the buffer, is reduced to the size of the
1782 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001783 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1784 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001785 :return: The number of bytes read into the buffer.
1786 """
1787 if nbytes is None:
1788 nbytes = len(buffer)
1789 else:
1790 nbytes = min(nbytes, len(buffer))
1791
1792 # We need to create a temporary buffer. This is annoying, it would be
1793 # better if we could pass memoryviews straight into the SSL_read call,
1794 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001795 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001796 if flags is not None and flags & socket.MSG_PEEK:
1797 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1798 else:
1799 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001800 self._raise_ssl_error(self._ssl, result)
1801
1802 # This strange line is all to avoid a memory copy. The buffer protocol
1803 # should allow us to assign a CFFI buffer to the LHS of this line, but
1804 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1805 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1806 # memoryview type.
1807 try:
1808 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1809 except NameError:
1810 buffer[:result] = _ffi.buffer(buf, result)
1811
1812 return result
1813
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001814 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001815 if _lib.BIO_should_retry(bio):
1816 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001817 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001818 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001819 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001820 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001822 # TODO: This is untested. I think io_special means the socket
1823 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001824 raise ValueError("BIO_should_io_special")
1825 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001826 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001827 raise ValueError("unknown bio failure")
1828 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001829 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001830 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001831
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001832 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001833 """
Alex Chand072cae2018-02-15 09:57:59 +00001834 If the Connection was created with a memory BIO, this method can be
1835 used to read bytes from the write end of that memory BIO. Many
1836 Connection methods will add bytes which must be read in this manner or
1837 the buffer will eventually fill up and the Connection will be able to
1838 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839
1840 :param bufsiz: The maximum number of bytes to read
1841 :return: The string read.
1842 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001843 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001844 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001845
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001846 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001847 raise TypeError("bufsiz must be an integer")
1848
Cory Benfielde62840e2016-11-28 12:17:08 +00001849 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001850 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001851 if result <= 0:
1852 self._handle_bio_errors(self._from_ssl, result)
1853
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001855
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001856 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857 """
Alex Chand072cae2018-02-15 09:57:59 +00001858 If the Connection was created with a memory BIO, this method can be
1859 used to add bytes to the read end of that memory BIO. The Connection
1860 can then read the bytes (for example, in response to a call to
1861 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001862
1863 :param buf: The string to put into the memory BIO.
1864 :return: The number of bytes written
1865 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001866 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001867
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001868 if self._into_ssl is None:
1869 raise TypeError("Connection sock was not None")
1870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001871 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001872 if result <= 0:
1873 self._handle_bio_errors(self._into_ssl, result)
1874 return result
1875
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001876 def renegotiate(self):
1877 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001878 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001880 :return: True if the renegotiation can be started, False otherwise
1881 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001882 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001883 if not self.renegotiate_pending():
1884 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1885 return True
1886 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001887
1888 def do_handshake(self):
1889 """
Alex Chand072cae2018-02-15 09:57:59 +00001890 Perform an SSL handshake (usually called after :meth:`renegotiate` or
1891 one of :meth:`set_accept_state` or :meth:`set_accept_state`). This can
1892 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001893
1894 :return: None.
1895 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001896 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001897 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001899 def renegotiate_pending(self):
1900 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001901 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001902 a renegotiation is finished.
1903
1904 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001905 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001907 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001908
1909 def total_renegotiations(self):
1910 """
1911 Find out the total number of renegotiations.
1912
1913 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001914 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001916 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001918 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001919 """
Alex Chand072cae2018-02-15 09:57:59 +00001920 Call the :meth:`connect` method of the underlying socket and set up SSL
1921 on the socket, using the :class:`Context` object supplied to this
1922 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923
1924 :param addr: A remote address
1925 :return: What the socket's connect method returns
1926 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001927 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001928 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001930 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001931 """
Alex Chand072cae2018-02-15 09:57:59 +00001932 Call the :meth:`connect_ex` method of the underlying socket and set up
1933 SSL on the socket, using the Context object supplied to this Connection
1934 object at creation. Note that if the :meth:`connect_ex` method of the
1935 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936
1937 :param addr: A remove address
1938 :return: What the socket's connect_ex method returns
1939 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001940 connect_ex = self._socket.connect_ex
1941 self.set_connect_state()
1942 return connect_ex(addr)
1943
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001944 def accept(self):
1945 """
Alex Chand072cae2018-02-15 09:57:59 +00001946 Call the :meth:`accept` method of the underlying socket and set up SSL
1947 on the returned socket, using the Context object supplied to this
1948 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001949
Alex Chand072cae2018-02-15 09:57:59 +00001950 :return: A *(conn, addr)* pair where *conn* is the new
1951 :class:`Connection` object created, and *address* is as returned by
1952 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001953 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001954 client, addr = self._socket.accept()
1955 conn = Connection(self._context, client)
1956 conn.set_accept_state()
1957 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001959 def bio_shutdown(self):
1960 """
Alex Chand072cae2018-02-15 09:57:59 +00001961 If the Connection was created with a memory BIO, this method can be
1962 used to indicate that *end of file* has been reached on the read end of
1963 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964
1965 :return: None
1966 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001967 if self._from_ssl is None:
1968 raise TypeError("Connection sock was not None")
1969
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001970 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001971
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001972 def shutdown(self):
1973 """
Alex Chand072cae2018-02-15 09:57:59 +00001974 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001975
1976 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00001977 have sent closure alerts), False otherwise (in which case you
1978 call :meth:`recv` or :meth:`send` when the connection becomes
1979 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001981 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001983 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001984 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001985 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001986 else:
1987 return False
1988
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989 def get_cipher_list(self):
1990 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001991 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001992
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001993 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994 """
1995 ciphers = []
1996 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001997 result = _lib.SSL_get_cipher_list(self._ssl, i)
1998 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002000 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 return ciphers
2002
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003 def get_client_ca_list(self):
2004 """
2005 Get CAs whose certificates are suggested for client authentication.
2006
Alex Chand072cae2018-02-15 09:57:59 +00002007 :return: If this is a server connection, the list of certificate
2008 authorities that will be sent or has been sent to the client, as
2009 controlled by this :class:`Connection`'s :class:`Context`.
2010
2011 If this is a client connection, the list will be empty until the
2012 connection with the server is established.
2013
2014 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002016 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2017 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002018 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002019 return []
2020
2021 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002022 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2023 name = _lib.sk_X509_NAME_value(ca_names, i)
2024 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002025 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002026
2027 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002028 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002029 result.append(pyname)
2030 return result
2031
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002032 def makefile(self):
2033 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002034 The makefile() method is not implemented, since there is no dup
2035 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002037 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002038 """
Alex Gaynor83284952015-09-05 10:43:30 -04002039 raise NotImplementedError(
2040 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002041
2042 def get_app_data(self):
2043 """
Alex Chand072cae2018-02-15 09:57:59 +00002044 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002045
2046 :return: The application data
2047 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002048 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002050 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002051 """
2052 Set application data
2053
Alex Chand072cae2018-02-15 09:57:59 +00002054 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002055 :return: None
2056 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002057 self._app_data = data
2058
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002059 def get_shutdown(self):
2060 """
Alex Chand072cae2018-02-15 09:57:59 +00002061 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002062
Alex Gaynor62da94d2015-09-05 14:37:34 -04002063 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2064 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002065 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002066 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002067
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002068 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002069 """
Alex Chand072cae2018-02-15 09:57:59 +00002070 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071
Alex Chand072cae2018-02-15 09:57:59 +00002072 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073 :return: None
2074 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002075 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002076 raise TypeError("state must be an integer")
2077
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002078 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002079
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002080 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002081 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002082 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002083
2084 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002085 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086 """
kjavc704a2e2015-09-07 12:12:27 +01002087 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002088
2089 def server_random(self):
2090 """
Alex Chand072cae2018-02-15 09:57:59 +00002091 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002092
2093 :return: A string representing the state
2094 """
Alex Gaynor93603062016-06-01 20:13:09 -07002095 session = _lib.SSL_get_session(self._ssl)
2096 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002097 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002098 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2099 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002100 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002101 _lib.SSL_get_server_random(self._ssl, outp, length)
2102 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002103
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002104 def client_random(self):
2105 """
Alex Chand072cae2018-02-15 09:57:59 +00002106 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002107
2108 :return: A string representing the state
2109 """
Alex Gaynor93603062016-06-01 20:13:09 -07002110 session = _lib.SSL_get_session(self._ssl)
2111 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002112 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002113
2114 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2115 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002116 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002117 _lib.SSL_get_client_random(self._ssl, outp, length)
2118 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002119
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002120 def master_key(self):
2121 """
Alex Chand072cae2018-02-15 09:57:59 +00002122 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123
2124 :return: A string representing the state
2125 """
Alex Gaynor93603062016-06-01 20:13:09 -07002126 session = _lib.SSL_get_session(self._ssl)
2127 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002128 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002129
2130 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2131 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002132 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002133 _lib.SSL_SESSION_get_master_key(session, outp, length)
2134 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002135
Paul Kehrerbdb76392017-12-01 04:54:32 +08002136 def export_keying_material(self, label, olen, context=None):
2137 """
2138 Obtain keying material for application use.
2139
Alex Chand072cae2018-02-15 09:57:59 +00002140 :param: label - a disambiguating label string as described in RFC 5705
2141 :param: olen - the length of the exported key material in bytes
2142 :param: context - a per-association context value
2143 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002144 """
2145 outp = _no_zero_allocator("unsigned char[]", olen)
2146 context_buf = _ffi.NULL
2147 context_len = 0
2148 use_context = 0
2149 if context is not None:
2150 context_buf = context
2151 context_len = len(context)
2152 use_context = 1
2153 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2154 label, len(label),
2155 context_buf, context_len,
2156 use_context)
2157 _openssl_assert(success == 1)
2158 return _ffi.buffer(outp, olen)[:]
2159
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002160 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002161 """
Alex Chand072cae2018-02-15 09:57:59 +00002162 Call the :meth:`shutdown` method of the underlying socket.
2163 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002164
2165 :return: What the socket's shutdown() method returns
2166 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002167 return self._socket.shutdown(*args, **kwargs)
2168
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002169 def get_peer_certificate(self):
2170 """
2171 Retrieve the other side's certificate (if any)
2172
2173 :return: The peer's certificate
2174 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002175 cert = _lib.SSL_get_peer_certificate(self._ssl)
2176 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002177 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002178 return None
2179
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002180 def get_peer_cert_chain(self):
2181 """
2182 Retrieve the other side's certificate (if any)
2183
2184 :return: A list of X509 instances giving the peer's certificate chain,
2185 or None if it does not have one.
2186 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002187 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2188 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002189 return None
2190
2191 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002192 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002193 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002194 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002195 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002196 result.append(pycert)
2197 return result
2198
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002199 def want_read(self):
2200 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002201 Checks if more data has to be read from the transport layer to complete
2202 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002203
2204 :return: True iff more data has to be read
2205 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002206 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002207
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002208 def want_write(self):
2209 """
2210 Checks if there is data to write to the transport layer to complete an
2211 operation.
2212
2213 :return: True iff there is data to write
2214 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002215 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002216
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002217 def set_accept_state(self):
2218 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002219 Set the connection to work in server mode. The handshake will be
2220 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002221
2222 :return: None
2223 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002224 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002225
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002226 def set_connect_state(self):
2227 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002228 Set the connection to work in client mode. The handshake will be
2229 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002230
2231 :return: None
2232 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002233 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002234
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002235 def get_session(self):
2236 """
2237 Returns the Session currently used.
2238
Alex Chand072cae2018-02-15 09:57:59 +00002239 :return: An instance of :class:`OpenSSL.SSL.Session` or
2240 :obj:`None` if no session exists.
2241
2242 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002243 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002244 session = _lib.SSL_get1_session(self._ssl)
2245 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002246 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002247
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002248 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002249 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002250 return pysession
2251
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002252 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002253 """
2254 Set the session to be used when the TLS/SSL connection is established.
2255
2256 :param session: A Session instance representing the session to use.
2257 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002258
2259 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002260 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002261 if not isinstance(session, Session):
2262 raise TypeError("session must be a Session instance")
2263
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002264 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002265 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002266 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002267
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002268 def _get_finished_message(self, function):
2269 """
Alex Chand072cae2018-02-15 09:57:59 +00002270 Helper to implement :meth:`get_finished` and
2271 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002272
Alex Chand072cae2018-02-15 09:57:59 +00002273 :param function: Either :data:`SSL_get_finished`: or
2274 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002275
Alex Chand072cae2018-02-15 09:57:59 +00002276 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002277 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002278 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002279 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002280 # The OpenSSL documentation says nothing about what might happen if the
2281 # count argument given is zero. Specifically, it doesn't say whether
2282 # the output buffer may be NULL in that case or not. Inspection of the
2283 # implementation reveals that it calls memcpy() unconditionally.
2284 # Section 7.1.4, paragraph 1 of the C standard suggests that
2285 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2286 # alone desirable) behavior (though it probably does on just about
2287 # every implementation...)
2288 #
2289 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2290 # one might expect) for the initial call so as to be safe against this
2291 # potentially undefined behavior.
2292 empty = _ffi.new("char[]", 0)
2293 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002294 if size == 0:
2295 # No Finished message so far.
2296 return None
2297
Cory Benfielde62840e2016-11-28 12:17:08 +00002298 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002299 function(self._ssl, buf, size)
2300 return _ffi.buffer(buf, size)[:]
2301
Fedor Brunner5747b932014-03-05 14:22:34 +01002302 def get_finished(self):
2303 """
Alex Chand072cae2018-02-15 09:57:59 +00002304 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002305
Alex Chand072cae2018-02-15 09:57:59 +00002306 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002307 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002308 :rtype: :class:`bytes` or :class:`NoneType`
2309
2310 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002311 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002312 return self._get_finished_message(_lib.SSL_get_finished)
2313
Fedor Brunner5747b932014-03-05 14:22:34 +01002314 def get_peer_finished(self):
2315 """
Alex Chand072cae2018-02-15 09:57:59 +00002316 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002317
Alex Chand072cae2018-02-15 09:57:59 +00002318 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002319 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002320 :rtype: :class:`bytes` or :class:`NoneType`
2321
2322 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002323 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002324 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002325
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002326 def get_cipher_name(self):
2327 """
2328 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002329
Alex Chand072cae2018-02-15 09:57:59 +00002330 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002331 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002332 :rtype: :class:`unicode` or :class:`NoneType`
2333
2334 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002335 """
2336 cipher = _lib.SSL_get_current_cipher(self._ssl)
2337 if cipher == _ffi.NULL:
2338 return None
2339 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002340 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2341 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002342
2343 def get_cipher_bits(self):
2344 """
2345 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002346
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002347 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002348 or :obj:`None` if no connection has been established.
2349 :rtype: :class:`int` or :class:`NoneType`
2350
2351 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002352 """
2353 cipher = _lib.SSL_get_current_cipher(self._ssl)
2354 if cipher == _ffi.NULL:
2355 return None
2356 else:
2357 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2358
2359 def get_cipher_version(self):
2360 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002361 Obtain the protocol version of the currently used cipher.
2362
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002363 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002364 or :obj:`None` if no connection has been established.
2365 :rtype: :class:`unicode` or :class:`NoneType`
2366
2367 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002368 """
2369 cipher = _lib.SSL_get_current_cipher(self._ssl)
2370 if cipher == _ffi.NULL:
2371 return None
2372 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002373 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002374 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002375
Jim Shaverabff1882015-05-27 09:15:55 -04002376 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002377 """
Alex Chand072cae2018-02-15 09:57:59 +00002378 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002379
2380 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002381 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002382 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002383 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002384 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002385 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002386 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002387
Jim Shaver208438c2015-05-28 09:52:38 -04002388 def get_protocol_version(self):
2389 """
Alex Chand072cae2018-02-15 09:57:59 +00002390 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002391
Alex Chand072cae2018-02-15 09:57:59 +00002392 :returns: The TLS version of the current connection. For example,
2393 it will return ``0x769`` for connections made over TLS version 1.
2394 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002395 """
2396 version = _lib.SSL_version(self._ssl)
2397 return version
2398
Cory Benfield10b277f2015-04-13 17:12:42 -04002399 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002400 def get_next_proto_negotiated(self):
2401 """
2402 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002403
2404 :returns: A bytestring of the protocol name. If no protocol has been
2405 negotiated yet, returns an empty string.
2406
2407 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002408 """
2409 data = _ffi.new("unsigned char **")
2410 data_len = _ffi.new("unsigned int *")
2411
2412 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2413
Cory Benfieldcd010f62014-05-15 19:00:27 +01002414 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002415
Cory Benfield7907e332015-04-13 17:18:25 -04002416 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002417 def set_alpn_protos(self, protos):
2418 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002419 Specify the client's ALPN protocol list.
2420
2421 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002422
2423 :param protos: A list of the protocols to be offered to the server.
2424 This list should be a Python list of bytestrings representing the
2425 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2426 """
2427 # Take the list of protocols and join them together, prefixing them
2428 # with their lengths.
2429 protostr = b''.join(
2430 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2431 )
2432
2433 # Build a C string from the list. We don't need to save this off
2434 # because OpenSSL immediately copies the data out.
2435 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002436 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002437
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002438 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002439 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002440 """
2441 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002442
2443 :returns: A bytestring of the protocol name. If no protocol has been
2444 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002445 """
Cory Benfield12eae892014-06-07 15:42:56 +01002446 data = _ffi.new("unsigned char **")
2447 data_len = _ffi.new("unsigned int *")
2448
2449 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2450
Cory Benfielde8e9c382015-04-11 17:33:48 -04002451 if not data_len:
2452 return b''
2453
Cory Benfield12eae892014-06-07 15:42:56 +01002454 return _ffi.buffer(data[0], data_len[0])[:]
2455
Cory Benfield496652a2017-01-24 11:42:56 +00002456 def request_ocsp(self):
2457 """
2458 Called to request that the server sends stapled OCSP data, if
2459 available. If this is not called on the client side then the server
2460 will not send OCSP data. Should be used in conjunction with
2461 :meth:`Context.set_ocsp_client_callback`.
2462 """
2463 rc = _lib.SSL_set_tlsext_status_type(
2464 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2465 )
2466 _openssl_assert(rc == 1)
2467
Cory Benfield12eae892014-06-07 15:42:56 +01002468
Alex Gaynor10d30832017-06-29 15:31:39 -07002469ConnectionType = deprecated(
2470 Connection, __name__,
2471 "ConnectionType has been deprecated, use Connection instead",
2472 DeprecationWarning
2473)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002474
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002475# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2476# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002477_lib.SSL_library_init()