blob: 32c038ab01de556e2920fb08fde71d70a96700fa [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Nicolas Karolak736c6212017-11-26 14:40:28 +010030__all__ = [
31 'OPENSSL_VERSION_NUMBER',
32 'SSLEAY_VERSION',
33 'SSLEAY_CFLAGS',
34 'SSLEAY_PLATFORM',
35 'SSLEAY_DIR',
36 'SSLEAY_BUILT_ON',
37 'SENT_SHUTDOWN',
38 'RECEIVED_SHUTDOWN',
39 'SSLv2_METHOD',
40 'SSLv3_METHOD',
41 'SSLv23_METHOD',
42 'TLSv1_METHOD',
43 'TLSv1_1_METHOD',
44 'TLSv1_2_METHOD',
45 'OP_NO_SSLv2',
46 'OP_NO_SSLv3',
47 'OP_NO_TLSv1',
48 'OP_NO_TLSv1_1',
49 'OP_NO_TLSv1_2',
50 'MODE_RELEASE_BUFFERS',
51 'OP_SINGLE_DH_USE',
52 'OP_SINGLE_ECDH_USE',
53 'OP_EPHEMERAL_RSA',
54 'OP_MICROSOFT_SESS_ID_BUG',
55 'OP_NETSCAPE_CHALLENGE_BUG',
56 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
57 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
58 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
59 'OP_MSIE_SSLV2_RSA_PADDING',
60 'OP_SSLEAY_080_CLIENT_DH_BUG',
61 'OP_TLS_D5_BUG',
62 'OP_TLS_BLOCK_PADDING_BUG',
63 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
64 'OP_CIPHER_SERVER_PREFERENCE',
65 'OP_TLS_ROLLBACK_BUG',
66 'OP_PKCS1_CHECK_1',
67 'OP_PKCS1_CHECK_2',
68 'OP_NETSCAPE_CA_DN_BUG',
69 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
70 'OP_NO_COMPRESSION',
71 'OP_NO_QUERY_MTU',
72 'OP_COOKIE_EXCHANGE',
73 'OP_NO_TICKET',
74 'OP_ALL',
75 'VERIFY_PEER',
76 'VERIFY_FAIL_IF_NO_PEER_CERT',
77 'VERIFY_CLIENT_ONCE',
78 'VERIFY_NONE',
79 'SESS_CACHE_OFF',
80 'SESS_CACHE_CLIENT',
81 'SESS_CACHE_SERVER',
82 'SESS_CACHE_BOTH',
83 'SESS_CACHE_NO_AUTO_CLEAR',
84 'SESS_CACHE_NO_INTERNAL_LOOKUP',
85 'SESS_CACHE_NO_INTERNAL_STORE',
86 'SESS_CACHE_NO_INTERNAL',
87 'SSL_ST_CONNECT',
88 'SSL_ST_ACCEPT',
89 'SSL_ST_MASK',
90 'SSL_ST_INIT',
91 'SSL_ST_BEFORE',
92 'SSL_ST_OK',
93 'SSL_ST_RENEGOTIATE',
94 'SSL_CB_LOOP',
95 'SSL_CB_EXIT',
96 'SSL_CB_READ',
97 'SSL_CB_WRITE',
98 'SSL_CB_ALERT',
99 'SSL_CB_READ_ALERT',
100 'SSL_CB_WRITE_ALERT',
101 'SSL_CB_ACCEPT_LOOP',
102 'SSL_CB_ACCEPT_EXIT',
103 'SSL_CB_CONNECT_LOOP',
104 'SSL_CB_CONNECT_EXIT',
105 'SSL_CB_HANDSHAKE_START',
106 'SSL_CB_HANDSHAKE_DONE',
107 'Error',
108 'WantReadError',
109 'WantWriteError',
110 'WantX509LookupError',
111 'ZeroReturnError',
112 'SysCallError',
113 'SSLeay_version',
114 'Session',
115 'Context',
116 'Connection'
117]
118
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500119try:
120 _memoryview = memoryview
121except NameError:
122 class _memoryview(object):
123 pass
124
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200125try:
126 _buffer = buffer
127except NameError:
128 class _buffer(object):
129 pass
130
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500131OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
132SSLEAY_VERSION = _lib.SSLEAY_VERSION
133SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
134SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
135SSLEAY_DIR = _lib.SSLEAY_DIR
136SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500138SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
139RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800140
141SSLv2_METHOD = 1
142SSLv3_METHOD = 2
143SSLv23_METHOD = 3
144TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500145TLSv1_1_METHOD = 5
146TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800147
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500148OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
149OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
150OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700151OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
152OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800153
Alex Gaynorbf012872016-06-04 13:18:39 -0700154MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900157OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
159OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
160OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400161OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
162 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
163)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
165OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400166OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
168OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
169OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
170OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
171OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
172OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
173OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
174OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
175OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400176OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
177 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
178)
Alex Gaynorbf012872016-06-04 13:18:39 -0700179OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
182OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400183OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800184
Alex Gaynorc4889812015-09-04 08:43:17 -0400185OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187VERIFY_PEER = _lib.SSL_VERIFY_PEER
188VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
189VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
190VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500192SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
193SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
194SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
195SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
196SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
197SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
198SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
199SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
202SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
203SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400204if _lib.Cryptography_HAS_SSL_ST:
205 SSL_ST_INIT = _lib.SSL_ST_INIT
206 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
207 SSL_ST_OK = _lib.SSL_ST_OK
208 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800209
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500210SSL_CB_LOOP = _lib.SSL_CB_LOOP
211SSL_CB_EXIT = _lib.SSL_CB_EXIT
212SSL_CB_READ = _lib.SSL_CB_READ
213SSL_CB_WRITE = _lib.SSL_CB_WRITE
214SSL_CB_ALERT = _lib.SSL_CB_ALERT
215SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
216SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
217SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
218SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
219SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
220SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
221SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
222SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800223
Paul Kehrer55fb3412017-06-29 18:44:08 -0500224# Taken from https://golang.org/src/crypto/x509/root_linux.go
225_CERTIFICATE_FILE_LOCATIONS = [
226 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
227 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
228 "/etc/ssl/ca-bundle.pem", # OpenSUSE
229 "/etc/pki/tls/cacert.pem", # OpenELEC
230 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
231]
232
233_CERTIFICATE_PATH_LOCATIONS = [
234 "/etc/ssl/certs", # SLES10/SLES11
235]
236
Paul Kehrera92a1a72017-07-19 15:53:23 +0200237# These values are compared to output from cffi's ffi.string so they must be
238# byte strings.
239_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
240_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500241
Alex Gaynor83284952015-09-05 10:43:30 -0400242
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500244 """
245 An error occurred in an `OpenSSL.SSL` API.
246 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247
248
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500249_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100250_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251
252
253class WantReadError(Error):
254 pass
255
256
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500257class WantWriteError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class WantX509LookupError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class ZeroReturnError(Error):
266 pass
267
268
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269class SysCallError(Error):
270 pass
271
272
Cory Benfield0ea76e72015-03-22 09:05:28 +0000273class _CallbackExceptionHelper(object):
274 """
275 A base class for wrapper classes that allow for intelligent exception
276 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500277
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400278 :ivar list _problems: Any exceptions that occurred while executing in a
279 context where they could not be raised in the normal way. Typically
280 this is because OpenSSL has called into some Python code and requires a
281 return value. The exceptions are saved to be raised later when it is
282 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000283 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400284
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400285 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800286 self._problems = []
287
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400289 """
290 Raise an exception from the OpenSSL error queue or that was previously
291 captured whe running a callback.
292 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000293 if self._problems:
294 try:
295 _raise_current_error()
296 except Error:
297 pass
298 raise self._problems.pop(0)
299
300
301class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400302 """
303 Wrap a callback such that it can be used as a certificate verification
304 callback.
305 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400306
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800307 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400308 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800309
310 @wraps(callback)
311 def wrapper(ok, store_ctx):
312 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500313 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
314 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
315 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800316
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400317 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
318 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
319 connection = Connection._reverse_mapping[ssl]
320
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800321 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400322 result = callback(
323 connection, cert, error_number, error_depth, ok
324 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325 except Exception as e:
326 self._problems.append(e)
327 return 0
328 else:
329 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500330 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800331 return 1
332 else:
333 return 0
334
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500335 self.callback = _ffi.callback(
336 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800337
338
Cory Benfield0ea76e72015-03-22 09:05:28 +0000339class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400340 """
341 Wrap a callback such that it can be used as an NPN advertisement callback.
342 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400343
Cory Benfield0ea76e72015-03-22 09:05:28 +0000344 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400345 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800346
Cory Benfield0ea76e72015-03-22 09:05:28 +0000347 @wraps(callback)
348 def wrapper(ssl, out, outlen, arg):
349 try:
350 conn = Connection._reverse_mapping[ssl]
351 protos = callback(conn)
352
353 # Join the protocols into a Python bytestring, length-prefixing
354 # each element.
355 protostr = b''.join(
356 chain.from_iterable((int2byte(len(p)), p) for p in protos)
357 )
358
359 # Save our callback arguments on the connection object. This is
360 # done to make sure that they don't get freed before OpenSSL
361 # uses them. Then, return them appropriately in the output
362 # parameters.
363 conn._npn_advertise_callback_args = [
364 _ffi.new("unsigned int *", len(protostr)),
365 _ffi.new("unsigned char[]", protostr),
366 ]
367 outlen[0] = conn._npn_advertise_callback_args[0][0]
368 out[0] = conn._npn_advertise_callback_args[1]
369 return 0
370 except Exception as e:
371 self._problems.append(e)
372 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
373
374 self.callback = _ffi.callback(
375 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
376 wrapper
377 )
378
379
380class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400381 """
382 Wrap a callback such that it can be used as an NPN selection callback.
383 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400384
Cory Benfield0ea76e72015-03-22 09:05:28 +0000385 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400386 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000387
388 @wraps(callback)
389 def wrapper(ssl, out, outlen, in_, inlen, arg):
390 try:
391 conn = Connection._reverse_mapping[ssl]
392
393 # The string passed to us is actually made up of multiple
394 # length-prefixed bytestrings. We need to split that into a
395 # list.
396 instr = _ffi.buffer(in_, inlen)[:]
397 protolist = []
398 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500399 length = indexbytes(instr, 0)
400 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000401 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500402 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000403
404 # Call the callback
405 outstr = callback(conn, protolist)
406
407 # Save our callback arguments on the connection object. This is
408 # done to make sure that they don't get freed before OpenSSL
409 # uses them. Then, return them appropriately in the output
410 # parameters.
411 conn._npn_select_callback_args = [
412 _ffi.new("unsigned char *", len(outstr)),
413 _ffi.new("unsigned char[]", outstr),
414 ]
415 outlen[0] = conn._npn_select_callback_args[0][0]
416 out[0] = conn._npn_select_callback_args[1]
417 return 0
418 except Exception as e:
419 self._problems.append(e)
420 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
421
422 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400423 ("int (*)(SSL *, unsigned char **, unsigned char *, "
424 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000425 wrapper
426 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800427
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800428
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400429class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400430 """
431 Wrap a callback such that it can be used as an ALPN selection callback.
432 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400433
Cory Benfieldf1177e72015-04-12 09:11:49 -0400434 def __init__(self, callback):
435 _CallbackExceptionHelper.__init__(self)
436
437 @wraps(callback)
438 def wrapper(ssl, out, outlen, in_, inlen, arg):
439 try:
440 conn = Connection._reverse_mapping[ssl]
441
442 # The string passed to us is made up of multiple
443 # length-prefixed bytestrings. We need to split that into a
444 # list.
445 instr = _ffi.buffer(in_, inlen)[:]
446 protolist = []
447 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400448 encoded_len = indexbytes(instr, 0)
449 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400450 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400451 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400452
453 # Call the callback
454 outstr = callback(conn, protolist)
455
456 if not isinstance(outstr, _binary_type):
457 raise TypeError("ALPN callback must return a bytestring.")
458
459 # Save our callback arguments on the connection object to make
460 # sure that they don't get freed before OpenSSL can use them.
461 # Then, return them in the appropriate output parameters.
462 conn._alpn_select_callback_args = [
463 _ffi.new("unsigned char *", len(outstr)),
464 _ffi.new("unsigned char[]", outstr),
465 ]
466 outlen[0] = conn._alpn_select_callback_args[0][0]
467 out[0] = conn._alpn_select_callback_args[1]
468 return 0
469 except Exception as e:
470 self._problems.append(e)
471 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
472
473 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400474 ("int (*)(SSL *, unsigned char **, unsigned char *, "
475 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400476 wrapper
477 )
478
479
Cory Benfield496652a2017-01-24 11:42:56 +0000480class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
481 """
482 Wrap a callback such that it can be used as an OCSP callback for the server
483 side.
484
485 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
486 ways. For servers, that callback is expected to retrieve some OCSP data and
487 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
488 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
489 is expected to check the OCSP data, and returns a negative value on error,
490 0 if the response is not acceptable, or positive if it is. These are
491 mutually exclusive return code behaviours, and they mean that we need two
492 helpers so that we always return an appropriate error code if the user's
493 code throws an exception.
494
495 Given that we have to have two helpers anyway, these helpers are a bit more
496 helpery than most: specifically, they hide a few more of the OpenSSL
497 functions so that the user has an easier time writing these callbacks.
498
499 This helper implements the server side.
500 """
501
502 def __init__(self, callback):
503 _CallbackExceptionHelper.__init__(self)
504
505 @wraps(callback)
506 def wrapper(ssl, cdata):
507 try:
508 conn = Connection._reverse_mapping[ssl]
509
510 # Extract the data if any was provided.
511 if cdata != _ffi.NULL:
512 data = _ffi.from_handle(cdata)
513 else:
514 data = None
515
516 # Call the callback.
517 ocsp_data = callback(conn, data)
518
519 if not isinstance(ocsp_data, _binary_type):
520 raise TypeError("OCSP callback must return a bytestring.")
521
522 # If the OCSP data was provided, we will pass it to OpenSSL.
523 # However, we have an early exit here: if no OCSP data was
524 # provided we will just exit out and tell OpenSSL that there
525 # is nothing to do.
526 if not ocsp_data:
527 return 3 # SSL_TLSEXT_ERR_NOACK
528
529 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
530 # private copy of this data, so we need to keep it alive, but
531 # it *does* want to free it itself if it gets replaced. This
532 # somewhat bonkers behaviour means we need to use
533 # OPENSSL_malloc directly, which is a pain in the butt to work
534 # with. It's ok for us to "leak" the memory here because
535 # OpenSSL now owns it and will free it.
536 ocsp_data_length = len(ocsp_data)
537 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
538 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
539
540 _lib.SSL_set_tlsext_status_ocsp_resp(
541 ssl, data_ptr, ocsp_data_length
542 )
543
544 return 0
545 except Exception as e:
546 self._problems.append(e)
547 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
548
549 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
550
551
552class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
553 """
554 Wrap a callback such that it can be used as an OCSP callback for the client
555 side.
556
557 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
558 ways. For servers, that callback is expected to retrieve some OCSP data and
559 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
560 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
561 is expected to check the OCSP data, and returns a negative value on error,
562 0 if the response is not acceptable, or positive if it is. These are
563 mutually exclusive return code behaviours, and they mean that we need two
564 helpers so that we always return an appropriate error code if the user's
565 code throws an exception.
566
567 Given that we have to have two helpers anyway, these helpers are a bit more
568 helpery than most: specifically, they hide a few more of the OpenSSL
569 functions so that the user has an easier time writing these callbacks.
570
571 This helper implements the client side.
572 """
573
574 def __init__(self, callback):
575 _CallbackExceptionHelper.__init__(self)
576
577 @wraps(callback)
578 def wrapper(ssl, cdata):
579 try:
580 conn = Connection._reverse_mapping[ssl]
581
582 # Extract the data if any was provided.
583 if cdata != _ffi.NULL:
584 data = _ffi.from_handle(cdata)
585 else:
586 data = None
587
588 # Get the OCSP data.
589 ocsp_ptr = _ffi.new("unsigned char **")
590 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
591 if ocsp_len < 0:
592 # No OCSP data.
593 ocsp_data = b''
594 else:
595 # Copy the OCSP data, then pass it to the callback.
596 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
597
598 valid = callback(conn, ocsp_data, data)
599
600 # Return 1 on success or 0 on error.
601 return int(bool(valid))
602
603 except Exception as e:
604 self._problems.append(e)
605 # Return negative value if an exception is hit.
606 return -1
607
608 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
609
610
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800611def _asFileDescriptor(obj):
612 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800613 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800614 meth = getattr(obj, "fileno", None)
615 if meth is not None:
616 obj = meth()
617
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800618 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619 fd = obj
620
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800621 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800622 raise TypeError("argument must be an int, or have a fileno() method.")
623 elif fd < 0:
624 raise ValueError(
625 "file descriptor cannot be a negative integer (%i)" % (fd,))
626
627 return fd
628
629
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800630def SSLeay_version(type):
631 """
632 Return a string describing the version of OpenSSL in use.
633
634 :param type: One of the SSLEAY_ constants defined in this module.
635 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500636 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800637
638
Cory Benfieldef404df2016-03-29 15:32:48 +0100639def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400640 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100641 Builds a decorator that ensures that functions that rely on OpenSSL
642 functions that are not present in this build raise NotImplementedError,
643 rather than AttributeError coming out of cryptography.
644
645 :param flag: A cryptography flag that guards the functions, e.g.
646 ``Cryptography_HAS_NEXTPROTONEG``.
647 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400648 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100649 def _requires_decorator(func):
650 if not flag:
651 @wraps(func)
652 def explode(*args, **kwargs):
653 raise NotImplementedError(error)
654 return explode
655 else:
656 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400657
Cory Benfieldef404df2016-03-29 15:32:48 +0100658 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400659
660
Cory Benfieldef404df2016-03-29 15:32:48 +0100661_requires_npn = _make_requires(
662 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
663)
Cory Benfield7907e332015-04-13 17:18:25 -0400664
665
Cory Benfieldef404df2016-03-29 15:32:48 +0100666_requires_alpn = _make_requires(
667 _lib.Cryptography_HAS_ALPN, "ALPN not available"
668)
Cory Benfielde6f35882016-03-29 11:21:04 +0100669
Cory Benfielde6f35882016-03-29 11:21:04 +0100670
Cory Benfieldef404df2016-03-29 15:32:48 +0100671_requires_sni = _make_requires(
672 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
673)
Cory Benfielde6f35882016-03-29 11:21:04 +0100674
675
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800676class Session(object):
677 pass
678
679
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680class Context(object):
681 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100682 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400683 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684 """
685 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800686 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500687 SSLv3_METHOD: "SSLv3_method",
688 SSLv23_METHOD: "SSLv23_method",
689 TLSv1_METHOD: "TLSv1_method",
690 TLSv1_1_METHOD: "TLSv1_1_method",
691 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400692 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500693 _methods = dict(
694 (identifier, getattr(_lib, name))
695 for (identifier, name) in _methods.items()
696 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697
698 def __init__(self, method):
699 """
700 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
701 TLSv1_METHOD.
702 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500703 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704 raise TypeError("method must be an integer")
705
706 try:
707 method_func = self._methods[method]
708 except KeyError:
709 raise ValueError("No such protocol")
710
711 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700712 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500714 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700715 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500716 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800717
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600718 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
719 # will be auto-selected. This function was added in 1.0.2 and made a
720 # noop in 1.1.0+ (where it is set automatically).
721 try:
722 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
723 _openssl_assert(res == 1)
724 except AttributeError:
725 pass
726
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800727 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800728 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800730 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800731 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800732 self._verify_callback = None
733 self._info_callback = None
734 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000736 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100737 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000738 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100739 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400740 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100741 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000742 self._ocsp_helper = None
743 self._ocsp_callback = None
744 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800745
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800747
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748 def load_verify_locations(self, cafile, capath=None):
749 """
750 Let SSL know where we can find trusted certificates for the certificate
751 chain
752
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400753 :param cafile: In which file we can find the certificates (``bytes`` or
754 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800755 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400756 (``bytes`` or ``unicode``).
757
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758 :return: None
759 """
760 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500761 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400762 else:
763 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800764
765 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500766 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400767 else:
768 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769
Alex Gaynor62da94d2015-09-05 14:37:34 -0400770 load_result = _lib.SSL_CTX_load_verify_locations(
771 self._context, cafile, capath
772 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800773 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500774 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800775
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776 def _wrap_callback(self, callback):
777 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800778 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800779 return callback(size, verify, self._passphrase_userdata)
780 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800781 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def set_passwd_cb(self, callback, userdata=None):
784 """
785 Set the passphrase callback
786
Diego Fernandezfe0120f2017-10-11 23:51:52 -0600787 :param callback: The Python callback to use; must return a byte string
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788 :param userdata: (optional) A Python object which will be given as
789 argument to the callback
790 :return: None
791 """
792 if not callable(callback):
793 raise TypeError("callback must be callable")
794
795 self._passphrase_helper = self._wrap_callback(callback)
796 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500797 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798 self._context, self._passphrase_callback)
799 self._passphrase_userdata = userdata
800
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801 def set_default_verify_paths(self):
802 """
803 Use the platform-specific CA certificate locations
804
805 :return: None
806 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500807 # SSL_CTX_set_default_verify_paths will attempt to load certs from
808 # both a cafile and capath that are set at compile time. However,
809 # it will first check environment variables and, if present, load
810 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400812 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500813 # After attempting to set default_verify_paths we need to know whether
814 # to go down the fallback path.
815 # First we'll check to see if any env vars have been set. If so,
816 # we won't try to do anything else because the user has set the path
817 # themselves.
818 dir_env_var = _ffi.string(
819 _lib.X509_get_default_cert_dir_env()
820 ).decode("ascii")
821 file_env_var = _ffi.string(
822 _lib.X509_get_default_cert_file_env()
823 ).decode("ascii")
824 if not self._check_env_vars_set(dir_env_var, file_env_var):
825 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
826 default_file = _ffi.string(_lib.X509_get_default_cert_file())
827 # Now we check to see if the default_dir and default_file are set
828 # to the exact values we use in our manylinux1 builds. If they are
829 # then we know to load the fallbacks
830 if (
831 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
832 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
833 ):
834 # This is manylinux1, let's load our fallback paths
835 self._fallback_default_verify_paths(
836 _CERTIFICATE_FILE_LOCATIONS,
837 _CERTIFICATE_PATH_LOCATIONS
838 )
839
840 def _check_env_vars_set(self, dir_env_var, file_env_var):
841 """
842 Check to see if the default cert dir/file environment vars are present.
843
844 :return: bool
845 """
846 return (
847 os.environ.get(file_env_var) is not None or
848 os.environ.get(dir_env_var) is not None
849 )
850
851 def _fallback_default_verify_paths(self, file_path, dir_path):
852 """
853 Default verify paths are based on the compiled version of OpenSSL.
854 However, when pyca/cryptography is compiled as a manylinux1 wheel
855 that compiled location can potentially be wrong. So, like Go, we
856 will try a predefined set of paths and attempt to load roots
857 from there.
858
859 :return: None
860 """
861 for cafile in file_path:
862 if os.path.isfile(cafile):
863 self.load_verify_locations(cafile)
864 break
865
866 for capath in dir_path:
867 if os.path.isdir(capath):
868 self.load_verify_locations(None, capath)
869 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800870
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800871 def use_certificate_chain_file(self, certfile):
872 """
873 Load a certificate chain from a file
874
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400875 :param certfile: The name of the certificate chain file (``bytes`` or
876 ``unicode``).
877
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800878 :return: None
879 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400880 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800881
Alex Gaynor62da94d2015-09-05 14:37:34 -0400882 result = _lib.SSL_CTX_use_certificate_chain_file(
883 self._context, certfile
884 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800885 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500886 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800887
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800888 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800889 """
890 Load a certificate from a file
891
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400892 :param certfile: The name of the certificate file (``bytes`` or
893 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800894 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400895
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800896 :return: None
897 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400898 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500899 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800900 raise TypeError("filetype must be an integer")
901
Alex Gaynor62da94d2015-09-05 14:37:34 -0400902 use_result = _lib.SSL_CTX_use_certificate_file(
903 self._context, certfile, filetype
904 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800905 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500906 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800907
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908 def use_certificate(self, cert):
909 """
910 Load a certificate from a X509 object
911
912 :param cert: The X509 object
913 :return: None
914 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800915 if not isinstance(cert, X509):
916 raise TypeError("cert must be an X509 instance")
917
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500918 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800919 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500920 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800921
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 def add_extra_chain_cert(self, certobj):
923 """
924 Add certificate to chain
925
926 :param certobj: The X509 certificate object to add to the chain
927 :return: None
928 """
929 if not isinstance(certobj, X509):
930 raise TypeError("certobj must be an X509 instance")
931
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500932 copy = _lib.X509_dup(certobj._x509)
933 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500935 # TODO: This is untested.
936 _lib.X509_free(copy)
937 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800938
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800939 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500940 if self._passphrase_helper is not None:
941 self._passphrase_helper.raise_if_problem(Error)
942
943 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800944
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400945 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946 """
947 Load a private key from a file
948
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400949 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800950 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400951
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952 :return: None
953 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400954 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800955
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400956 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800957 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500958 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959 raise TypeError("filetype must be an integer")
960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 self._context, keyfile, filetype)
963 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800964 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800965
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966 def use_privatekey(self, pkey):
967 """
968 Load a private key from a PKey object
969
970 :param pkey: The PKey object
971 :return: None
972 """
973 if not isinstance(pkey, PKey):
974 raise TypeError("pkey must be a PKey instance")
975
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500976 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800977 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800978 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800980 def check_privatekey(self):
981 """
982 Check that the private key and certificate match up
983
984 :return: None (raises an exception if something's wrong)
985 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500986 if not _lib.SSL_CTX_check_private_key(self._context):
987 _raise_current_error()
988
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 def load_client_ca(self, cafile):
990 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100991 Load the trusted certificates that will be sent to the client. Does
992 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400993 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100995 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996 :return: None
997 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100998 ca_list = _lib.SSL_load_client_CA_file(
999 _text_to_bytes_and_warn("cafile", cafile)
1000 )
1001 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001002 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003
1004 def set_session_id(self, buf):
1005 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001006 Set the session id to *buf* within which a session can be reused for
1007 this Context object. This is needed when doing session resumption,
1008 because there is no way for a stored session to know which Context
1009 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001011 :param bytes buf: The session id.
1012
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001013 :returns: None
1014 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001015 buf = _text_to_bytes_and_warn("buf", buf)
1016 _openssl_assert(
1017 _lib.SSL_CTX_set_session_id_context(
1018 self._context,
1019 buf,
1020 len(buf),
1021 ) == 1
1022 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001023
1024 def set_session_cache_mode(self, mode):
1025 """
1026 Enable/disable session caching and specify the mode used.
1027
1028 :param mode: One or more of the SESS_CACHE_* flags (combine using
1029 bitwise or)
1030 :returns: The previously set caching mode.
1031 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001032 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033 raise TypeError("mode must be an integer")
1034
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001035 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001036
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001037 def get_session_cache_mode(self):
1038 """
1039 :returns: The currently used cache mode.
1040 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001041 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 def set_verify(self, mode, callback):
1044 """
1045 Set the verify mode and verify callback
1046
1047 :param mode: The verify mode, this is either VERIFY_NONE or
1048 VERIFY_PEER combined with possible other flags
1049 :param callback: The Python callback to use
1050 :return: None
1051
1052 See SSL_CTX_set_verify(3SSL) for further details.
1053 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001054 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001055 raise TypeError("mode must be an integer")
1056
1057 if not callable(callback):
1058 raise TypeError("callback must be callable")
1059
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001060 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001061 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001062 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001063
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064 def set_verify_depth(self, depth):
1065 """
1066 Set the verify depth
1067
1068 :param depth: An integer specifying the verify depth
1069 :return: None
1070 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001071 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072 raise TypeError("depth must be an integer")
1073
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076 def get_verify_mode(self):
1077 """
1078 Get the verify mode
1079
1080 :return: The verify mode
1081 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001084 def get_verify_depth(self):
1085 """
1086 Get the verify depth
1087
1088 :return: The verify depth
1089 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001092 def load_tmp_dh(self, dhfile):
1093 """
1094 Load parameters for Ephemeral Diffie-Hellman
1095
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001096 :param dhfile: The file to load EDH parameters from (``bytes`` or
1097 ``unicode``).
1098
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099 :return: None
1100 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001101 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001102
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001103 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001104 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001105 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001106 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001108 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1109 dh = _ffi.gc(dh, _lib.DH_free)
1110 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001112 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001113 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001114 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001115
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001116 :param curve: A curve object to use as returned by either
1117 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
1118 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001119
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001120 :return: None
1121 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001122 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001123
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124 def set_cipher_list(self, cipher_list):
1125 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001126 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001128 See the OpenSSL manual for more information (e.g.
1129 :manpage:`ciphers(1)`).
1130
1131 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001132 :return: None
1133 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001134 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001135
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001136 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001137 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001139 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001140 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001141 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001142
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001143 def set_client_ca_list(self, certificate_authorities):
1144 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001145 Set the list of preferred client certificate signers for this server
1146 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147
Alex Gaynor62da94d2015-09-05 14:37:34 -04001148 This list of certificate authorities will be sent to the client when
1149 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001150
1151 :param certificate_authorities: a sequence of X509Names.
1152 :return: None
1153 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001155 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001156
1157 try:
1158 for ca_name in certificate_authorities:
1159 if not isinstance(ca_name, X509Name):
1160 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001161 "client CAs must be X509Name objects, not %s "
1162 "objects" % (
1163 type(ca_name).__name__,
1164 )
1165 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001167 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001169 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001171 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001172 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001174 raise
1175
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001176 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001177
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001178 def add_client_ca(self, certificate_authority):
1179 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001180 Add the CA certificate to the list of preferred signers for this
1181 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182
1183 The list of certificate authorities will be sent to the client when the
1184 server requests a client certificate.
1185
1186 :param certificate_authority: certificate authority's X509 certificate.
1187 :return: None
1188 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001189 if not isinstance(certificate_authority, X509):
1190 raise TypeError("certificate_authority must be an X509 instance")
1191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001192 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001193 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001194 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001195
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001196 def set_timeout(self, timeout):
1197 """
1198 Set session timeout
1199
1200 :param timeout: The timeout in seconds
1201 :return: The previous session timeout
1202 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001203 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001204 raise TypeError("timeout must be an integer")
1205
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001206 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001207
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001208 def get_timeout(self):
1209 """
1210 Get the session timeout
1211
1212 :return: The session timeout
1213 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001214 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001216 def set_info_callback(self, callback):
1217 """
1218 Set the info callback
1219
1220 :param callback: The Python callback to use
1221 :return: None
1222 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001223 @wraps(callback)
1224 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001225 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001226 self._info_callback = _ffi.callback(
1227 "void (*)(const SSL *, int, int)", wrapper)
1228 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001229
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001230 def get_app_data(self):
1231 """
1232 Get the application data (supplied via set_app_data())
1233
1234 :return: The application data
1235 """
1236 return self._app_data
1237
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001238 def set_app_data(self, data):
1239 """
1240 Set the application data (will be returned from get_app_data())
1241
1242 :param data: Any Python object
1243 :return: None
1244 """
1245 self._app_data = data
1246
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001247 def get_cert_store(self):
1248 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001249 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001250
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001251 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001252 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001253 store = _lib.SSL_CTX_get_cert_store(self._context)
1254 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001255 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001256 return None
1257
1258 pystore = X509Store.__new__(X509Store)
1259 pystore._store = store
1260 return pystore
1261
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001262 def set_options(self, options):
1263 """
1264 Add options. Options set before are not cleared!
1265
1266 :param options: The options to add.
1267 :return: The new option bitmask.
1268 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001269 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001270 raise TypeError("options must be an integer")
1271
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001272 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001273
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001274 def set_mode(self, mode):
1275 """
1276 Add modes via bitmask. Modes set before are not cleared!
1277
1278 :param mode: The mode to add.
1279 :return: The new mode bitmask.
1280 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001281 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282 raise TypeError("mode must be an integer")
1283
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001285
Cory Benfielde6f35882016-03-29 11:21:04 +01001286 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001287 def set_tlsext_servername_callback(self, callback):
1288 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001289 Specify a callback function to be called when clients specify a server
1290 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001291
1292 :param callback: The callback function. It will be invoked with one
1293 argument, the Connection instance.
1294 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001295 @wraps(callback)
1296 def wrapper(ssl, alert, arg):
1297 callback(Connection._reverse_mapping[ssl])
1298 return 0
1299
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001300 self._tlsext_servername_callback = _ffi.callback(
1301 "int (*)(const SSL *, int *, void *)", wrapper)
1302 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001303 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001304
Cory Benfield10b277f2015-04-13 17:12:42 -04001305 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001306 def set_npn_advertise_callback(self, callback):
1307 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001308 Specify a callback function that will be called when offering `Next
1309 Protocol Negotiation
1310 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001311
1312 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001313 argument, the Connection instance. It should return a list of
1314 bytestrings representing the advertised protocols, like
1315 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001316 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001317 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1318 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001319 _lib.SSL_CTX_set_next_protos_advertised_cb(
1320 self._context, self._npn_advertise_callback, _ffi.NULL)
1321
Cory Benfield10b277f2015-04-13 17:12:42 -04001322 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001323 def set_npn_select_callback(self, callback):
1324 """
1325 Specify a callback function that will be called when a server offers
1326 Next Protocol Negotiation options.
1327
1328 :param callback: The callback function. It will be invoked with two
1329 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001330 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1331 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001332 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001333 self._npn_select_helper = _NpnSelectHelper(callback)
1334 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001335 _lib.SSL_CTX_set_next_proto_select_cb(
1336 self._context, self._npn_select_callback, _ffi.NULL)
1337
Cory Benfield7907e332015-04-13 17:18:25 -04001338 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001339 def set_alpn_protos(self, protos):
1340 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001341 Specify the clients ALPN protocol list.
1342
1343 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001344
1345 :param protos: A list of the protocols to be offered to the server.
1346 This list should be a Python list of bytestrings representing the
1347 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1348 """
1349 # Take the list of protocols and join them together, prefixing them
1350 # with their lengths.
1351 protostr = b''.join(
1352 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1353 )
1354
1355 # Build a C string from the list. We don't need to save this off
1356 # because OpenSSL immediately copies the data out.
1357 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001358 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001359
Cory Benfield7907e332015-04-13 17:18:25 -04001360 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001361 def set_alpn_select_callback(self, callback):
1362 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001363 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001364
1365 :param callback: The callback function. It will be invoked with two
1366 arguments: the Connection, and a list of offered protocols as
1367 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001368 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001369 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001370 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001371 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001372 _lib.SSL_CTX_set_alpn_select_cb(
1373 self._context, self._alpn_select_callback, _ffi.NULL)
1374
Cory Benfield496652a2017-01-24 11:42:56 +00001375 def _set_ocsp_callback(self, helper, data):
1376 """
1377 This internal helper does the common work for
1378 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1379 almost all of it.
1380 """
1381 self._ocsp_helper = helper
1382 self._ocsp_callback = helper.callback
1383 if data is None:
1384 self._ocsp_data = _ffi.NULL
1385 else:
1386 self._ocsp_data = _ffi.new_handle(data)
1387
1388 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1389 self._context, self._ocsp_callback
1390 )
1391 _openssl_assert(rc == 1)
1392 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1393 _openssl_assert(rc == 1)
1394
1395 def set_ocsp_server_callback(self, callback, data=None):
1396 """
1397 Set a callback to provide OCSP data to be stapled to the TLS handshake
1398 on the server side.
1399
1400 :param callback: The callback function. It will be invoked with two
1401 arguments: the Connection, and the optional arbitrary data you have
1402 provided. The callback must return a bytestring that contains the
1403 OCSP data to staple to the handshake. If no OCSP data is available
1404 for this connection, return the empty bytestring.
1405 :param data: Some opaque data that will be passed into the callback
1406 function when called. This can be used to avoid needing to do
1407 complex data lookups or to keep track of what context is being
1408 used. This parameter is optional.
1409 """
1410 helper = _OCSPServerCallbackHelper(callback)
1411 self._set_ocsp_callback(helper, data)
1412
1413 def set_ocsp_client_callback(self, callback, data=None):
1414 """
1415 Set a callback to validate OCSP data stapled to the TLS handshake on
1416 the client side.
1417
1418 :param callback: The callback function. It will be invoked with three
1419 arguments: the Connection, a bytestring containing the stapled OCSP
1420 assertion, and the optional arbitrary data you have provided. The
1421 callback must return a boolean that indicates the result of
1422 validating the OCSP data: ``True`` if the OCSP data is valid and
1423 the certificate can be trusted, or ``False`` if either the OCSP
1424 data is invalid or the certificate has been revoked.
1425 :param data: Some opaque data that will be passed into the callback
1426 function when called. This can be used to avoid needing to do
1427 complex data lookups or to keep track of what context is being
1428 used. This parameter is optional.
1429 """
1430 helper = _OCSPClientCallbackHelper(callback)
1431 self._set_ocsp_callback(helper, data)
1432
Alex Chanc6077062016-11-18 13:53:39 +00001433
Alex Gaynor10d30832017-06-29 15:31:39 -07001434ContextType = deprecated(
1435 Context, __name__,
1436 "ContextType has been deprecated, use Context instead", DeprecationWarning
1437)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001438
1439
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001440class Connection(object):
1441 """
1442 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001443 _reverse_mapping = WeakValueDictionary()
1444
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001445 def __init__(self, context, socket=None):
1446 """
1447 Create a new Connection object, using the given OpenSSL.SSL.Context
1448 instance and socket.
1449
1450 :param context: An SSL Context to use for this connection
1451 :param socket: The socket to use for transport layer
1452 """
1453 if not isinstance(context, Context):
1454 raise TypeError("context must be a Context instance")
1455
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001456 ssl = _lib.SSL_new(context._context)
1457 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001458 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001459 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001460
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001461 # References to strings used for Next Protocol Negotiation. OpenSSL's
1462 # header files suggest that these might get copied at some point, but
1463 # doesn't specify when, so we store them here to make sure they don't
1464 # get freed before OpenSSL uses them.
1465 self._npn_advertise_callback_args = None
1466 self._npn_select_callback_args = None
1467
Cory Benfield12eae892014-06-07 15:42:56 +01001468 # References to strings used for Application Layer Protocol
1469 # Negotiation. These strings get copied at some point but it's well
1470 # after the callback returns, so we have to hang them somewhere to
1471 # avoid them getting freed.
1472 self._alpn_select_callback_args = None
1473
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001474 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001475
1476 if socket is None:
1477 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001478 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001479 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001480 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001481
Alex Gaynora829e902016-06-04 18:16:01 -07001482 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1483 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001484
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001485 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001486 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001487 self._into_ssl = None
1488 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001489 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001490 set_result = _lib.SSL_set_fd(
1491 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001492 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001493
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494 def __getattr__(self, name):
1495 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001496 Look up attributes on the wrapped socket object if they are not found
1497 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498 """
kjav0b66fa12015-09-02 11:51:26 +01001499 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001500 raise AttributeError("'%s' object has no attribute '%s'" % (
1501 self.__class__.__name__, name
1502 ))
kjav0b66fa12015-09-02 11:51:26 +01001503 else:
1504 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001505
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001506 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001507 if self._context._verify_helper is not None:
1508 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001509 if self._context._npn_advertise_helper is not None:
1510 self._context._npn_advertise_helper.raise_if_problem()
1511 if self._context._npn_select_helper is not None:
1512 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001513 if self._context._alpn_select_helper is not None:
1514 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001515 if self._context._ocsp_helper is not None:
1516 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001517
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001518 error = _lib.SSL_get_error(ssl, result)
1519 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001520 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001521 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001522 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001523 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001524 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001525 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001526 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001527 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001528 elif error == _lib.SSL_ERROR_SYSCALL:
1529 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001530 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001531 if platform == "win32":
1532 errno = _ffi.getwinerror()[0]
1533 else:
1534 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001535
1536 if errno != 0:
1537 raise SysCallError(errno, errorcode.get(errno))
1538 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001539 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001540 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001541 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001543 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001544 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001545 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001546
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001547 def get_context(self):
1548 """
1549 Get session context
1550 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001552
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001553 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001554 """
1555 Switch this connection to a new session context
1556
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001557 :param context: A :py:class:`Context` instance giving the new session
1558 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001560 if not isinstance(context, Context):
1561 raise TypeError("context must be a Context instance")
1562
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001563 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001564 self._context = context
1565
Cory Benfielde6f35882016-03-29 11:21:04 +01001566 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 def get_servername(self):
1568 """
1569 Retrieve the servername extension value if provided in the client hello
1570 message, or None if there wasn't one.
1571
1572 :return: A byte string giving the server name or :py:data:`None`.
1573 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001574 name = _lib.SSL_get_servername(
1575 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1576 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001577 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001578 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001580 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581
Cory Benfielde6f35882016-03-29 11:21:04 +01001582 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001583 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001584 """
1585 Set the value of the servername extension to send in the client hello.
1586
1587 :param name: A byte string giving the name.
1588 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001589 if not isinstance(name, bytes):
1590 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001591 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 raise TypeError("name must not contain NUL byte")
1593
1594 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001595 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001596
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597 def pending(self):
1598 """
1599 Get the number of bytes that can be safely read from the connection
1600
1601 :return: The number of bytes available in the receive buffer.
1602 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001604
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001606 """
1607 Send data on the connection. NOTE: If you get one of the WantRead,
1608 WantWrite or WantX509Lookup exceptions on this, you have to call the
1609 method again with the SAME buffer.
1610
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001611 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612 :param flags: (optional) Included for compatibility with the socket
1613 API, the value is ignored
1614 :return: The number of bytes written
1615 """
Abraham Martine82326c2015-02-04 10:18:10 +00001616 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001617 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001618
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001619 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001620 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001621 if isinstance(buf, _buffer):
1622 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001623 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001624 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001625 if len(buf) > 2147483647:
1626 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001627
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001629 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001630 return result
1631 write = send
1632
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001633 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001634 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635 Send "all" data on the connection. This calls send() repeatedly until
1636 all data is sent. If an error occurs, it's impossible to tell how much
1637 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001638
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001639 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001640 :param flags: (optional) Included for compatibility with the socket
1641 API, the value is ignored
1642 :return: The number of bytes written
1643 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001644 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001645
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001646 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001647 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001648 if isinstance(buf, _buffer):
1649 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001650 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001651 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001652
1653 left_to_send = len(buf)
1654 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001655 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656
1657 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001658 # SSL_write's num arg is an int,
1659 # so we cannot send more than 2**31-1 bytes at once.
1660 result = _lib.SSL_write(
1661 self._ssl,
1662 data + total_sent,
1663 min(left_to_send, 2147483647)
1664 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001665 self._raise_ssl_error(self._ssl, result)
1666 total_sent += result
1667 left_to_send -= result
1668
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001669 def recv(self, bufsiz, flags=None):
1670 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001671 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001672
1673 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001674 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1675 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001676 :return: The string read from the Connection
1677 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001678 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001679 if flags is not None and flags & socket.MSG_PEEK:
1680 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1681 else:
1682 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001683 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001684 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001685 read = recv
1686
Cory Benfield62d10332014-06-15 10:03:41 +01001687 def recv_into(self, buffer, nbytes=None, flags=None):
1688 """
1689 Receive data on the connection and store the data into a buffer rather
1690 than creating a new string.
1691
1692 :param buffer: The buffer to copy into.
1693 :param nbytes: (optional) The maximum number of bytes to read into the
1694 buffer. If not present, defaults to the size of the buffer. If
1695 larger than the size of the buffer, is reduced to the size of the
1696 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001697 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1698 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001699 :return: The number of bytes read into the buffer.
1700 """
1701 if nbytes is None:
1702 nbytes = len(buffer)
1703 else:
1704 nbytes = min(nbytes, len(buffer))
1705
1706 # We need to create a temporary buffer. This is annoying, it would be
1707 # better if we could pass memoryviews straight into the SSL_read call,
1708 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001709 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001710 if flags is not None and flags & socket.MSG_PEEK:
1711 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1712 else:
1713 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001714 self._raise_ssl_error(self._ssl, result)
1715
1716 # This strange line is all to avoid a memory copy. The buffer protocol
1717 # should allow us to assign a CFFI buffer to the LHS of this line, but
1718 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1719 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1720 # memoryview type.
1721 try:
1722 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1723 except NameError:
1724 buffer[:result] = _ffi.buffer(buf, result)
1725
1726 return result
1727
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001728 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001729 if _lib.BIO_should_retry(bio):
1730 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001731 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001732 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001733 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001734 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001735 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001736 # TODO: This is untested. I think io_special means the socket
1737 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001738 raise ValueError("BIO_should_io_special")
1739 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001740 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001741 raise ValueError("unknown bio failure")
1742 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001743 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001744 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001746 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001747 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001748 When using non-socket connections this function reads the "dirty" data
1749 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001750
1751 :param bufsiz: The maximum number of bytes to read
1752 :return: The string read.
1753 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001754 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001756
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001757 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001758 raise TypeError("bufsiz must be an integer")
1759
Cory Benfielde62840e2016-11-28 12:17:08 +00001760 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001761 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001762 if result <= 0:
1763 self._handle_bio_errors(self._from_ssl, result)
1764
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001765 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001766
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001767 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001769 When using non-socket connections this function sends "dirty" data that
1770 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001771
1772 :param buf: The string to put into the memory BIO.
1773 :return: The number of bytes written
1774 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001775 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001776
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001777 if self._into_ssl is None:
1778 raise TypeError("Connection sock was not None")
1779
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001780 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001781 if result <= 0:
1782 self._handle_bio_errors(self._into_ssl, result)
1783 return result
1784
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001785 def renegotiate(self):
1786 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001787 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001788
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001789 :return: True if the renegotiation can be started, False otherwise
1790 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001791 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001792 if not self.renegotiate_pending():
1793 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1794 return True
1795 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001796
1797 def do_handshake(self):
1798 """
1799 Perform an SSL handshake (usually called after renegotiate() or one of
1800 set_*_state()). This can raise the same exceptions as send and recv.
1801
1802 :return: None.
1803 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001804 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001805 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001806
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001807 def renegotiate_pending(self):
1808 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001809 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001810 a renegotiation is finished.
1811
1812 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001813 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001814 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001815 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816
1817 def total_renegotiations(self):
1818 """
1819 Find out the total number of renegotiations.
1820
1821 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001822 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001824 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001825
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001826 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001827 """
1828 Connect to remote host and set up client-side SSL
1829
1830 :param addr: A remote address
1831 :return: What the socket's connect method returns
1832 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001833 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001834 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001835
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001836 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001837 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001838 Connect to remote host and set up client-side SSL. Note that if the
1839 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001840
1841 :param addr: A remove address
1842 :return: What the socket's connect_ex method returns
1843 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001844 connect_ex = self._socket.connect_ex
1845 self.set_connect_state()
1846 return connect_ex(addr)
1847
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848 def accept(self):
1849 """
1850 Accept incoming connection and set up SSL on it
1851
1852 :return: A (conn,addr) pair where conn is a Connection and addr is an
1853 address
1854 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001855 client, addr = self._socket.accept()
1856 conn = Connection(self._context, client)
1857 conn.set_accept_state()
1858 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001859
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860 def bio_shutdown(self):
1861 """
1862 When using non-socket connections this function signals end of
1863 data on the input for this connection.
1864
1865 :return: None
1866 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001867 if self._from_ssl is None:
1868 raise TypeError("Connection sock was not None")
1869
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001870 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001871
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001872 def shutdown(self):
1873 """
1874 Send closure alert
1875
1876 :return: True if the shutdown completed successfully (i.e. both sides
1877 have sent closure alerts), false otherwise (i.e. you have to
1878 wait for a ZeroReturnError on a recv() method call
1879 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001880 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001882 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001883 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001884 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001885 else:
1886 return False
1887
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001888 def get_cipher_list(self):
1889 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001890 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001891
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001892 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001893 """
1894 ciphers = []
1895 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001896 result = _lib.SSL_get_cipher_list(self._ssl, i)
1897 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001899 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001900 return ciphers
1901
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001902 def get_client_ca_list(self):
1903 """
1904 Get CAs whose certificates are suggested for client authentication.
1905
Alex Gaynor62da94d2015-09-05 14:37:34 -04001906 :return: If this is a server connection, a list of X509Names
1907 representing the acceptable CAs as set by
1908 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1909 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1910 connection, the list of such X509Names sent by the server, or an
1911 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001913 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1914 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001915 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916 return []
1917
1918 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001919 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1920 name = _lib.sk_X509_NAME_value(ca_names, i)
1921 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001922 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001923
1924 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001925 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001926 result.append(pyname)
1927 return result
1928
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001929 def makefile(self):
1930 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001931 The makefile() method is not implemented, since there is no dup
1932 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001933
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001934 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001935 """
Alex Gaynor83284952015-09-05 10:43:30 -04001936 raise NotImplementedError(
1937 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001938
1939 def get_app_data(self):
1940 """
1941 Get application data
1942
1943 :return: The application data
1944 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001945 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001946
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001947 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001948 """
1949 Set application data
1950
1951 :param data - The application data
1952 :return: None
1953 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001954 self._app_data = data
1955
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001956 def get_shutdown(self):
1957 """
1958 Get shutdown state
1959
Alex Gaynor62da94d2015-09-05 14:37:34 -04001960 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1961 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001963 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001965 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966 """
1967 Set shutdown state
1968
1969 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1970 :return: None
1971 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001972 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001973 raise TypeError("state must be an integer")
1974
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001975 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001976
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001977 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001978 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001979 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001980
1981 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001982 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983 """
kjavc704a2e2015-09-07 12:12:27 +01001984 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001985
1986 def server_random(self):
1987 """
1988 Get a copy of the server hello nonce.
1989
1990 :return: A string representing the state
1991 """
Alex Gaynor93603062016-06-01 20:13:09 -07001992 session = _lib.SSL_get_session(self._ssl)
1993 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001994 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001995 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1996 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001997 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001998 _lib.SSL_get_server_random(self._ssl, outp, length)
1999 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 def client_random(self):
2002 """
2003 Get a copy of the client hello nonce.
2004
2005 :return: A string representing the state
2006 """
Alex Gaynor93603062016-06-01 20:13:09 -07002007 session = _lib.SSL_get_session(self._ssl)
2008 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002010
2011 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2012 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002013 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002014 _lib.SSL_get_client_random(self._ssl, outp, length)
2015 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002016
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002017 def master_key(self):
2018 """
2019 Get a copy of the master key.
2020
2021 :return: A string representing the state
2022 """
Alex Gaynor93603062016-06-01 20:13:09 -07002023 session = _lib.SSL_get_session(self._ssl)
2024 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002025 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002026
2027 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2028 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002029 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002030 _lib.SSL_SESSION_get_master_key(session, outp, length)
2031 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002032
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002033 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002034 """
2035 See shutdown(2)
2036
2037 :return: What the socket's shutdown() method returns
2038 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002039 return self._socket.shutdown(*args, **kwargs)
2040
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002041 def get_peer_certificate(self):
2042 """
2043 Retrieve the other side's certificate (if any)
2044
2045 :return: The peer's certificate
2046 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002047 cert = _lib.SSL_get_peer_certificate(self._ssl)
2048 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002049 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002050 return None
2051
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002052 def get_peer_cert_chain(self):
2053 """
2054 Retrieve the other side's certificate (if any)
2055
2056 :return: A list of X509 instances giving the peer's certificate chain,
2057 or None if it does not have one.
2058 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002059 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2060 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002061 return None
2062
2063 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002064 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002065 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002066 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002067 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002068 result.append(pycert)
2069 return result
2070
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002071 def want_read(self):
2072 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002073 Checks if more data has to be read from the transport layer to complete
2074 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002075
2076 :return: True iff more data has to be read
2077 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002078 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002079
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002080 def want_write(self):
2081 """
2082 Checks if there is data to write to the transport layer to complete an
2083 operation.
2084
2085 :return: True iff there is data to write
2086 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002087 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002088
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002089 def set_accept_state(self):
2090 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002091 Set the connection to work in server mode. The handshake will be
2092 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002093
2094 :return: None
2095 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002096 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002097
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002098 def set_connect_state(self):
2099 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002100 Set the connection to work in client mode. The handshake will be
2101 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002102
2103 :return: None
2104 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002105 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002106
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002107 def get_session(self):
2108 """
2109 Returns the Session currently used.
2110
Alex Gaynor62da94d2015-09-05 14:37:34 -04002111 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
2112 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002113 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002114 session = _lib.SSL_get1_session(self._ssl)
2115 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002116 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002117
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002118 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002119 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002120 return pysession
2121
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002122 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002123 """
2124 Set the session to be used when the TLS/SSL connection is established.
2125
2126 :param session: A Session instance representing the session to use.
2127 :returns: None
2128 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002129 if not isinstance(session, Session):
2130 raise TypeError("session must be a Session instance")
2131
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002132 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002133 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002134 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002135
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002136 def _get_finished_message(self, function):
2137 """
2138 Helper to implement :py:meth:`get_finished` and
2139 :py:meth:`get_peer_finished`.
2140
2141 :param function: Either :py:data:`SSL_get_finished`: or
2142 :py:data:`SSL_get_peer_finished`.
2143
2144 :return: :py:data:`None` if the desired message has not yet been
2145 received, otherwise the contents of the message.
2146 :rtype: :py:class:`bytes` or :py:class:`NoneType`
2147 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002148 # The OpenSSL documentation says nothing about what might happen if the
2149 # count argument given is zero. Specifically, it doesn't say whether
2150 # the output buffer may be NULL in that case or not. Inspection of the
2151 # implementation reveals that it calls memcpy() unconditionally.
2152 # Section 7.1.4, paragraph 1 of the C standard suggests that
2153 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2154 # alone desirable) behavior (though it probably does on just about
2155 # every implementation...)
2156 #
2157 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2158 # one might expect) for the initial call so as to be safe against this
2159 # potentially undefined behavior.
2160 empty = _ffi.new("char[]", 0)
2161 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002162 if size == 0:
2163 # No Finished message so far.
2164 return None
2165
Cory Benfielde62840e2016-11-28 12:17:08 +00002166 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002167 function(self._ssl, buf, size)
2168 return _ffi.buffer(buf, size)[:]
2169
Fedor Brunner5747b932014-03-05 14:22:34 +01002170 def get_finished(self):
2171 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002172 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002173
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002174 :return: The contents of the message or :py:obj:`None` if the TLS
2175 handshake has not yet completed.
2176 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002177 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002178 return self._get_finished_message(_lib.SSL_get_finished)
2179
Fedor Brunner5747b932014-03-05 14:22:34 +01002180 def get_peer_finished(self):
2181 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002182 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002183
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002184 :return: The contents of the message or :py:obj:`None` if the TLS
2185 handshake has not yet completed.
2186 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002187 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002188 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002189
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002190 def get_cipher_name(self):
2191 """
2192 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002193
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002194 :returns: The name of the currently used cipher or :py:obj:`None`
2195 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002196 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002197 """
2198 cipher = _lib.SSL_get_current_cipher(self._ssl)
2199 if cipher == _ffi.NULL:
2200 return None
2201 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002202 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2203 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002204
2205 def get_cipher_bits(self):
2206 """
2207 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002208
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002209 :returns: The number of secret bits of the currently used cipher
2210 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002211 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002212 """
2213 cipher = _lib.SSL_get_current_cipher(self._ssl)
2214 if cipher == _ffi.NULL:
2215 return None
2216 else:
2217 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2218
2219 def get_cipher_version(self):
2220 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002221 Obtain the protocol version of the currently used cipher.
2222
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002223 :returns: The protocol name of the currently used cipher
2224 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002225 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002226 """
2227 cipher = _lib.SSL_get_current_cipher(self._ssl)
2228 if cipher == _ffi.NULL:
2229 return None
2230 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002231 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002232 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002233
Jim Shaverabff1882015-05-27 09:15:55 -04002234 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002235 """
2236 Obtain the protocol version of the current connection.
2237
2238 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002239 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002240 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002241 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002242 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002243 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002244 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002245
Jim Shaver208438c2015-05-28 09:52:38 -04002246 def get_protocol_version(self):
2247 """
2248 Obtain the protocol version of the current connection.
2249
2250 :returns: The TLS version of the current connection, for example
2251 the value for TLS 1 would be 0x769.
2252 :rtype: :py:class:`int`
2253 """
2254 version = _lib.SSL_version(self._ssl)
2255 return version
2256
Cory Benfield10b277f2015-04-13 17:12:42 -04002257 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002258 def get_next_proto_negotiated(self):
2259 """
2260 Get the protocol that was negotiated by NPN.
2261 """
2262 data = _ffi.new("unsigned char **")
2263 data_len = _ffi.new("unsigned int *")
2264
2265 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2266
Cory Benfieldcd010f62014-05-15 19:00:27 +01002267 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002268
Cory Benfield7907e332015-04-13 17:18:25 -04002269 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002270 def set_alpn_protos(self, protos):
2271 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002272 Specify the client's ALPN protocol list.
2273
2274 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002275
2276 :param protos: A list of the protocols to be offered to the server.
2277 This list should be a Python list of bytestrings representing the
2278 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2279 """
2280 # Take the list of protocols and join them together, prefixing them
2281 # with their lengths.
2282 protostr = b''.join(
2283 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2284 )
2285
2286 # Build a C string from the list. We don't need to save this off
2287 # because OpenSSL immediately copies the data out.
2288 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002289 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002290
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002291 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002292 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002293 """
2294 Get the protocol that was negotiated by ALPN.
2295 """
Cory Benfield12eae892014-06-07 15:42:56 +01002296 data = _ffi.new("unsigned char **")
2297 data_len = _ffi.new("unsigned int *")
2298
2299 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2300
Cory Benfielde8e9c382015-04-11 17:33:48 -04002301 if not data_len:
2302 return b''
2303
Cory Benfield12eae892014-06-07 15:42:56 +01002304 return _ffi.buffer(data[0], data_len[0])[:]
2305
Cory Benfield496652a2017-01-24 11:42:56 +00002306 def request_ocsp(self):
2307 """
2308 Called to request that the server sends stapled OCSP data, if
2309 available. If this is not called on the client side then the server
2310 will not send OCSP data. Should be used in conjunction with
2311 :meth:`Context.set_ocsp_client_callback`.
2312 """
2313 rc = _lib.SSL_set_tlsext_status_type(
2314 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2315 )
2316 _openssl_assert(rc == 1)
2317
Cory Benfield12eae892014-06-07 15:42:56 +01002318
Alex Gaynor10d30832017-06-29 15:31:39 -07002319ConnectionType = deprecated(
2320 Connection, __name__,
2321 "ConnectionType has been deprecated, use Connection instead",
2322 DeprecationWarning
2323)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002324
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002325# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2326# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002327_lib.SSL_library_init()