blob: 552115115aad578019c2342f4c2b360dc74a14f2 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Alex Gaynorbe2bd542019-02-21 21:41:22 -05003import warnings
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02004from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05005from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01006from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08007from weakref import WeakValueDictionary
8from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08009
Alex Gaynor336d8022017-06-29 21:46:42 -070010from six import (
11 binary_type as _binary_type, integer_types as integer_types, int2byte,
12 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050013
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010015 UNSPECIFIED as _UNSPECIFIED,
16 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 ffi as _ffi,
18 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010019 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040021 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010022 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000023 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040024)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080025
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080026from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050027 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080028
Nicolas Karolak736c6212017-11-26 14:40:28 +010029__all__ = [
30 'OPENSSL_VERSION_NUMBER',
31 'SSLEAY_VERSION',
32 'SSLEAY_CFLAGS',
33 'SSLEAY_PLATFORM',
34 'SSLEAY_DIR',
35 'SSLEAY_BUILT_ON',
36 'SENT_SHUTDOWN',
37 'RECEIVED_SHUTDOWN',
38 'SSLv2_METHOD',
39 'SSLv3_METHOD',
40 'SSLv23_METHOD',
41 'TLSv1_METHOD',
42 'TLSv1_1_METHOD',
43 'TLSv1_2_METHOD',
44 'OP_NO_SSLv2',
45 'OP_NO_SSLv3',
46 'OP_NO_TLSv1',
47 'OP_NO_TLSv1_1',
48 'OP_NO_TLSv1_2',
Nathaniel J. Smitha1813732019-08-01 21:32:13 -070049 'OP_NO_TLSv1_3',
Nicolas Karolak736c6212017-11-26 14:40:28 +010050 'MODE_RELEASE_BUFFERS',
51 'OP_SINGLE_DH_USE',
52 'OP_SINGLE_ECDH_USE',
53 'OP_EPHEMERAL_RSA',
54 'OP_MICROSOFT_SESS_ID_BUG',
55 'OP_NETSCAPE_CHALLENGE_BUG',
56 'OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG',
57 'OP_SSLREF2_REUSE_CERT_TYPE_BUG',
58 'OP_MICROSOFT_BIG_SSLV3_BUFFER',
59 'OP_MSIE_SSLV2_RSA_PADDING',
60 'OP_SSLEAY_080_CLIENT_DH_BUG',
61 'OP_TLS_D5_BUG',
62 'OP_TLS_BLOCK_PADDING_BUG',
63 'OP_DONT_INSERT_EMPTY_FRAGMENTS',
64 'OP_CIPHER_SERVER_PREFERENCE',
65 'OP_TLS_ROLLBACK_BUG',
66 'OP_PKCS1_CHECK_1',
67 'OP_PKCS1_CHECK_2',
68 'OP_NETSCAPE_CA_DN_BUG',
69 'OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG',
70 'OP_NO_COMPRESSION',
71 'OP_NO_QUERY_MTU',
72 'OP_COOKIE_EXCHANGE',
73 'OP_NO_TICKET',
74 'OP_ALL',
75 'VERIFY_PEER',
76 'VERIFY_FAIL_IF_NO_PEER_CERT',
77 'VERIFY_CLIENT_ONCE',
78 'VERIFY_NONE',
79 'SESS_CACHE_OFF',
80 'SESS_CACHE_CLIENT',
81 'SESS_CACHE_SERVER',
82 'SESS_CACHE_BOTH',
83 'SESS_CACHE_NO_AUTO_CLEAR',
84 'SESS_CACHE_NO_INTERNAL_LOOKUP',
85 'SESS_CACHE_NO_INTERNAL_STORE',
86 'SESS_CACHE_NO_INTERNAL',
87 'SSL_ST_CONNECT',
88 'SSL_ST_ACCEPT',
89 'SSL_ST_MASK',
Nicolas Karolak736c6212017-11-26 14:40:28 +010090 'SSL_CB_LOOP',
91 'SSL_CB_EXIT',
92 'SSL_CB_READ',
93 'SSL_CB_WRITE',
94 'SSL_CB_ALERT',
95 'SSL_CB_READ_ALERT',
96 'SSL_CB_WRITE_ALERT',
97 'SSL_CB_ACCEPT_LOOP',
98 'SSL_CB_ACCEPT_EXIT',
99 'SSL_CB_CONNECT_LOOP',
100 'SSL_CB_CONNECT_EXIT',
101 'SSL_CB_HANDSHAKE_START',
102 'SSL_CB_HANDSHAKE_DONE',
103 'Error',
104 'WantReadError',
105 'WantWriteError',
106 'WantX509LookupError',
107 'ZeroReturnError',
108 'SysCallError',
109 'SSLeay_version',
110 'Session',
111 'Context',
112 'Connection'
113]
114
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500115try:
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +0200116 _buffer = buffer
117except NameError:
118 class _buffer(object):
119 pass
120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
122SSLEAY_VERSION = _lib.SSLEAY_VERSION
123SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
124SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
125SSLEAY_DIR = _lib.SSLEAY_DIR
126SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800127
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
129RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800130
131SSLv2_METHOD = 1
132SSLv3_METHOD = 2
133SSLv23_METHOD = 3
134TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -0500135TLSv1_1_METHOD = 5
136TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500138OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
139OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
140OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -0700141OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
142OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Nathaniel J. Smitha1813732019-08-01 21:32:13 -0700143try:
144 OP_NO_TLSv1_3 = _lib.SSL_OP_NO_TLSv1_3
145except AttributeError:
146 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800147
Alex Gaynorbf012872016-06-04 13:18:39 -0700148MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800149
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500150OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +0900151OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
153OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
154OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400155OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
156 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
157)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
159OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400160OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500161OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
162OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
163OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
164OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
165OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
166OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
167OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
168OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
169OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -0400170OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
171 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
172)
Alex Gaynorbf012872016-06-04 13:18:39 -0700173OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800174
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500175OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
176OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400177OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800178
Alex Gaynorc4889812015-09-04 08:43:17 -0400179OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500181VERIFY_PEER = _lib.SSL_VERIFY_PEER
182VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
183VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
184VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800185
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500186SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
187SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
188SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
189SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
190SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
191SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
192SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
193SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500195SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
196SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
197SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400198if _lib.Cryptography_HAS_SSL_ST:
199 SSL_ST_INIT = _lib.SSL_ST_INIT
200 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
201 SSL_ST_OK = _lib.SSL_ST_OK
202 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Ondřej Nový993c4e42018-03-01 14:09:37 +0100203 __all__.extend([
204 'SSL_ST_INIT',
205 'SSL_ST_BEFORE',
206 'SSL_ST_OK',
207 'SSL_ST_RENEGOTIATE',
208 ])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800209
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500210SSL_CB_LOOP = _lib.SSL_CB_LOOP
211SSL_CB_EXIT = _lib.SSL_CB_EXIT
212SSL_CB_READ = _lib.SSL_CB_READ
213SSL_CB_WRITE = _lib.SSL_CB_WRITE
214SSL_CB_ALERT = _lib.SSL_CB_ALERT
215SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
216SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
217SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
218SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
219SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
220SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
221SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
222SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800223
Paul Kehrer55fb3412017-06-29 18:44:08 -0500224# Taken from https://golang.org/src/crypto/x509/root_linux.go
225_CERTIFICATE_FILE_LOCATIONS = [
226 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
227 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
228 "/etc/ssl/ca-bundle.pem", # OpenSUSE
229 "/etc/pki/tls/cacert.pem", # OpenELEC
230 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
231]
232
233_CERTIFICATE_PATH_LOCATIONS = [
234 "/etc/ssl/certs", # SLES10/SLES11
235]
236
Paul Kehrera92a1a72017-07-19 15:53:23 +0200237# These values are compared to output from cffi's ffi.string so they must be
238# byte strings.
239_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
240_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500241
Alex Gaynor83284952015-09-05 10:43:30 -0400242
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500243class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500244 """
245 An error occurred in an `OpenSSL.SSL` API.
246 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500247
248
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500249_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100250_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500251
252
253class WantReadError(Error):
254 pass
255
256
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500257class WantWriteError(Error):
258 pass
259
260
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500261class WantX509LookupError(Error):
262 pass
263
264
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500265class ZeroReturnError(Error):
266 pass
267
268
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500269class SysCallError(Error):
270 pass
271
272
Cory Benfield0ea76e72015-03-22 09:05:28 +0000273class _CallbackExceptionHelper(object):
274 """
275 A base class for wrapper classes that allow for intelligent exception
276 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500277
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400278 :ivar list _problems: Any exceptions that occurred while executing in a
279 context where they could not be raised in the normal way. Typically
280 this is because OpenSSL has called into some Python code and requires a
281 return value. The exceptions are saved to be raised later when it is
282 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000283 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400284
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400285 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800286 self._problems = []
287
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400289 """
290 Raise an exception from the OpenSSL error queue or that was previously
291 captured whe running a callback.
292 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000293 if self._problems:
294 try:
295 _raise_current_error()
296 except Error:
297 pass
298 raise self._problems.pop(0)
299
300
301class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400302 """
303 Wrap a callback such that it can be used as a certificate verification
304 callback.
305 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400306
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800307 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400308 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800309
310 @wraps(callback)
311 def wrapper(ok, store_ctx):
Paul Kehrere7381862017-11-30 20:55:25 +0800312 x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
313 _lib.X509_up_ref(x509)
314 cert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500315 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
316 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800317
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400318 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
319 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
320 connection = Connection._reverse_mapping[ssl]
321
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800322 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400323 result = callback(
324 connection, cert, error_number, error_depth, ok
325 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800326 except Exception as e:
327 self._problems.append(e)
328 return 0
329 else:
330 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500331 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800332 return 1
333 else:
334 return 0
335
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500336 self.callback = _ffi.callback(
337 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800338
339
Cory Benfield0ea76e72015-03-22 09:05:28 +0000340class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400341 """
342 Wrap a callback such that it can be used as an NPN advertisement callback.
343 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400344
Cory Benfield0ea76e72015-03-22 09:05:28 +0000345 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400346 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800347
Cory Benfield0ea76e72015-03-22 09:05:28 +0000348 @wraps(callback)
349 def wrapper(ssl, out, outlen, arg):
350 try:
351 conn = Connection._reverse_mapping[ssl]
352 protos = callback(conn)
353
354 # Join the protocols into a Python bytestring, length-prefixing
355 # each element.
356 protostr = b''.join(
357 chain.from_iterable((int2byte(len(p)), p) for p in protos)
358 )
359
360 # Save our callback arguments on the connection object. This is
361 # done to make sure that they don't get freed before OpenSSL
362 # uses them. Then, return them appropriately in the output
363 # parameters.
364 conn._npn_advertise_callback_args = [
365 _ffi.new("unsigned int *", len(protostr)),
366 _ffi.new("unsigned char[]", protostr),
367 ]
368 outlen[0] = conn._npn_advertise_callback_args[0][0]
369 out[0] = conn._npn_advertise_callback_args[1]
370 return 0
371 except Exception as e:
372 self._problems.append(e)
373 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
374
375 self.callback = _ffi.callback(
376 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
377 wrapper
378 )
379
380
381class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400382 """
383 Wrap a callback such that it can be used as an NPN selection callback.
384 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400385
Cory Benfield0ea76e72015-03-22 09:05:28 +0000386 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400387 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000388
389 @wraps(callback)
390 def wrapper(ssl, out, outlen, in_, inlen, arg):
391 try:
392 conn = Connection._reverse_mapping[ssl]
393
394 # The string passed to us is actually made up of multiple
395 # length-prefixed bytestrings. We need to split that into a
396 # list.
397 instr = _ffi.buffer(in_, inlen)[:]
398 protolist = []
399 while instr:
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500400 length = indexbytes(instr, 0)
401 proto = instr[1:length + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000402 protolist.append(proto)
Alex Gaynorc3697ad2017-11-20 08:19:32 -0500403 instr = instr[length + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000404
405 # Call the callback
406 outstr = callback(conn, protolist)
407
408 # Save our callback arguments on the connection object. This is
409 # done to make sure that they don't get freed before OpenSSL
410 # uses them. Then, return them appropriately in the output
411 # parameters.
412 conn._npn_select_callback_args = [
413 _ffi.new("unsigned char *", len(outstr)),
414 _ffi.new("unsigned char[]", outstr),
415 ]
416 outlen[0] = conn._npn_select_callback_args[0][0]
417 out[0] = conn._npn_select_callback_args[1]
418 return 0
419 except Exception as e:
420 self._problems.append(e)
421 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
422
423 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400424 ("int (*)(SSL *, unsigned char **, unsigned char *, "
425 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000426 wrapper
427 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800428
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800429
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400430class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400431 """
432 Wrap a callback such that it can be used as an ALPN selection callback.
433 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400434
Cory Benfieldf1177e72015-04-12 09:11:49 -0400435 def __init__(self, callback):
436 _CallbackExceptionHelper.__init__(self)
437
438 @wraps(callback)
439 def wrapper(ssl, out, outlen, in_, inlen, arg):
440 try:
441 conn = Connection._reverse_mapping[ssl]
442
443 # The string passed to us is made up of multiple
444 # length-prefixed bytestrings. We need to split that into a
445 # list.
446 instr = _ffi.buffer(in_, inlen)[:]
447 protolist = []
448 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400449 encoded_len = indexbytes(instr, 0)
450 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400451 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400452 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400453
454 # Call the callback
455 outstr = callback(conn, protolist)
456
457 if not isinstance(outstr, _binary_type):
458 raise TypeError("ALPN callback must return a bytestring.")
459
460 # Save our callback arguments on the connection object to make
461 # sure that they don't get freed before OpenSSL can use them.
462 # Then, return them in the appropriate output parameters.
463 conn._alpn_select_callback_args = [
464 _ffi.new("unsigned char *", len(outstr)),
465 _ffi.new("unsigned char[]", outstr),
466 ]
467 outlen[0] = conn._alpn_select_callback_args[0][0]
468 out[0] = conn._alpn_select_callback_args[1]
469 return 0
470 except Exception as e:
471 self._problems.append(e)
472 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
473
474 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400475 ("int (*)(SSL *, unsigned char **, unsigned char *, "
476 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400477 wrapper
478 )
479
480
Cory Benfield496652a2017-01-24 11:42:56 +0000481class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
482 """
483 Wrap a callback such that it can be used as an OCSP callback for the server
484 side.
485
486 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
487 ways. For servers, that callback is expected to retrieve some OCSP data and
488 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
489 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
490 is expected to check the OCSP data, and returns a negative value on error,
491 0 if the response is not acceptable, or positive if it is. These are
492 mutually exclusive return code behaviours, and they mean that we need two
493 helpers so that we always return an appropriate error code if the user's
494 code throws an exception.
495
496 Given that we have to have two helpers anyway, these helpers are a bit more
497 helpery than most: specifically, they hide a few more of the OpenSSL
498 functions so that the user has an easier time writing these callbacks.
499
500 This helper implements the server side.
501 """
502
503 def __init__(self, callback):
504 _CallbackExceptionHelper.__init__(self)
505
506 @wraps(callback)
507 def wrapper(ssl, cdata):
508 try:
509 conn = Connection._reverse_mapping[ssl]
510
511 # Extract the data if any was provided.
512 if cdata != _ffi.NULL:
513 data = _ffi.from_handle(cdata)
514 else:
515 data = None
516
517 # Call the callback.
518 ocsp_data = callback(conn, data)
519
520 if not isinstance(ocsp_data, _binary_type):
521 raise TypeError("OCSP callback must return a bytestring.")
522
523 # If the OCSP data was provided, we will pass it to OpenSSL.
524 # However, we have an early exit here: if no OCSP data was
525 # provided we will just exit out and tell OpenSSL that there
526 # is nothing to do.
527 if not ocsp_data:
528 return 3 # SSL_TLSEXT_ERR_NOACK
529
David Benjamin7ac5f272018-05-21 21:24:04 -0400530 # OpenSSL takes ownership of this data and expects it to have
531 # been allocated by OPENSSL_malloc.
Cory Benfield496652a2017-01-24 11:42:56 +0000532 ocsp_data_length = len(ocsp_data)
533 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
534 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
535
536 _lib.SSL_set_tlsext_status_ocsp_resp(
537 ssl, data_ptr, ocsp_data_length
538 )
539
540 return 0
541 except Exception as e:
542 self._problems.append(e)
543 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
544
545 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
546
547
548class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
549 """
550 Wrap a callback such that it can be used as an OCSP callback for the client
551 side.
552
553 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
554 ways. For servers, that callback is expected to retrieve some OCSP data and
555 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
556 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
557 is expected to check the OCSP data, and returns a negative value on error,
558 0 if the response is not acceptable, or positive if it is. These are
559 mutually exclusive return code behaviours, and they mean that we need two
560 helpers so that we always return an appropriate error code if the user's
561 code throws an exception.
562
563 Given that we have to have two helpers anyway, these helpers are a bit more
564 helpery than most: specifically, they hide a few more of the OpenSSL
565 functions so that the user has an easier time writing these callbacks.
566
567 This helper implements the client side.
568 """
569
570 def __init__(self, callback):
571 _CallbackExceptionHelper.__init__(self)
572
573 @wraps(callback)
574 def wrapper(ssl, cdata):
575 try:
576 conn = Connection._reverse_mapping[ssl]
577
578 # Extract the data if any was provided.
579 if cdata != _ffi.NULL:
580 data = _ffi.from_handle(cdata)
581 else:
582 data = None
583
584 # Get the OCSP data.
585 ocsp_ptr = _ffi.new("unsigned char **")
586 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
587 if ocsp_len < 0:
588 # No OCSP data.
589 ocsp_data = b''
590 else:
591 # Copy the OCSP data, then pass it to the callback.
592 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
593
594 valid = callback(conn, ocsp_data, data)
595
596 # Return 1 on success or 0 on error.
597 return int(bool(valid))
598
599 except Exception as e:
600 self._problems.append(e)
601 # Return negative value if an exception is hit.
602 return -1
603
604 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
605
606
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800607def _asFileDescriptor(obj):
608 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800609 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800610 meth = getattr(obj, "fileno", None)
611 if meth is not None:
612 obj = meth()
613
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800614 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800615 fd = obj
616
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800617 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800618 raise TypeError("argument must be an int, or have a fileno() method.")
619 elif fd < 0:
620 raise ValueError(
621 "file descriptor cannot be a negative integer (%i)" % (fd,))
622
623 return fd
624
625
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800626def SSLeay_version(type):
627 """
628 Return a string describing the version of OpenSSL in use.
629
Alex Chand072cae2018-02-15 09:57:59 +0000630 :param type: One of the :const:`SSLEAY_` constants defined in this module.
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800631 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800633
634
Alex Gaynorbe2bd542019-02-21 21:41:22 -0500635def _warn_npn():
636 warnings.warn("NPN is deprecated. Protocols should switch to using ALPN.",
637 DeprecationWarning, stacklevel=3)
638
639
Cory Benfieldef404df2016-03-29 15:32:48 +0100640def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400641 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100642 Builds a decorator that ensures that functions that rely on OpenSSL
643 functions that are not present in this build raise NotImplementedError,
644 rather than AttributeError coming out of cryptography.
645
646 :param flag: A cryptography flag that guards the functions, e.g.
647 ``Cryptography_HAS_NEXTPROTONEG``.
648 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400649 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100650 def _requires_decorator(func):
651 if not flag:
652 @wraps(func)
653 def explode(*args, **kwargs):
654 raise NotImplementedError(error)
655 return explode
656 else:
657 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400658
Cory Benfieldef404df2016-03-29 15:32:48 +0100659 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400660
661
Cory Benfieldef404df2016-03-29 15:32:48 +0100662_requires_npn = _make_requires(
663 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
664)
Cory Benfield7907e332015-04-13 17:18:25 -0400665
666
Cory Benfieldef404df2016-03-29 15:32:48 +0100667_requires_alpn = _make_requires(
668 _lib.Cryptography_HAS_ALPN, "ALPN not available"
669)
Cory Benfielde6f35882016-03-29 11:21:04 +0100670
Cory Benfielde6f35882016-03-29 11:21:04 +0100671
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800672class Session(object):
Alex Chand072cae2018-02-15 09:57:59 +0000673 """
674 A class representing an SSL session. A session defines certain connection
675 parameters which may be re-used to speed up the setup of subsequent
676 connections.
677
678 .. versionadded:: 0.14
679 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800680 pass
681
682
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800683class Context(object):
684 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100685 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400686 up new SSL connections.
Alex Chand072cae2018-02-15 09:57:59 +0000687
688 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
689 TLSv1_METHOD.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690 """
691 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800692 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500693 SSLv3_METHOD: "SSLv3_method",
694 SSLv23_METHOD: "SSLv23_method",
695 TLSv1_METHOD: "TLSv1_method",
696 TLSv1_1_METHOD: "TLSv1_1_method",
697 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400698 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500699 _methods = dict(
700 (identifier, getattr(_lib, name))
701 for (identifier, name) in _methods.items()
702 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800703
704 def __init__(self, method):
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500705 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800706 raise TypeError("method must be an integer")
707
708 try:
709 method_func = self._methods[method]
710 except KeyError:
711 raise ValueError("No such protocol")
712
713 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700714 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800715
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500716 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700717 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500718 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800719
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600720 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
721 # will be auto-selected. This function was added in 1.0.2 and made a
722 # noop in 1.1.0+ (where it is set automatically).
723 try:
724 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
725 _openssl_assert(res == 1)
726 except AttributeError:
727 pass
728
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800730 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800731 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800732 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800733 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800734 self._verify_callback = None
735 self._info_callback = None
736 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800737 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000738 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100739 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000740 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100741 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400742 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100743 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000744 self._ocsp_helper = None
745 self._ocsp_callback = None
746 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800747
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500748 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800749
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750 def load_verify_locations(self, cafile, capath=None):
751 """
752 Let SSL know where we can find trusted certificates for the certificate
Alex Chand072cae2018-02-15 09:57:59 +0000753 chain. Note that the certificates have to be in PEM format.
754
755 If capath is passed, it must be a directory prepared using the
756 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
757 *pemfile* or *capath* may be :data:`None`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400759 :param cafile: In which file we can find the certificates (``bytes`` or
760 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400762 (``bytes`` or ``unicode``).
763
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800764 :return: None
765 """
766 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400768 else:
769 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800770
771 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500772 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400773 else:
774 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800775
Alex Gaynor62da94d2015-09-05 14:37:34 -0400776 load_result = _lib.SSL_CTX_load_verify_locations(
777 self._context, cafile, capath
778 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800779 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500780 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800781
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782 def _wrap_callback(self, callback):
783 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800784 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785 return callback(size, verify, self._passphrase_userdata)
786 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800787 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789 def set_passwd_cb(self, callback, userdata=None):
790 """
Alex Chand072cae2018-02-15 09:57:59 +0000791 Set the passphrase callback. This function will be called
792 when a private key with a passphrase is loaded.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Alex Chand072cae2018-02-15 09:57:59 +0000794 :param callback: The Python callback to use. This must accept three
795 positional arguments. First, an integer giving the maximum length
796 of the passphrase it may return. If the returned passphrase is
797 longer than this, it will be truncated. Second, a boolean value
798 which will be true if the user should be prompted for the
799 passphrase twice and the callback should verify that the two values
800 supplied are equal. Third, the value given as the *userdata*
801 parameter to :meth:`set_passwd_cb`. The *callback* must return
802 a byte string. If an error occurs, *callback* should return a false
803 value (e.g. an empty string).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800804 :param userdata: (optional) A Python object which will be given as
805 argument to the callback
806 :return: None
807 """
808 if not callable(callback):
809 raise TypeError("callback must be callable")
810
811 self._passphrase_helper = self._wrap_callback(callback)
812 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500813 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814 self._context, self._passphrase_callback)
815 self._passphrase_userdata = userdata
816
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817 def set_default_verify_paths(self):
818 """
Alex Chand072cae2018-02-15 09:57:59 +0000819 Specify that the platform provided CA certificates are to be used for
820 verification purposes. This method has some caveats related to the
821 binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
822
823 * macOS will only load certificates using this method if the user has
824 the ``openssl@1.1`` `Homebrew <https://brew.sh>`_ formula installed
825 in the default location.
826 * Windows will not work.
827 * manylinux1 cryptography wheels will work on most common Linux
828 distributions in pyOpenSSL 17.1.0 and above. pyOpenSSL detects the
829 manylinux1 wheel and attempts to load roots via a fallback path.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800830
831 :return: None
832 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500833 # SSL_CTX_set_default_verify_paths will attempt to load certs from
834 # both a cafile and capath that are set at compile time. However,
835 # it will first check environment variables and, if present, load
836 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500837 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400838 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500839 # After attempting to set default_verify_paths we need to know whether
840 # to go down the fallback path.
841 # First we'll check to see if any env vars have been set. If so,
842 # we won't try to do anything else because the user has set the path
843 # themselves.
844 dir_env_var = _ffi.string(
845 _lib.X509_get_default_cert_dir_env()
846 ).decode("ascii")
847 file_env_var = _ffi.string(
848 _lib.X509_get_default_cert_file_env()
849 ).decode("ascii")
850 if not self._check_env_vars_set(dir_env_var, file_env_var):
851 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
852 default_file = _ffi.string(_lib.X509_get_default_cert_file())
853 # Now we check to see if the default_dir and default_file are set
854 # to the exact values we use in our manylinux1 builds. If they are
855 # then we know to load the fallbacks
856 if (
857 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
858 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
859 ):
860 # This is manylinux1, let's load our fallback paths
861 self._fallback_default_verify_paths(
862 _CERTIFICATE_FILE_LOCATIONS,
863 _CERTIFICATE_PATH_LOCATIONS
864 )
865
866 def _check_env_vars_set(self, dir_env_var, file_env_var):
867 """
868 Check to see if the default cert dir/file environment vars are present.
869
870 :return: bool
871 """
872 return (
873 os.environ.get(file_env_var) is not None or
874 os.environ.get(dir_env_var) is not None
875 )
876
877 def _fallback_default_verify_paths(self, file_path, dir_path):
878 """
879 Default verify paths are based on the compiled version of OpenSSL.
880 However, when pyca/cryptography is compiled as a manylinux1 wheel
881 that compiled location can potentially be wrong. So, like Go, we
882 will try a predefined set of paths and attempt to load roots
883 from there.
884
885 :return: None
886 """
887 for cafile in file_path:
888 if os.path.isfile(cafile):
889 self.load_verify_locations(cafile)
890 break
891
892 for capath in dir_path:
893 if os.path.isdir(capath):
894 self.load_verify_locations(None, capath)
895 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800896
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800897 def use_certificate_chain_file(self, certfile):
898 """
Alex Chand072cae2018-02-15 09:57:59 +0000899 Load a certificate chain from a file.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400901 :param certfile: The name of the certificate chain file (``bytes`` or
Alex Chand072cae2018-02-15 09:57:59 +0000902 ``unicode``). Must be PEM encoded.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400903
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800904 :return: None
905 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400906 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800907
Alex Gaynor62da94d2015-09-05 14:37:34 -0400908 result = _lib.SSL_CTX_use_certificate_chain_file(
909 self._context, certfile
910 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800911 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500912 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800913
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800914 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800915 """
916 Load a certificate from a file
917
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400918 :param certfile: The name of the certificate file (``bytes`` or
919 ``unicode``).
Alex Chand072cae2018-02-15 09:57:59 +0000920 :param filetype: (optional) The encoding of the file, which is either
921 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
922 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400923
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800924 :return: None
925 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400926 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500927 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800928 raise TypeError("filetype must be an integer")
929
Alex Gaynor62da94d2015-09-05 14:37:34 -0400930 use_result = _lib.SSL_CTX_use_certificate_file(
931 self._context, certfile, filetype
932 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800933 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500934 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 def use_certificate(self, cert):
937 """
938 Load a certificate from a X509 object
939
940 :param cert: The X509 object
941 :return: None
942 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800943 if not isinstance(cert, X509):
944 raise TypeError("cert must be an X509 instance")
945
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500946 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800947 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500948 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800949
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800950 def add_extra_chain_cert(self, certobj):
951 """
952 Add certificate to chain
953
954 :param certobj: The X509 certificate object to add to the chain
955 :return: None
956 """
957 if not isinstance(certobj, X509):
958 raise TypeError("certobj must be an X509 instance")
959
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500960 copy = _lib.X509_dup(certobj._x509)
961 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500963 # TODO: This is untested.
964 _lib.X509_free(copy)
965 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800967 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500968 if self._passphrase_helper is not None:
969 self._passphrase_helper.raise_if_problem(Error)
970
971 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800972
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400973 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974 """
975 Load a private key from a file
976
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400977 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Alex Chand072cae2018-02-15 09:57:59 +0000978 :param filetype: (optional) The encoding of the file, which is either
979 :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`. The default is
980 :const:`FILETYPE_PEM`.
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400981
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800982 :return: None
983 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400984 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800985
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400986 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500988 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 raise TypeError("filetype must be an integer")
990
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992 self._context, keyfile, filetype)
993 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800994 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800996 def use_privatekey(self, pkey):
997 """
998 Load a private key from a PKey object
999
1000 :param pkey: The PKey object
1001 :return: None
1002 """
1003 if not isinstance(pkey, PKey):
1004 raise TypeError("pkey must be a PKey instance")
1005
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001006 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001007 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -08001008 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010 def check_privatekey(self):
1011 """
Alex Chand072cae2018-02-15 09:57:59 +00001012 Check if the private key (loaded with :meth:`use_privatekey`) matches
1013 the certificate (loaded with :meth:`use_certificate`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014
Alex Chand072cae2018-02-15 09:57:59 +00001015 :return: :data:`None` (raises :exc:`Error` if something's wrong)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001016 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -05001017 if not _lib.SSL_CTX_check_private_key(self._context):
1018 _raise_current_error()
1019
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020 def load_client_ca(self, cafile):
1021 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001022 Load the trusted certificates that will be sent to the client. Does
1023 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -04001024 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001026 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001027 :return: None
1028 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001029 ca_list = _lib.SSL_load_client_CA_file(
1030 _text_to_bytes_and_warn("cafile", cafile)
1031 )
1032 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001033 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001034
1035 def set_session_id(self, buf):
1036 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001037 Set the session id to *buf* within which a session can be reused for
1038 this Context object. This is needed when doing session resumption,
1039 because there is no way for a stored session to know which Context
1040 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001042 :param bytes buf: The session id.
1043
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044 :returns: None
1045 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001046 buf = _text_to_bytes_and_warn("buf", buf)
1047 _openssl_assert(
1048 _lib.SSL_CTX_set_session_id_context(
1049 self._context,
1050 buf,
1051 len(buf),
1052 ) == 1
1053 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054
1055 def set_session_cache_mode(self, mode):
1056 """
Alex Chand072cae2018-02-15 09:57:59 +00001057 Set the behavior of the session cache used by all connections using
1058 this Context. The previously set mode is returned. See
1059 :const:`SESS_CACHE_*` for details about particular modes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001060
1061 :param mode: One or more of the SESS_CACHE_* flags (combine using
1062 bitwise or)
1063 :returns: The previously set caching mode.
Alex Chand072cae2018-02-15 09:57:59 +00001064
1065 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001067 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001068 raise TypeError("mode must be an integer")
1069
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001070 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001071
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001072 def get_session_cache_mode(self):
1073 """
Alex Chand072cae2018-02-15 09:57:59 +00001074 Get the current session cache mode.
1075
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001076 :returns: The currently used cache mode.
Alex Chand072cae2018-02-15 09:57:59 +00001077
1078 .. versionadded:: 0.14
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001079 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001080 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001081
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082 def set_verify(self, mode, callback):
1083 """
Alex Chand072cae2018-02-15 09:57:59 +00001084 et the verification flags for this Context object to *mode* and specify
1085 that *callback* should be used for verification callbacks.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086
Alex Chand072cae2018-02-15 09:57:59 +00001087 :param mode: The verify mode, this should be one of
1088 :const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
1089 :const:`VERIFY_PEER` is used, *mode* can be OR:ed with
1090 :const:`VERIFY_FAIL_IF_NO_PEER_CERT` and
1091 :const:`VERIFY_CLIENT_ONCE` to further control the behaviour.
1092 :param callback: The Python callback to use. This should take five
1093 arguments: A Connection object, an X509 object, and three integer
1094 variables, which are in turn potential error number, error depth
1095 and return code. *callback* should return True if verification
1096 passes and False otherwise.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001097 :return: None
1098
1099 See SSL_CTX_set_verify(3SSL) for further details.
1100 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001101 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001102 raise TypeError("mode must be an integer")
1103
1104 if not callable(callback):
1105 raise TypeError("callback must be callable")
1106
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001107 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001108 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001110
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111 def set_verify_depth(self, depth):
1112 """
Alex Chand072cae2018-02-15 09:57:59 +00001113 Set the maximum depth for the certificate chain verification that shall
1114 be allowed for this Context object.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001115
1116 :param depth: An integer specifying the verify depth
1117 :return: None
1118 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001119 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001120 raise TypeError("depth must be an integer")
1121
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001122 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001123
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124 def get_verify_mode(self):
1125 """
Alex Chand072cae2018-02-15 09:57:59 +00001126 Retrieve the Context object's verify mode, as set by
1127 :meth:`set_verify`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001128
1129 :return: The verify mode
1130 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001131 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001132
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001133 def get_verify_depth(self):
1134 """
Alex Chand072cae2018-02-15 09:57:59 +00001135 Retrieve the Context object's verify depth, as set by
1136 :meth:`set_verify_depth`.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001137
1138 :return: The verify depth
1139 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001140 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001141
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001142 def load_tmp_dh(self, dhfile):
1143 """
1144 Load parameters for Ephemeral Diffie-Hellman
1145
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001146 :param dhfile: The file to load EDH parameters from (``bytes`` or
1147 ``unicode``).
1148
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001149 :return: None
1150 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001151 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001152
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001153 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001155 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001157
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001158 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1159 dh = _ffi.gc(dh, _lib.DH_free)
1160 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001162 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001163 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001164 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001165
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001166 :param curve: A curve object to use as returned by either
Alex Chand072cae2018-02-15 09:57:59 +00001167 :meth:`OpenSSL.crypto.get_elliptic_curve` or
1168 :meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001169
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001170 :return: None
1171 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001172 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001173
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001174 def set_cipher_list(self, cipher_list):
1175 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001176 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001177
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001178 See the OpenSSL manual for more information (e.g.
1179 :manpage:`ciphers(1)`).
1180
1181 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182 :return: None
1183 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001184 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001185
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001186 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001187 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001188
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001189 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001190 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001191 )
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001192 # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
1193 # ciphers even if you pass an invalid cipher. Applications (like
1194 # Twisted) have tests that depend on an error being raised if an
1195 # invalid cipher string is passed, but without the following check
1196 # for the TLS 1.3 specific cipher suites it would never error.
1197 tmpconn = Connection(self, None)
Mark Williamsdf2480d2019-02-14 19:30:07 -08001198 if (
1199 tmpconn.get_cipher_list() == [
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001200 'TLS_AES_256_GCM_SHA384',
1201 'TLS_CHACHA20_POLY1305_SHA256',
1202 'TLS_AES_128_GCM_SHA256'
1203 ]
Mark Williamsdf2480d2019-02-14 19:30:07 -08001204 ):
1205 raise Error(
1206 [
1207 (
1208 'SSL routines',
1209 'SSL_CTX_set_cipher_list',
1210 'no cipher match',
1211 ),
1212 ],
1213 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001214
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215 def set_client_ca_list(self, certificate_authorities):
1216 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001217 Set the list of preferred client certificate signers for this server
1218 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001219
Alex Gaynor62da94d2015-09-05 14:37:34 -04001220 This list of certificate authorities will be sent to the client when
1221 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001222
1223 :param certificate_authorities: a sequence of X509Names.
1224 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001225
1226 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001227 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001228 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001229 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001230
1231 try:
1232 for ca_name in certificate_authorities:
1233 if not isinstance(ca_name, X509Name):
1234 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001235 "client CAs must be X509Name objects, not %s "
1236 "objects" % (
1237 type(ca_name).__name__,
1238 )
1239 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001241 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001242 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001243 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001244 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001245 _raise_current_error()
Alex Gaynorc3697ad2017-11-20 08:19:32 -05001246 except Exception:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001247 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001248 raise
1249
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001250 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001251
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001252 def add_client_ca(self, certificate_authority):
1253 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001254 Add the CA certificate to the list of preferred signers for this
1255 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001256
1257 The list of certificate authorities will be sent to the client when the
1258 server requests a client certificate.
1259
1260 :param certificate_authority: certificate authority's X509 certificate.
1261 :return: None
Alex Chand072cae2018-02-15 09:57:59 +00001262
1263 .. versionadded:: 0.10
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001264 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001265 if not isinstance(certificate_authority, X509):
1266 raise TypeError("certificate_authority must be an X509 instance")
1267
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001268 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001269 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001270 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001271
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001272 def set_timeout(self, timeout):
1273 """
Alex Chand072cae2018-02-15 09:57:59 +00001274 Set the timeout for newly created sessions for this Context object to
1275 *timeout*. The default value is 300 seconds. See the OpenSSL manual
1276 for more information (e.g. :manpage:`SSL_CTX_set_timeout(3)`).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001277
Alex Chand072cae2018-02-15 09:57:59 +00001278 :param timeout: The timeout in (whole) seconds
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001279 :return: The previous session timeout
1280 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001281 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001282 raise TypeError("timeout must be an integer")
1283
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001285
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001286 def get_timeout(self):
1287 """
Alex Chand072cae2018-02-15 09:57:59 +00001288 Retrieve session timeout, as set by :meth:`set_timeout`. The default
1289 is 300 seconds.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001290
1291 :return: The session timeout
1292 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001293 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001294
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001295 def set_info_callback(self, callback):
1296 """
Alex Chand072cae2018-02-15 09:57:59 +00001297 Set the information callback to *callback*. This function will be
1298 called from time to time during SSL handshakes.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001299
Alex Chand072cae2018-02-15 09:57:59 +00001300 :param callback: The Python callback to use. This should take three
1301 arguments: a Connection object and two integers. The first integer
1302 specifies where in the SSL handshake the function was called, and
1303 the other the return code from a (possibly failed) internal
1304 function call.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001305 :return: None
1306 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001307 @wraps(callback)
1308 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001309 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001310 self._info_callback = _ffi.callback(
1311 "void (*)(const SSL *, int, int)", wrapper)
1312 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001313
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001314 def get_app_data(self):
1315 """
Alex Chand072cae2018-02-15 09:57:59 +00001316 Get the application data (supplied via :meth:`set_app_data()`)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001317
1318 :return: The application data
1319 """
1320 return self._app_data
1321
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001322 def set_app_data(self, data):
1323 """
1324 Set the application data (will be returned from get_app_data())
1325
1326 :param data: Any Python object
1327 :return: None
1328 """
1329 self._app_data = data
1330
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001331 def get_cert_store(self):
1332 """
Alex Chand072cae2018-02-15 09:57:59 +00001333 Get the certificate store for the context. This can be used to add
1334 "trusted" certificates without using the
1335 :meth:`load_verify_locations` method.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001336
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001337 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001338 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001339 store = _lib.SSL_CTX_get_cert_store(self._context)
1340 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001341 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001342 return None
1343
1344 pystore = X509Store.__new__(X509Store)
1345 pystore._store = store
1346 return pystore
1347
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001348 def set_options(self, options):
1349 """
1350 Add options. Options set before are not cleared!
Alex Chand072cae2018-02-15 09:57:59 +00001351 This method should be used with the :const:`OP_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001352
1353 :param options: The options to add.
1354 :return: The new option bitmask.
1355 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001356 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001357 raise TypeError("options must be an integer")
1358
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001359 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001360
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001361 def set_mode(self, mode):
1362 """
Alex Chand072cae2018-02-15 09:57:59 +00001363 Add modes via bitmask. Modes set before are not cleared! This method
1364 should be used with the :const:`MODE_*` constants.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001365
1366 :param mode: The mode to add.
1367 :return: The new mode bitmask.
1368 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001369 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001370 raise TypeError("mode must be an integer")
1371
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001372 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001373
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001374 def set_tlsext_servername_callback(self, callback):
1375 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001376 Specify a callback function to be called when clients specify a server
1377 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001378
1379 :param callback: The callback function. It will be invoked with one
1380 argument, the Connection instance.
Alex Chand072cae2018-02-15 09:57:59 +00001381
1382 .. versionadded:: 0.13
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001383 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001384 @wraps(callback)
1385 def wrapper(ssl, alert, arg):
1386 callback(Connection._reverse_mapping[ssl])
1387 return 0
1388
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001389 self._tlsext_servername_callback = _ffi.callback(
David Benjamince5c3842018-05-21 21:14:46 -04001390 "int (*)(SSL *, int *, void *)", wrapper)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001391 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001392 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001393
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001394 def set_tlsext_use_srtp(self, profiles):
1395 """
1396 Enable support for negotiating SRTP keying material.
1397
1398 :param bytes profiles: A colon delimited list of protection profile
1399 names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``.
1400 :return: None
1401 """
1402 if not isinstance(profiles, bytes):
1403 raise TypeError("profiles must be a byte string.")
1404
1405 _openssl_assert(
1406 _lib.SSL_CTX_set_tlsext_use_srtp(self._context, profiles) == 0
1407 )
1408
Cory Benfield10b277f2015-04-13 17:12:42 -04001409 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001410 def set_npn_advertise_callback(self, callback):
1411 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001412 Specify a callback function that will be called when offering `Next
1413 Protocol Negotiation
1414 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001415
1416 :param callback: The callback function. It will be invoked with one
Alex Chand072cae2018-02-15 09:57:59 +00001417 argument, the :class:`Connection` instance. It should return a
1418 list of bytestrings representing the advertised protocols, like
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001419 ``[b'http/1.1', b'spdy/2']``.
Alex Chand072cae2018-02-15 09:57:59 +00001420
1421 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001422 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001423 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001424 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1425 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001426 _lib.SSL_CTX_set_next_protos_advertised_cb(
1427 self._context, self._npn_advertise_callback, _ffi.NULL)
1428
Cory Benfield10b277f2015-04-13 17:12:42 -04001429 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001430 def set_npn_select_callback(self, callback):
1431 """
1432 Specify a callback function that will be called when a server offers
1433 Next Protocol Negotiation options.
1434
1435 :param callback: The callback function. It will be invoked with two
1436 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001437 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1438 one of those bytestrings, the chosen protocol.
Alex Chand072cae2018-02-15 09:57:59 +00001439
1440 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01001441 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05001442 _warn_npn()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001443 self._npn_select_helper = _NpnSelectHelper(callback)
1444 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001445 _lib.SSL_CTX_set_next_proto_select_cb(
1446 self._context, self._npn_select_callback, _ffi.NULL)
1447
Cory Benfield7907e332015-04-13 17:18:25 -04001448 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001449 def set_alpn_protos(self, protos):
1450 """
Alex Chand072cae2018-02-15 09:57:59 +00001451 Specify the protocols that the client is prepared to speak after the
1452 TLS connection has been negotiated using Application Layer Protocol
1453 Negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001454
1455 :param protos: A list of the protocols to be offered to the server.
1456 This list should be a Python list of bytestrings representing the
1457 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1458 """
1459 # Take the list of protocols and join them together, prefixing them
1460 # with their lengths.
1461 protostr = b''.join(
1462 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1463 )
1464
1465 # Build a C string from the list. We don't need to save this off
1466 # because OpenSSL immediately copies the data out.
1467 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001468 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001469
Cory Benfield7907e332015-04-13 17:18:25 -04001470 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001471 def set_alpn_select_callback(self, callback):
1472 """
Alex Chand072cae2018-02-15 09:57:59 +00001473 Specify a callback function that will be called on the server when a
1474 client offers protocols using ALPN.
Cory Benfield12eae892014-06-07 15:42:56 +01001475
1476 :param callback: The callback function. It will be invoked with two
1477 arguments: the Connection, and a list of offered protocols as
1478 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001479 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001480 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001481 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001482 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001483 _lib.SSL_CTX_set_alpn_select_cb(
1484 self._context, self._alpn_select_callback, _ffi.NULL)
1485
Cory Benfield496652a2017-01-24 11:42:56 +00001486 def _set_ocsp_callback(self, helper, data):
1487 """
1488 This internal helper does the common work for
1489 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1490 almost all of it.
1491 """
1492 self._ocsp_helper = helper
1493 self._ocsp_callback = helper.callback
1494 if data is None:
1495 self._ocsp_data = _ffi.NULL
1496 else:
1497 self._ocsp_data = _ffi.new_handle(data)
1498
1499 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1500 self._context, self._ocsp_callback
1501 )
1502 _openssl_assert(rc == 1)
1503 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1504 _openssl_assert(rc == 1)
1505
1506 def set_ocsp_server_callback(self, callback, data=None):
1507 """
1508 Set a callback to provide OCSP data to be stapled to the TLS handshake
1509 on the server side.
1510
1511 :param callback: The callback function. It will be invoked with two
1512 arguments: the Connection, and the optional arbitrary data you have
1513 provided. The callback must return a bytestring that contains the
1514 OCSP data to staple to the handshake. If no OCSP data is available
1515 for this connection, return the empty bytestring.
1516 :param data: Some opaque data that will be passed into the callback
1517 function when called. This can be used to avoid needing to do
1518 complex data lookups or to keep track of what context is being
1519 used. This parameter is optional.
1520 """
1521 helper = _OCSPServerCallbackHelper(callback)
1522 self._set_ocsp_callback(helper, data)
1523
1524 def set_ocsp_client_callback(self, callback, data=None):
1525 """
1526 Set a callback to validate OCSP data stapled to the TLS handshake on
1527 the client side.
1528
1529 :param callback: The callback function. It will be invoked with three
1530 arguments: the Connection, a bytestring containing the stapled OCSP
1531 assertion, and the optional arbitrary data you have provided. The
1532 callback must return a boolean that indicates the result of
1533 validating the OCSP data: ``True`` if the OCSP data is valid and
1534 the certificate can be trusted, or ``False`` if either the OCSP
1535 data is invalid or the certificate has been revoked.
1536 :param data: Some opaque data that will be passed into the callback
1537 function when called. This can be used to avoid needing to do
1538 complex data lookups or to keep track of what context is being
1539 used. This parameter is optional.
1540 """
1541 helper = _OCSPClientCallbackHelper(callback)
1542 self._set_ocsp_callback(helper, data)
1543
Alex Chanc6077062016-11-18 13:53:39 +00001544
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545class Connection(object):
1546 """
1547 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001548 _reverse_mapping = WeakValueDictionary()
1549
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001550 def __init__(self, context, socket=None):
1551 """
1552 Create a new Connection object, using the given OpenSSL.SSL.Context
1553 instance and socket.
1554
1555 :param context: An SSL Context to use for this connection
1556 :param socket: The socket to use for transport layer
1557 """
1558 if not isinstance(context, Context):
1559 raise TypeError("context must be a Context instance")
1560
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001561 ssl = _lib.SSL_new(context._context)
1562 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Paul Kehrer15c29352018-05-14 13:31:27 -04001563 # We set SSL_MODE_AUTO_RETRY to handle situations where OpenSSL returns
1564 # an SSL_ERROR_WANT_READ when processing a non-application data packet
1565 # even though there is still data on the underlying transport.
1566 # See https://github.com/openssl/openssl/issues/6234 for more details.
1567 _lib.SSL_set_mode(self._ssl, _lib.SSL_MODE_AUTO_RETRY)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001568 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001569 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001570
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001571 # References to strings used for Next Protocol Negotiation. OpenSSL's
1572 # header files suggest that these might get copied at some point, but
1573 # doesn't specify when, so we store them here to make sure they don't
1574 # get freed before OpenSSL uses them.
1575 self._npn_advertise_callback_args = None
1576 self._npn_select_callback_args = None
1577
Cory Benfield12eae892014-06-07 15:42:56 +01001578 # References to strings used for Application Layer Protocol
1579 # Negotiation. These strings get copied at some point but it's well
1580 # after the callback returns, so we have to hang them somewhere to
1581 # avoid them getting freed.
1582 self._alpn_select_callback_args = None
1583
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585
1586 if socket is None:
1587 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001588 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001589 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001590 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001591
Alex Gaynora829e902016-06-04 18:16:01 -07001592 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1593 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001595 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001597 self._into_ssl = None
1598 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001599 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001600 set_result = _lib.SSL_set_fd(
1601 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001602 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001603
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001604 def __getattr__(self, name):
1605 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001606 Look up attributes on the wrapped socket object if they are not found
1607 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608 """
kjav0b66fa12015-09-02 11:51:26 +01001609 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001610 raise AttributeError("'%s' object has no attribute '%s'" % (
1611 self.__class__.__name__, name
1612 ))
kjav0b66fa12015-09-02 11:51:26 +01001613 else:
1614 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001615
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001616 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001617 if self._context._verify_helper is not None:
1618 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001619 if self._context._npn_advertise_helper is not None:
1620 self._context._npn_advertise_helper.raise_if_problem()
1621 if self._context._npn_select_helper is not None:
1622 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001623 if self._context._alpn_select_helper is not None:
1624 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001625 if self._context._ocsp_helper is not None:
1626 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001627
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 error = _lib.SSL_get_error(ssl, result)
1629 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001630 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001631 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001632 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001633 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001634 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001635 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001636 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001637 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001638 elif error == _lib.SSL_ERROR_SYSCALL:
1639 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001640 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001641 if platform == "win32":
1642 errno = _ffi.getwinerror()[0]
1643 else:
1644 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001645
1646 if errno != 0:
1647 raise SysCallError(errno, errorcode.get(errno))
1648 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001649 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001650 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001651 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001652 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001653 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001655 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001657 def get_context(self):
1658 """
Alex Chand072cae2018-02-15 09:57:59 +00001659 Retrieve the :class:`Context` object associated with this
1660 :class:`Connection`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 """
Alex Chand072cae2018-02-15 09:57:59 +00001666 Switch this connection to a new session context.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001667
Alex Chand072cae2018-02-15 09:57:59 +00001668 :param context: A :class:`Context` instance giving the new session
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001669 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671 if not isinstance(context, Context):
1672 raise TypeError("context must be a Context instance")
1673
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001674 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675 self._context = context
1676
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677 def get_servername(self):
1678 """
1679 Retrieve the servername extension value if provided in the client hello
1680 message, or None if there wasn't one.
1681
Alex Chand072cae2018-02-15 09:57:59 +00001682 :return: A byte string giving the server name or :data:`None`.
1683
1684 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001685 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001686 name = _lib.SSL_get_servername(
1687 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1688 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001690 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001691
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001692 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001694 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001695 """
1696 Set the value of the servername extension to send in the client hello.
1697
1698 :param name: A byte string giving the name.
Alex Chand072cae2018-02-15 09:57:59 +00001699
1700 .. versionadded:: 0.13
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001702 if not isinstance(name, bytes):
1703 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001704 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001705 raise TypeError("name must not contain NUL byte")
1706
1707 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001708 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710 def pending(self):
1711 """
Alex Chand072cae2018-02-15 09:57:59 +00001712 Get the number of bytes that can be safely read from the SSL buffer
1713 (**not** the underlying transport buffer).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001714
1715 :return: The number of bytes available in the receive buffer.
1716 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001717 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001718
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001719 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001720 """
1721 Send data on the connection. NOTE: If you get one of the WantRead,
1722 WantWrite or WantX509Lookup exceptions on this, you have to call the
1723 method again with the SAME buffer.
1724
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001725 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 :param flags: (optional) Included for compatibility with the socket
1727 API, the value is ignored
1728 :return: The number of bytes written
1729 """
Abraham Martine82326c2015-02-04 10:18:10 +00001730 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001731 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001732
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001733 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001734 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001735 if isinstance(buf, _buffer):
1736 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001737 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001738 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001739 if len(buf) > 2147483647:
1740 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001741
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001742 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001743 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001744 return result
1745 write = send
1746
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001747 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001748 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001749 Send "all" data on the connection. This calls send() repeatedly until
1750 all data is sent. If an error occurs, it's impossible to tell how much
1751 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001752
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001753 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001754 :param flags: (optional) Included for compatibility with the socket
1755 API, the value is ignored
1756 :return: The number of bytes written
1757 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001758 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001759
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001760 if isinstance(buf, memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001761 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001762 if isinstance(buf, _buffer):
1763 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001764 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001765 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001766
1767 left_to_send = len(buf)
1768 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001769 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001770
1771 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001772 # SSL_write's num arg is an int,
1773 # so we cannot send more than 2**31-1 bytes at once.
1774 result = _lib.SSL_write(
1775 self._ssl,
1776 data + total_sent,
1777 min(left_to_send, 2147483647)
1778 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001779 self._raise_ssl_error(self._ssl, result)
1780 total_sent += result
1781 left_to_send -= result
1782
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001783 def recv(self, bufsiz, flags=None):
1784 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001785 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001786
1787 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001788 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1789 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001790 :return: The string read from the Connection
1791 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001792 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001793 if flags is not None and flags & socket.MSG_PEEK:
1794 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1795 else:
1796 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001797 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001798 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001799 read = recv
1800
Cory Benfield62d10332014-06-15 10:03:41 +01001801 def recv_into(self, buffer, nbytes=None, flags=None):
1802 """
Alex Chand072cae2018-02-15 09:57:59 +00001803 Receive data on the connection and copy it directly into the provided
1804 buffer, rather than creating a new string.
Cory Benfield62d10332014-06-15 10:03:41 +01001805
1806 :param buffer: The buffer to copy into.
1807 :param nbytes: (optional) The maximum number of bytes to read into the
1808 buffer. If not present, defaults to the size of the buffer. If
1809 larger than the size of the buffer, is reduced to the size of the
1810 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001811 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1812 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001813 :return: The number of bytes read into the buffer.
1814 """
1815 if nbytes is None:
1816 nbytes = len(buffer)
1817 else:
1818 nbytes = min(nbytes, len(buffer))
1819
1820 # We need to create a temporary buffer. This is annoying, it would be
1821 # better if we could pass memoryviews straight into the SSL_read call,
1822 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001823 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001824 if flags is not None and flags & socket.MSG_PEEK:
1825 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1826 else:
1827 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001828 self._raise_ssl_error(self._ssl, result)
1829
1830 # This strange line is all to avoid a memory copy. The buffer protocol
1831 # should allow us to assign a CFFI buffer to the LHS of this line, but
1832 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +01001833 # wrap it in a memoryview.
1834 buffer[:result] = memoryview(_ffi.buffer(buf, result))
Cory Benfield62d10332014-06-15 10:03:41 +01001835
1836 return result
1837
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001838 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001839 if _lib.BIO_should_retry(bio):
1840 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001841 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001842 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001843 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001844 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001845 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001846 # TODO: This is untested. I think io_special means the socket
1847 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001848 raise ValueError("BIO_should_io_special")
1849 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001850 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001851 raise ValueError("unknown bio failure")
1852 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001853 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001854 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001855
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001856 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857 """
Alex Chand072cae2018-02-15 09:57:59 +00001858 If the Connection was created with a memory BIO, this method can be
1859 used to read bytes from the write end of that memory BIO. Many
1860 Connection methods will add bytes which must be read in this manner or
1861 the buffer will eventually fill up and the Connection will be able to
1862 take no further actions.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001863
1864 :param bufsiz: The maximum number of bytes to read
1865 :return: The string read.
1866 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001867 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001868 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001869
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001870 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001871 raise TypeError("bufsiz must be an integer")
1872
Cory Benfielde62840e2016-11-28 12:17:08 +00001873 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001874 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001875 if result <= 0:
1876 self._handle_bio_errors(self._from_ssl, result)
1877
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001878 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001879
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001880 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881 """
Alex Chand072cae2018-02-15 09:57:59 +00001882 If the Connection was created with a memory BIO, this method can be
1883 used to add bytes to the read end of that memory BIO. The Connection
1884 can then read the bytes (for example, in response to a call to
1885 :meth:`recv`).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001886
1887 :param buf: The string to put into the memory BIO.
1888 :return: The number of bytes written
1889 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001890 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001891
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001892 if self._into_ssl is None:
1893 raise TypeError("Connection sock was not None")
1894
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001895 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001896 if result <= 0:
1897 self._handle_bio_errors(self._into_ssl, result)
1898 return result
1899
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001900 def renegotiate(self):
1901 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001902 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001903
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001904 :return: True if the renegotiation can be started, False otherwise
1905 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001906 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001907 if not self.renegotiate_pending():
1908 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1909 return True
1910 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001911
1912 def do_handshake(self):
1913 """
Alex Chand072cae2018-02-15 09:57:59 +00001914 Perform an SSL handshake (usually called after :meth:`renegotiate` or
Daniel Holth3efa98c2019-07-05 14:50:57 -04001915 one of :meth:`set_accept_state` or :meth:`set_connect_state`). This can
Alex Chand072cae2018-02-15 09:57:59 +00001916 raise the same exceptions as :meth:`send` and :meth:`recv`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917
1918 :return: None.
1919 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001920 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001921 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001922
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001923 def renegotiate_pending(self):
1924 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001925 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926 a renegotiation is finished.
1927
1928 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001929 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001931 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932
1933 def total_renegotiations(self):
1934 """
1935 Find out the total number of renegotiations.
1936
1937 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001938 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001940 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001942 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943 """
Alex Chand072cae2018-02-15 09:57:59 +00001944 Call the :meth:`connect` method of the underlying socket and set up SSL
1945 on the socket, using the :class:`Context` object supplied to this
1946 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947
1948 :param addr: A remote address
1949 :return: What the socket's connect method returns
1950 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001951 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001952 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001953
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001954 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001955 """
Alex Chand072cae2018-02-15 09:57:59 +00001956 Call the :meth:`connect_ex` method of the underlying socket and set up
1957 SSL on the socket, using the Context object supplied to this Connection
1958 object at creation. Note that if the :meth:`connect_ex` method of the
1959 socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001960
1961 :param addr: A remove address
1962 :return: What the socket's connect_ex method returns
1963 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001964 connect_ex = self._socket.connect_ex
1965 self.set_connect_state()
1966 return connect_ex(addr)
1967
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001968 def accept(self):
1969 """
Alex Chand072cae2018-02-15 09:57:59 +00001970 Call the :meth:`accept` method of the underlying socket and set up SSL
1971 on the returned socket, using the Context object supplied to this
1972 :class:`Connection` object at creation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001973
Alex Chand072cae2018-02-15 09:57:59 +00001974 :return: A *(conn, addr)* pair where *conn* is the new
1975 :class:`Connection` object created, and *address* is as returned by
1976 the socket's :meth:`accept`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001977 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001978 client, addr = self._socket.accept()
1979 conn = Connection(self._context, client)
1980 conn.set_accept_state()
1981 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001982
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983 def bio_shutdown(self):
1984 """
Alex Chand072cae2018-02-15 09:57:59 +00001985 If the Connection was created with a memory BIO, this method can be
1986 used to indicate that *end of file* has been reached on the read end of
1987 that memory BIO.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001988
1989 :return: None
1990 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991 if self._from_ssl is None:
1992 raise TypeError("Connection sock was not None")
1993
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001994 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001995
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001996 def shutdown(self):
1997 """
Alex Chand072cae2018-02-15 09:57:59 +00001998 Send the shutdown message to the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999
2000 :return: True if the shutdown completed successfully (i.e. both sides
Alex Chand072cae2018-02-15 09:57:59 +00002001 have sent closure alerts), False otherwise (in which case you
2002 call :meth:`recv` or :meth:`send` when the connection becomes
2003 readable/writeable).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002004 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002005 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002006 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08002007 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002009 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002010 else:
2011 return False
2012
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002013 def get_cipher_list(self):
2014 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002015 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016
Hynek Schlawackf90e3682016-03-11 11:21:13 +01002017 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018 """
2019 ciphers = []
2020 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002021 result = _lib.SSL_get_cipher_list(self._ssl, i)
2022 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002023 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002024 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025 return ciphers
2026
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027 def get_client_ca_list(self):
2028 """
2029 Get CAs whose certificates are suggested for client authentication.
2030
Alex Chand072cae2018-02-15 09:57:59 +00002031 :return: If this is a server connection, the list of certificate
2032 authorities that will be sent or has been sent to the client, as
2033 controlled by this :class:`Connection`'s :class:`Context`.
2034
2035 If this is a client connection, the list will be empty until the
2036 connection with the server is established.
2037
2038 .. versionadded:: 0.10
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002039 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002040 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
2041 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05002042 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002043 return []
2044
2045 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002046 for i in range(_lib.sk_X509_NAME_num(ca_names)):
2047 name = _lib.sk_X509_NAME_value(ca_names, i)
2048 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07002049 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002050
2051 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002052 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002053 result.append(pyname)
2054 return result
2055
Aykee7f33452018-05-16 19:18:16 +02002056 def makefile(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002057 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002058 The makefile() method is not implemented, since there is no dup
2059 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002060
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04002061 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002062 """
Alex Gaynor83284952015-09-05 10:43:30 -04002063 raise NotImplementedError(
2064 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002065
2066 def get_app_data(self):
2067 """
Alex Chand072cae2018-02-15 09:57:59 +00002068 Retrieve application data as set by :meth:`set_app_data`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002069
2070 :return: The application data
2071 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002072 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002073
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002074 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002075 """
2076 Set application data
2077
Alex Chand072cae2018-02-15 09:57:59 +00002078 :param data: The application data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002079 :return: None
2080 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002081 self._app_data = data
2082
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002083 def get_shutdown(self):
2084 """
Alex Chand072cae2018-02-15 09:57:59 +00002085 Get the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002086
Alex Gaynor62da94d2015-09-05 14:37:34 -04002087 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
2088 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002089 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002090 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002091
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002092 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002093 """
Alex Chand072cae2018-02-15 09:57:59 +00002094 Set the shutdown state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002095
Alex Chand072cae2018-02-15 09:57:59 +00002096 :param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002097 :return: None
2098 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002099 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002100 raise TypeError("state must be an integer")
2101
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002102 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002103
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002104 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002105 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002106 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002107
2108 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01002109 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002110 """
kjavc704a2e2015-09-07 12:12:27 +01002111 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002112
2113 def server_random(self):
2114 """
Alex Chand072cae2018-02-15 09:57:59 +00002115 Retrieve the random value used with the server hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002116
2117 :return: A string representing the state
2118 """
Alex Gaynor93603062016-06-01 20:13:09 -07002119 session = _lib.SSL_get_session(self._ssl)
2120 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002121 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002122 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
2123 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002124 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002125 _lib.SSL_get_server_random(self._ssl, outp, length)
2126 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002127
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002128 def client_random(self):
2129 """
Alex Chand072cae2018-02-15 09:57:59 +00002130 Retrieve the random value used with the client hello message.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002131
2132 :return: A string representing the state
2133 """
Alex Gaynor93603062016-06-01 20:13:09 -07002134 session = _lib.SSL_get_session(self._ssl)
2135 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002136 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002137
2138 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
2139 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002140 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002141 _lib.SSL_get_client_random(self._ssl, outp, length)
2142 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002143
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002144 def master_key(self):
2145 """
Alex Chand072cae2018-02-15 09:57:59 +00002146 Retrieve the value of the master key for this session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002147
2148 :return: A string representing the state
2149 """
Alex Gaynor93603062016-06-01 20:13:09 -07002150 session = _lib.SSL_get_session(self._ssl)
2151 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002152 return None
Alex Gaynor93603062016-06-01 20:13:09 -07002153
2154 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
2155 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00002156 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07002157 _lib.SSL_SESSION_get_master_key(session, outp, length)
2158 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002159
Paul Kehrerbdb76392017-12-01 04:54:32 +08002160 def export_keying_material(self, label, olen, context=None):
2161 """
2162 Obtain keying material for application use.
2163
Alex Chand072cae2018-02-15 09:57:59 +00002164 :param: label - a disambiguating label string as described in RFC 5705
2165 :param: olen - the length of the exported key material in bytes
2166 :param: context - a per-association context value
2167 :return: the exported key material bytes or None
Paul Kehrerbdb76392017-12-01 04:54:32 +08002168 """
2169 outp = _no_zero_allocator("unsigned char[]", olen)
2170 context_buf = _ffi.NULL
2171 context_len = 0
2172 use_context = 0
2173 if context is not None:
2174 context_buf = context
2175 context_len = len(context)
2176 use_context = 1
2177 success = _lib.SSL_export_keying_material(self._ssl, outp, olen,
2178 label, len(label),
2179 context_buf, context_len,
2180 use_context)
2181 _openssl_assert(success == 1)
2182 return _ffi.buffer(outp, olen)[:]
2183
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002184 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002185 """
Alex Chand072cae2018-02-15 09:57:59 +00002186 Call the :meth:`shutdown` method of the underlying socket.
2187 See :manpage:`shutdown(2)`.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002188
2189 :return: What the socket's shutdown() method returns
2190 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002191 return self._socket.shutdown(*args, **kwargs)
2192
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002193 def get_certificate(self):
2194 """
2195 Retrieve the local certificate (if any)
2196
2197 :return: The local certificate
2198 """
2199 cert = _lib.SSL_get_certificate(self._ssl)
2200 if cert != _ffi.NULL:
2201 _lib.X509_up_ref(cert)
2202 return X509._from_raw_x509_ptr(cert)
2203 return None
2204
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002205 def get_peer_certificate(self):
2206 """
2207 Retrieve the other side's certificate (if any)
2208
2209 :return: The peer's certificate
2210 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002211 cert = _lib.SSL_get_peer_certificate(self._ssl)
2212 if cert != _ffi.NULL:
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002213 return X509._from_raw_x509_ptr(cert)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002214 return None
2215
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002216 def get_peer_cert_chain(self):
2217 """
2218 Retrieve the other side's certificate (if any)
2219
2220 :return: A list of X509 instances giving the peer's certificate chain,
2221 or None if it does not have one.
2222 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
2224 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002225 return None
2226
2227 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002228 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08002229 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002230 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Alex Gaynor4aa52c32017-11-20 09:04:08 -05002231 pycert = X509._from_raw_x509_ptr(cert)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002232 result.append(pycert)
2233 return result
2234
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002235 def want_read(self):
2236 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002237 Checks if more data has to be read from the transport layer to complete
2238 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002239
2240 :return: True iff more data has to be read
2241 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002242 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002243
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002244 def want_write(self):
2245 """
2246 Checks if there is data to write to the transport layer to complete an
2247 operation.
2248
2249 :return: True iff there is data to write
2250 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002251 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002252
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002253 def set_accept_state(self):
2254 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002255 Set the connection to work in server mode. The handshake will be
2256 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002257
2258 :return: None
2259 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002260 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002261
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002262 def set_connect_state(self):
2263 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002264 Set the connection to work in client mode. The handshake will be
2265 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002266
2267 :return: None
2268 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002269 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002270
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002271 def get_session(self):
2272 """
2273 Returns the Session currently used.
2274
Alex Chand072cae2018-02-15 09:57:59 +00002275 :return: An instance of :class:`OpenSSL.SSL.Session` or
2276 :obj:`None` if no session exists.
2277
2278 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002279 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002280 session = _lib.SSL_get1_session(self._ssl)
2281 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002282 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002283
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002284 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002285 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002286 return pysession
2287
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002288 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002289 """
2290 Set the session to be used when the TLS/SSL connection is established.
2291
2292 :param session: A Session instance representing the session to use.
2293 :returns: None
Alex Chand072cae2018-02-15 09:57:59 +00002294
2295 .. versionadded:: 0.14
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002296 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002297 if not isinstance(session, Session):
2298 raise TypeError("session must be a Session instance")
2299
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002300 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002301 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002302 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002303
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002304 def _get_finished_message(self, function):
2305 """
Alex Chand072cae2018-02-15 09:57:59 +00002306 Helper to implement :meth:`get_finished` and
2307 :meth:`get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002308
Alex Chand072cae2018-02-15 09:57:59 +00002309 :param function: Either :data:`SSL_get_finished`: or
2310 :data:`SSL_get_peer_finished`.
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002311
Alex Chand072cae2018-02-15 09:57:59 +00002312 :return: :data:`None` if the desired message has not yet been
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002313 received, otherwise the contents of the message.
Alex Chand072cae2018-02-15 09:57:59 +00002314 :rtype: :class:`bytes` or :class:`NoneType`
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002315 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002316 # The OpenSSL documentation says nothing about what might happen if the
2317 # count argument given is zero. Specifically, it doesn't say whether
2318 # the output buffer may be NULL in that case or not. Inspection of the
2319 # implementation reveals that it calls memcpy() unconditionally.
2320 # Section 7.1.4, paragraph 1 of the C standard suggests that
2321 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2322 # alone desirable) behavior (though it probably does on just about
2323 # every implementation...)
2324 #
2325 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2326 # one might expect) for the initial call so as to be safe against this
2327 # potentially undefined behavior.
2328 empty = _ffi.new("char[]", 0)
2329 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002330 if size == 0:
2331 # No Finished message so far.
2332 return None
2333
Cory Benfielde62840e2016-11-28 12:17:08 +00002334 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002335 function(self._ssl, buf, size)
2336 return _ffi.buffer(buf, size)[:]
2337
Fedor Brunner5747b932014-03-05 14:22:34 +01002338 def get_finished(self):
2339 """
Alex Chand072cae2018-02-15 09:57:59 +00002340 Obtain the latest TLS Finished message that we sent.
Fedor Brunner5747b932014-03-05 14:22:34 +01002341
Alex Chand072cae2018-02-15 09:57:59 +00002342 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002343 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002344 :rtype: :class:`bytes` or :class:`NoneType`
2345
2346 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002347 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002348 return self._get_finished_message(_lib.SSL_get_finished)
2349
Fedor Brunner5747b932014-03-05 14:22:34 +01002350 def get_peer_finished(self):
2351 """
Alex Chand072cae2018-02-15 09:57:59 +00002352 Obtain the latest TLS Finished message that we received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002353
Alex Chand072cae2018-02-15 09:57:59 +00002354 :return: The contents of the message or :obj:`None` if the TLS
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002355 handshake has not yet completed.
Alex Chand072cae2018-02-15 09:57:59 +00002356 :rtype: :class:`bytes` or :class:`NoneType`
2357
2358 .. versionadded:: 0.15
Fedor Brunner5747b932014-03-05 14:22:34 +01002359 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002360 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002361
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002362 def get_cipher_name(self):
2363 """
2364 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002365
Alex Chand072cae2018-02-15 09:57:59 +00002366 :returns: The name of the currently used cipher or :obj:`None`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002367 if no connection has been established.
Alex Chand072cae2018-02-15 09:57:59 +00002368 :rtype: :class:`unicode` or :class:`NoneType`
2369
2370 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002371 """
2372 cipher = _lib.SSL_get_current_cipher(self._ssl)
2373 if cipher == _ffi.NULL:
2374 return None
2375 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002376 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2377 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002378
2379 def get_cipher_bits(self):
2380 """
2381 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002382
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002383 :returns: The number of secret bits of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002384 or :obj:`None` if no connection has been established.
2385 :rtype: :class:`int` or :class:`NoneType`
2386
2387 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002388 """
2389 cipher = _lib.SSL_get_current_cipher(self._ssl)
2390 if cipher == _ffi.NULL:
2391 return None
2392 else:
2393 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2394
2395 def get_cipher_version(self):
2396 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002397 Obtain the protocol version of the currently used cipher.
2398
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002399 :returns: The protocol name of the currently used cipher
Alex Chand072cae2018-02-15 09:57:59 +00002400 or :obj:`None` if no connection has been established.
2401 :rtype: :class:`unicode` or :class:`NoneType`
2402
2403 .. versionadded:: 0.15
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002404 """
2405 cipher = _lib.SSL_get_current_cipher(self._ssl)
2406 if cipher == _ffi.NULL:
2407 return None
2408 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002409 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002410 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002411
Jim Shaverabff1882015-05-27 09:15:55 -04002412 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002413 """
Alex Chand072cae2018-02-15 09:57:59 +00002414 Retrieve the protocol version of the current connection.
Jim Shaverba65e662015-04-26 12:23:40 -04002415
2416 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002417 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002418 for connections that were not successfully established.
Alex Chand072cae2018-02-15 09:57:59 +00002419 :rtype: :class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002420 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002421 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002422 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002423
Jim Shaver208438c2015-05-28 09:52:38 -04002424 def get_protocol_version(self):
2425 """
Alex Chand072cae2018-02-15 09:57:59 +00002426 Retrieve the SSL or TLS protocol version of the current connection.
Jim Shaver208438c2015-05-28 09:52:38 -04002427
Alex Chand072cae2018-02-15 09:57:59 +00002428 :returns: The TLS version of the current connection. For example,
2429 it will return ``0x769`` for connections made over TLS version 1.
2430 :rtype: :class:`int`
Jim Shaver208438c2015-05-28 09:52:38 -04002431 """
2432 version = _lib.SSL_version(self._ssl)
2433 return version
2434
Cory Benfield10b277f2015-04-13 17:12:42 -04002435 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002436 def get_next_proto_negotiated(self):
2437 """
2438 Get the protocol that was negotiated by NPN.
Alex Chand072cae2018-02-15 09:57:59 +00002439
2440 :returns: A bytestring of the protocol name. If no protocol has been
2441 negotiated yet, returns an empty string.
2442
2443 .. versionadded:: 0.15
Cory Benfield84a121e2014-03-31 20:30:25 +01002444 """
Alex Gaynorbe2bd542019-02-21 21:41:22 -05002445 _warn_npn()
Cory Benfield84a121e2014-03-31 20:30:25 +01002446 data = _ffi.new("unsigned char **")
2447 data_len = _ffi.new("unsigned int *")
2448
2449 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2450
Cory Benfieldcd010f62014-05-15 19:00:27 +01002451 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002452
Cory Benfield7907e332015-04-13 17:18:25 -04002453 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002454 def set_alpn_protos(self, protos):
2455 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002456 Specify the client's ALPN protocol list.
2457
2458 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002459
2460 :param protos: A list of the protocols to be offered to the server.
2461 This list should be a Python list of bytestrings representing the
2462 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2463 """
2464 # Take the list of protocols and join them together, prefixing them
2465 # with their lengths.
2466 protostr = b''.join(
2467 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2468 )
2469
2470 # Build a C string from the list. We don't need to save this off
2471 # because OpenSSL immediately copies the data out.
2472 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002473 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002474
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002475 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002476 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002477 """
2478 Get the protocol that was negotiated by ALPN.
Alex Chand072cae2018-02-15 09:57:59 +00002479
2480 :returns: A bytestring of the protocol name. If no protocol has been
2481 negotiated yet, returns an empty string.
Cory Benfield222f30e2015-04-13 18:10:21 -04002482 """
Cory Benfield12eae892014-06-07 15:42:56 +01002483 data = _ffi.new("unsigned char **")
2484 data_len = _ffi.new("unsigned int *")
2485
2486 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2487
Cory Benfielde8e9c382015-04-11 17:33:48 -04002488 if not data_len:
2489 return b''
2490
Cory Benfield12eae892014-06-07 15:42:56 +01002491 return _ffi.buffer(data[0], data_len[0])[:]
2492
Cory Benfield496652a2017-01-24 11:42:56 +00002493 def request_ocsp(self):
2494 """
2495 Called to request that the server sends stapled OCSP data, if
2496 available. If this is not called on the client side then the server
2497 will not send OCSP data. Should be used in conjunction with
2498 :meth:`Context.set_ocsp_client_callback`.
2499 """
2500 rc = _lib.SSL_set_tlsext_status_type(
2501 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2502 )
2503 _openssl_assert(rc == 1)
2504
Cory Benfield12eae892014-06-07 15:42:56 +01002505
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002506# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2507# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002508_lib.SSL_library_init()