blob: 8d94bd8da2d520ed6dc7d774a2e1deedba34aa56 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050030try:
31 _memoryview = memoryview
32except NameError:
33 class _memoryview(object):
34 pass
35
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020036try:
37 _buffer = buffer
38except NameError:
39 class _buffer(object):
40 pass
41
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050042OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
43SSLEAY_VERSION = _lib.SSLEAY_VERSION
44SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
45SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
46SSLEAY_DIR = _lib.SSLEAY_DIR
47SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080048
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050049SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
50RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080051
52SSLv2_METHOD = 1
53SSLv3_METHOD = 2
54SSLv23_METHOD = 3
55TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050056TLSv1_1_METHOD = 5
57TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080058
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050059OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
60OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
61OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -070062OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
63OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080064
Alex Gaynorbf012872016-06-04 13:18:39 -070065MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090068OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050069OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
70OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
71OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040072OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
73 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
74)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
76OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040077OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050078OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
79OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
80OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
81OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
82OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
83OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
84OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
85OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
86OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040087OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
88 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
89)
Alex Gaynorbf012872016-06-04 13:18:39 -070090OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080091
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050092OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
93OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040094OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080095
Alex Gaynorc4889812015-09-04 08:43:17 -040096OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098VERIFY_PEER = _lib.SSL_VERIFY_PEER
99VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
100VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
101VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500103SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
104SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
105SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
106SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
107SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
108SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
109SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
110SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500112SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
113SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
114SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400115if _lib.Cryptography_HAS_SSL_ST:
116 SSL_ST_INIT = _lib.SSL_ST_INIT
117 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
118 SSL_ST_OK = _lib.SSL_ST_OK
119 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121SSL_CB_LOOP = _lib.SSL_CB_LOOP
122SSL_CB_EXIT = _lib.SSL_CB_EXIT
123SSL_CB_READ = _lib.SSL_CB_READ
124SSL_CB_WRITE = _lib.SSL_CB_WRITE
125SSL_CB_ALERT = _lib.SSL_CB_ALERT
126SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
127SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
128SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
129SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
130SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
131SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
132SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
133SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800134
Paul Kehrer55fb3412017-06-29 18:44:08 -0500135# Taken from https://golang.org/src/crypto/x509/root_linux.go
136_CERTIFICATE_FILE_LOCATIONS = [
137 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
138 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
139 "/etc/ssl/ca-bundle.pem", # OpenSUSE
140 "/etc/pki/tls/cacert.pem", # OpenELEC
141 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
142]
143
144_CERTIFICATE_PATH_LOCATIONS = [
145 "/etc/ssl/certs", # SLES10/SLES11
146]
147
Paul Kehrera92a1a72017-07-19 15:53:23 +0200148# These values are compared to output from cffi's ffi.string so they must be
149# byte strings.
150_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
151_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
Paul Kehrer55fb3412017-06-29 18:44:08 -0500152
Alex Gaynor83284952015-09-05 10:43:30 -0400153
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500154class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500155 """
156 An error occurred in an `OpenSSL.SSL` API.
157 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158
159
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500160_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100161_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500162
163
164class WantReadError(Error):
165 pass
166
167
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500168class WantWriteError(Error):
169 pass
170
171
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500172class WantX509LookupError(Error):
173 pass
174
175
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500176class ZeroReturnError(Error):
177 pass
178
179
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500180class SysCallError(Error):
181 pass
182
183
Cory Benfield0ea76e72015-03-22 09:05:28 +0000184class _CallbackExceptionHelper(object):
185 """
186 A base class for wrapper classes that allow for intelligent exception
187 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500188
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400189 :ivar list _problems: Any exceptions that occurred while executing in a
190 context where they could not be raised in the normal way. Typically
191 this is because OpenSSL has called into some Python code and requires a
192 return value. The exceptions are saved to be raised later when it is
193 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000194 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400195
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400196 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800197 self._problems = []
198
Cory Benfield0ea76e72015-03-22 09:05:28 +0000199 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400200 """
201 Raise an exception from the OpenSSL error queue or that was previously
202 captured whe running a callback.
203 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000204 if self._problems:
205 try:
206 _raise_current_error()
207 except Error:
208 pass
209 raise self._problems.pop(0)
210
211
212class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400213 """
214 Wrap a callback such that it can be used as a certificate verification
215 callback.
216 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400217
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800218 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400219 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800220
221 @wraps(callback)
222 def wrapper(ok, store_ctx):
223 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500224 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
225 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
226 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800227
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400228 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
229 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
230 connection = Connection._reverse_mapping[ssl]
231
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800232 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400233 result = callback(
234 connection, cert, error_number, error_depth, ok
235 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800236 except Exception as e:
237 self._problems.append(e)
238 return 0
239 else:
240 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500241 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800242 return 1
243 else:
244 return 0
245
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500246 self.callback = _ffi.callback(
247 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800248
249
Cory Benfield0ea76e72015-03-22 09:05:28 +0000250class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400251 """
252 Wrap a callback such that it can be used as an NPN advertisement callback.
253 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400254
Cory Benfield0ea76e72015-03-22 09:05:28 +0000255 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400256 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800257
Cory Benfield0ea76e72015-03-22 09:05:28 +0000258 @wraps(callback)
259 def wrapper(ssl, out, outlen, arg):
260 try:
261 conn = Connection._reverse_mapping[ssl]
262 protos = callback(conn)
263
264 # Join the protocols into a Python bytestring, length-prefixing
265 # each element.
266 protostr = b''.join(
267 chain.from_iterable((int2byte(len(p)), p) for p in protos)
268 )
269
270 # Save our callback arguments on the connection object. This is
271 # done to make sure that they don't get freed before OpenSSL
272 # uses them. Then, return them appropriately in the output
273 # parameters.
274 conn._npn_advertise_callback_args = [
275 _ffi.new("unsigned int *", len(protostr)),
276 _ffi.new("unsigned char[]", protostr),
277 ]
278 outlen[0] = conn._npn_advertise_callback_args[0][0]
279 out[0] = conn._npn_advertise_callback_args[1]
280 return 0
281 except Exception as e:
282 self._problems.append(e)
283 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
284
285 self.callback = _ffi.callback(
286 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
287 wrapper
288 )
289
290
291class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400292 """
293 Wrap a callback such that it can be used as an NPN selection callback.
294 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400295
Cory Benfield0ea76e72015-03-22 09:05:28 +0000296 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400297 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000298
299 @wraps(callback)
300 def wrapper(ssl, out, outlen, in_, inlen, arg):
301 try:
302 conn = Connection._reverse_mapping[ssl]
303
304 # The string passed to us is actually made up of multiple
305 # length-prefixed bytestrings. We need to split that into a
306 # list.
307 instr = _ffi.buffer(in_, inlen)[:]
308 protolist = []
309 while instr:
310 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400311 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000312 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400313 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000314
315 # Call the callback
316 outstr = callback(conn, protolist)
317
318 # Save our callback arguments on the connection object. This is
319 # done to make sure that they don't get freed before OpenSSL
320 # uses them. Then, return them appropriately in the output
321 # parameters.
322 conn._npn_select_callback_args = [
323 _ffi.new("unsigned char *", len(outstr)),
324 _ffi.new("unsigned char[]", outstr),
325 ]
326 outlen[0] = conn._npn_select_callback_args[0][0]
327 out[0] = conn._npn_select_callback_args[1]
328 return 0
329 except Exception as e:
330 self._problems.append(e)
331 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
332
333 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400334 ("int (*)(SSL *, unsigned char **, unsigned char *, "
335 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000336 wrapper
337 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800338
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800339
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400340class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400341 """
342 Wrap a callback such that it can be used as an ALPN selection callback.
343 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400344
Cory Benfieldf1177e72015-04-12 09:11:49 -0400345 def __init__(self, callback):
346 _CallbackExceptionHelper.__init__(self)
347
348 @wraps(callback)
349 def wrapper(ssl, out, outlen, in_, inlen, arg):
350 try:
351 conn = Connection._reverse_mapping[ssl]
352
353 # The string passed to us is made up of multiple
354 # length-prefixed bytestrings. We need to split that into a
355 # list.
356 instr = _ffi.buffer(in_, inlen)[:]
357 protolist = []
358 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400359 encoded_len = indexbytes(instr, 0)
360 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400361 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400362 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400363
364 # Call the callback
365 outstr = callback(conn, protolist)
366
367 if not isinstance(outstr, _binary_type):
368 raise TypeError("ALPN callback must return a bytestring.")
369
370 # Save our callback arguments on the connection object to make
371 # sure that they don't get freed before OpenSSL can use them.
372 # Then, return them in the appropriate output parameters.
373 conn._alpn_select_callback_args = [
374 _ffi.new("unsigned char *", len(outstr)),
375 _ffi.new("unsigned char[]", outstr),
376 ]
377 outlen[0] = conn._alpn_select_callback_args[0][0]
378 out[0] = conn._alpn_select_callback_args[1]
379 return 0
380 except Exception as e:
381 self._problems.append(e)
382 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
383
384 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400385 ("int (*)(SSL *, unsigned char **, unsigned char *, "
386 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400387 wrapper
388 )
389
390
Cory Benfield496652a2017-01-24 11:42:56 +0000391class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
392 """
393 Wrap a callback such that it can be used as an OCSP callback for the server
394 side.
395
396 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
397 ways. For servers, that callback is expected to retrieve some OCSP data and
398 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
399 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
400 is expected to check the OCSP data, and returns a negative value on error,
401 0 if the response is not acceptable, or positive if it is. These are
402 mutually exclusive return code behaviours, and they mean that we need two
403 helpers so that we always return an appropriate error code if the user's
404 code throws an exception.
405
406 Given that we have to have two helpers anyway, these helpers are a bit more
407 helpery than most: specifically, they hide a few more of the OpenSSL
408 functions so that the user has an easier time writing these callbacks.
409
410 This helper implements the server side.
411 """
412
413 def __init__(self, callback):
414 _CallbackExceptionHelper.__init__(self)
415
416 @wraps(callback)
417 def wrapper(ssl, cdata):
418 try:
419 conn = Connection._reverse_mapping[ssl]
420
421 # Extract the data if any was provided.
422 if cdata != _ffi.NULL:
423 data = _ffi.from_handle(cdata)
424 else:
425 data = None
426
427 # Call the callback.
428 ocsp_data = callback(conn, data)
429
430 if not isinstance(ocsp_data, _binary_type):
431 raise TypeError("OCSP callback must return a bytestring.")
432
433 # If the OCSP data was provided, we will pass it to OpenSSL.
434 # However, we have an early exit here: if no OCSP data was
435 # provided we will just exit out and tell OpenSSL that there
436 # is nothing to do.
437 if not ocsp_data:
438 return 3 # SSL_TLSEXT_ERR_NOACK
439
440 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
441 # private copy of this data, so we need to keep it alive, but
442 # it *does* want to free it itself if it gets replaced. This
443 # somewhat bonkers behaviour means we need to use
444 # OPENSSL_malloc directly, which is a pain in the butt to work
445 # with. It's ok for us to "leak" the memory here because
446 # OpenSSL now owns it and will free it.
447 ocsp_data_length = len(ocsp_data)
448 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
449 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
450
451 _lib.SSL_set_tlsext_status_ocsp_resp(
452 ssl, data_ptr, ocsp_data_length
453 )
454
455 return 0
456 except Exception as e:
457 self._problems.append(e)
458 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
459
460 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
461
462
463class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
464 """
465 Wrap a callback such that it can be used as an OCSP callback for the client
466 side.
467
468 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
469 ways. For servers, that callback is expected to retrieve some OCSP data and
470 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
471 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
472 is expected to check the OCSP data, and returns a negative value on error,
473 0 if the response is not acceptable, or positive if it is. These are
474 mutually exclusive return code behaviours, and they mean that we need two
475 helpers so that we always return an appropriate error code if the user's
476 code throws an exception.
477
478 Given that we have to have two helpers anyway, these helpers are a bit more
479 helpery than most: specifically, they hide a few more of the OpenSSL
480 functions so that the user has an easier time writing these callbacks.
481
482 This helper implements the client side.
483 """
484
485 def __init__(self, callback):
486 _CallbackExceptionHelper.__init__(self)
487
488 @wraps(callback)
489 def wrapper(ssl, cdata):
490 try:
491 conn = Connection._reverse_mapping[ssl]
492
493 # Extract the data if any was provided.
494 if cdata != _ffi.NULL:
495 data = _ffi.from_handle(cdata)
496 else:
497 data = None
498
499 # Get the OCSP data.
500 ocsp_ptr = _ffi.new("unsigned char **")
501 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
502 if ocsp_len < 0:
503 # No OCSP data.
504 ocsp_data = b''
505 else:
506 # Copy the OCSP data, then pass it to the callback.
507 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
508
509 valid = callback(conn, ocsp_data, data)
510
511 # Return 1 on success or 0 on error.
512 return int(bool(valid))
513
514 except Exception as e:
515 self._problems.append(e)
516 # Return negative value if an exception is hit.
517 return -1
518
519 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
520
521
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800522def _asFileDescriptor(obj):
523 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800524 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800525 meth = getattr(obj, "fileno", None)
526 if meth is not None:
527 obj = meth()
528
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800529 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800530 fd = obj
531
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800532 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800533 raise TypeError("argument must be an int, or have a fileno() method.")
534 elif fd < 0:
535 raise ValueError(
536 "file descriptor cannot be a negative integer (%i)" % (fd,))
537
538 return fd
539
540
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800541def SSLeay_version(type):
542 """
543 Return a string describing the version of OpenSSL in use.
544
545 :param type: One of the SSLEAY_ constants defined in this module.
546 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500547 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800548
549
Cory Benfieldef404df2016-03-29 15:32:48 +0100550def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400551 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100552 Builds a decorator that ensures that functions that rely on OpenSSL
553 functions that are not present in this build raise NotImplementedError,
554 rather than AttributeError coming out of cryptography.
555
556 :param flag: A cryptography flag that guards the functions, e.g.
557 ``Cryptography_HAS_NEXTPROTONEG``.
558 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400559 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100560 def _requires_decorator(func):
561 if not flag:
562 @wraps(func)
563 def explode(*args, **kwargs):
564 raise NotImplementedError(error)
565 return explode
566 else:
567 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400568
Cory Benfieldef404df2016-03-29 15:32:48 +0100569 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400570
571
Cory Benfieldef404df2016-03-29 15:32:48 +0100572_requires_npn = _make_requires(
573 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
574)
Cory Benfield7907e332015-04-13 17:18:25 -0400575
576
Cory Benfieldef404df2016-03-29 15:32:48 +0100577_requires_alpn = _make_requires(
578 _lib.Cryptography_HAS_ALPN, "ALPN not available"
579)
Cory Benfielde6f35882016-03-29 11:21:04 +0100580
Cory Benfielde6f35882016-03-29 11:21:04 +0100581
Cory Benfieldef404df2016-03-29 15:32:48 +0100582_requires_sni = _make_requires(
583 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
584)
Cory Benfielde6f35882016-03-29 11:21:04 +0100585
586
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800587class Session(object):
588 pass
589
590
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800591class Context(object):
592 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100593 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400594 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800595 """
596 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800597 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500598 SSLv3_METHOD: "SSLv3_method",
599 SSLv23_METHOD: "SSLv23_method",
600 TLSv1_METHOD: "TLSv1_method",
601 TLSv1_1_METHOD: "TLSv1_1_method",
602 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400603 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500604 _methods = dict(
605 (identifier, getattr(_lib, name))
606 for (identifier, name) in _methods.items()
607 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608
609 def __init__(self, method):
610 """
611 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
612 TLSv1_METHOD.
613 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500614 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800615 raise TypeError("method must be an integer")
616
617 try:
618 method_func = self._methods[method]
619 except KeyError:
620 raise ValueError("No such protocol")
621
622 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700623 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800624
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500625 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700626 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500627 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800628
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600629 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
630 # will be auto-selected. This function was added in 1.0.2 and made a
631 # noop in 1.1.0+ (where it is set automatically).
632 try:
633 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
634 _openssl_assert(res == 1)
635 except AttributeError:
636 pass
637
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800639 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800640 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800641 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800642 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800643 self._verify_callback = None
644 self._info_callback = None
645 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800646 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000647 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100648 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000649 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100650 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400651 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100652 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000653 self._ocsp_helper = None
654 self._ocsp_callback = None
655 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500657 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800659 def load_verify_locations(self, cafile, capath=None):
660 """
661 Let SSL know where we can find trusted certificates for the certificate
662 chain
663
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400664 :param cafile: In which file we can find the certificates (``bytes`` or
665 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400667 (``bytes`` or ``unicode``).
668
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800669 :return: None
670 """
671 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500672 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400673 else:
674 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800675
676 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500677 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400678 else:
679 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680
Alex Gaynor62da94d2015-09-05 14:37:34 -0400681 load_result = _lib.SSL_CTX_load_verify_locations(
682 self._context, cafile, capath
683 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500685 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800686
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800687 def _wrap_callback(self, callback):
688 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800689 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690 return callback(size, verify, self._passphrase_userdata)
691 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800692 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694 def set_passwd_cb(self, callback, userdata=None):
695 """
696 Set the passphrase callback
697
698 :param callback: The Python callback to use
699 :param userdata: (optional) A Python object which will be given as
700 argument to the callback
701 :return: None
702 """
703 if not callable(callback):
704 raise TypeError("callback must be callable")
705
706 self._passphrase_helper = self._wrap_callback(callback)
707 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500708 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800709 self._context, self._passphrase_callback)
710 self._passphrase_userdata = userdata
711
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712 def set_default_verify_paths(self):
713 """
714 Use the platform-specific CA certificate locations
715
716 :return: None
717 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500718 # SSL_CTX_set_default_verify_paths will attempt to load certs from
719 # both a cafile and capath that are set at compile time. However,
720 # it will first check environment variables and, if present, load
721 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500722 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400723 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500724 # After attempting to set default_verify_paths we need to know whether
725 # to go down the fallback path.
726 # First we'll check to see if any env vars have been set. If so,
727 # we won't try to do anything else because the user has set the path
728 # themselves.
729 dir_env_var = _ffi.string(
730 _lib.X509_get_default_cert_dir_env()
731 ).decode("ascii")
732 file_env_var = _ffi.string(
733 _lib.X509_get_default_cert_file_env()
734 ).decode("ascii")
735 if not self._check_env_vars_set(dir_env_var, file_env_var):
736 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
737 default_file = _ffi.string(_lib.X509_get_default_cert_file())
738 # Now we check to see if the default_dir and default_file are set
739 # to the exact values we use in our manylinux1 builds. If they are
740 # then we know to load the fallbacks
741 if (
742 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
743 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
744 ):
745 # This is manylinux1, let's load our fallback paths
746 self._fallback_default_verify_paths(
747 _CERTIFICATE_FILE_LOCATIONS,
748 _CERTIFICATE_PATH_LOCATIONS
749 )
750
751 def _check_env_vars_set(self, dir_env_var, file_env_var):
752 """
753 Check to see if the default cert dir/file environment vars are present.
754
755 :return: bool
756 """
757 return (
758 os.environ.get(file_env_var) is not None or
759 os.environ.get(dir_env_var) is not None
760 )
761
762 def _fallback_default_verify_paths(self, file_path, dir_path):
763 """
764 Default verify paths are based on the compiled version of OpenSSL.
765 However, when pyca/cryptography is compiled as a manylinux1 wheel
766 that compiled location can potentially be wrong. So, like Go, we
767 will try a predefined set of paths and attempt to load roots
768 from there.
769
770 :return: None
771 """
772 for cafile in file_path:
773 if os.path.isfile(cafile):
774 self.load_verify_locations(cafile)
775 break
776
777 for capath in dir_path:
778 if os.path.isdir(capath):
779 self.load_verify_locations(None, capath)
780 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800781
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782 def use_certificate_chain_file(self, certfile):
783 """
784 Load a certificate chain from a file
785
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400786 :param certfile: The name of the certificate chain file (``bytes`` or
787 ``unicode``).
788
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789 :return: None
790 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400791 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800792
Alex Gaynor62da94d2015-09-05 14:37:34 -0400793 result = _lib.SSL_CTX_use_certificate_chain_file(
794 self._context, certfile
795 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800796 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500797 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800798
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800799 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800 """
801 Load a certificate from a file
802
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400803 :param certfile: The name of the certificate file (``bytes`` or
804 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800805 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400806
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800807 :return: None
808 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400809 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500810 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800811 raise TypeError("filetype must be an integer")
812
Alex Gaynor62da94d2015-09-05 14:37:34 -0400813 use_result = _lib.SSL_CTX_use_certificate_file(
814 self._context, certfile, filetype
815 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800816 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500817 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800818
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800819 def use_certificate(self, cert):
820 """
821 Load a certificate from a X509 object
822
823 :param cert: The X509 object
824 :return: None
825 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800826 if not isinstance(cert, X509):
827 raise TypeError("cert must be an X509 instance")
828
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500829 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800830 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500831 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800832
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800833 def add_extra_chain_cert(self, certobj):
834 """
835 Add certificate to chain
836
837 :param certobj: The X509 certificate object to add to the chain
838 :return: None
839 """
840 if not isinstance(certobj, X509):
841 raise TypeError("certobj must be an X509 instance")
842
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500843 copy = _lib.X509_dup(certobj._x509)
844 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500846 # TODO: This is untested.
847 _lib.X509_free(copy)
848 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800849
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800850 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500851 if self._passphrase_helper is not None:
852 self._passphrase_helper.raise_if_problem(Error)
853
854 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800855
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400856 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800857 """
858 Load a private key from a file
859
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400860 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800861 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400862
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800863 :return: None
864 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400865 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800866
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400867 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500869 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800870 raise TypeError("filetype must be an integer")
871
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873 self._context, keyfile, filetype)
874 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800875 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800876
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800877 def use_privatekey(self, pkey):
878 """
879 Load a private key from a PKey object
880
881 :param pkey: The PKey object
882 :return: None
883 """
884 if not isinstance(pkey, PKey):
885 raise TypeError("pkey must be a PKey instance")
886
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500887 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800888 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800889 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800890
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891 def check_privatekey(self):
892 """
893 Check that the private key and certificate match up
894
895 :return: None (raises an exception if something's wrong)
896 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500897 if not _lib.SSL_CTX_check_private_key(self._context):
898 _raise_current_error()
899
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900 def load_client_ca(self, cafile):
901 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100902 Load the trusted certificates that will be sent to the client. Does
903 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400904 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100906 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 :return: None
908 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100909 ca_list = _lib.SSL_load_client_CA_file(
910 _text_to_bytes_and_warn("cafile", cafile)
911 )
912 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100913 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800914
915 def set_session_id(self, buf):
916 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100917 Set the session id to *buf* within which a session can be reused for
918 this Context object. This is needed when doing session resumption,
919 because there is no way for a stored session to know which Context
920 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800921
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100922 :param bytes buf: The session id.
923
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800924 :returns: None
925 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100926 buf = _text_to_bytes_and_warn("buf", buf)
927 _openssl_assert(
928 _lib.SSL_CTX_set_session_id_context(
929 self._context,
930 buf,
931 len(buf),
932 ) == 1
933 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934
935 def set_session_cache_mode(self, mode):
936 """
937 Enable/disable session caching and specify the mode used.
938
939 :param mode: One or more of the SESS_CACHE_* flags (combine using
940 bitwise or)
941 :returns: The previously set caching mode.
942 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500943 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800944 raise TypeError("mode must be an integer")
945
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500946 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800947
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800948 def get_session_cache_mode(self):
949 """
950 :returns: The currently used cache mode.
951 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500952 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800953
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800954 def set_verify(self, mode, callback):
955 """
956 Set the verify mode and verify callback
957
958 :param mode: The verify mode, this is either VERIFY_NONE or
959 VERIFY_PEER combined with possible other flags
960 :param callback: The Python callback to use
961 :return: None
962
963 See SSL_CTX_set_verify(3SSL) for further details.
964 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500965 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966 raise TypeError("mode must be an integer")
967
968 if not callable(callback):
969 raise TypeError("callback must be callable")
970
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400971 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800972 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500973 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975 def set_verify_depth(self, depth):
976 """
977 Set the verify depth
978
979 :param depth: An integer specifying the verify depth
980 :return: None
981 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500982 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983 raise TypeError("depth must be an integer")
984
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500985 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987 def get_verify_mode(self):
988 """
989 Get the verify mode
990
991 :return: The verify mode
992 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995 def get_verify_depth(self):
996 """
997 Get the verify depth
998
999 :return: The verify depth
1000 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001001 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001002
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001003 def load_tmp_dh(self, dhfile):
1004 """
1005 Load parameters for Ephemeral Diffie-Hellman
1006
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001007 :param dhfile: The file to load EDH parameters from (``bytes`` or
1008 ``unicode``).
1009
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001010 :return: None
1011 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001012 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001013
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001014 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001015 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001016 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001017 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001018
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001019 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1020 dh = _ffi.gc(dh, _lib.DH_free)
1021 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001022
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001023 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001024 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001025 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001026
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001027 :param curve: A curve object to use as returned by either
1028 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
1029 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001030
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001031 :return: None
1032 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001033 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001034
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001035 def set_cipher_list(self, cipher_list):
1036 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001037 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001039 See the OpenSSL manual for more information (e.g.
1040 :manpage:`ciphers(1)`).
1041
1042 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 :return: None
1044 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001045 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001046
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001047 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001048 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001049
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001050 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001051 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001052 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001053
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001054 def set_client_ca_list(self, certificate_authorities):
1055 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001056 Set the list of preferred client certificate signers for this server
1057 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001058
Alex Gaynor62da94d2015-09-05 14:37:34 -04001059 This list of certificate authorities will be sent to the client when
1060 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
1062 :param certificate_authorities: a sequence of X509Names.
1063 :return: None
1064 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001065 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001066 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001067
1068 try:
1069 for ca_name in certificate_authorities:
1070 if not isinstance(ca_name, X509Name):
1071 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001072 "client CAs must be X509Name objects, not %s "
1073 "objects" % (
1074 type(ca_name).__name__,
1075 )
1076 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001078 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001080 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001082 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001083 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001084 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001085 raise
1086
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001088
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001089 def add_client_ca(self, certificate_authority):
1090 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001091 Add the CA certificate to the list of preferred signers for this
1092 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093
1094 The list of certificate authorities will be sent to the client when the
1095 server requests a client certificate.
1096
1097 :param certificate_authority: certificate authority's X509 certificate.
1098 :return: None
1099 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001100 if not isinstance(certificate_authority, X509):
1101 raise TypeError("certificate_authority must be an X509 instance")
1102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001103 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001104 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001105 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001106
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107 def set_timeout(self, timeout):
1108 """
1109 Set session timeout
1110
1111 :param timeout: The timeout in seconds
1112 :return: The previous session timeout
1113 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001114 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001115 raise TypeError("timeout must be an integer")
1116
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001117 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001118
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001119 def get_timeout(self):
1120 """
1121 Get the session timeout
1122
1123 :return: The session timeout
1124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001125 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001126
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127 def set_info_callback(self, callback):
1128 """
1129 Set the info callback
1130
1131 :param callback: The Python callback to use
1132 :return: None
1133 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001134 @wraps(callback)
1135 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001136 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001137 self._info_callback = _ffi.callback(
1138 "void (*)(const SSL *, int, int)", wrapper)
1139 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001140
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001141 def get_app_data(self):
1142 """
1143 Get the application data (supplied via set_app_data())
1144
1145 :return: The application data
1146 """
1147 return self._app_data
1148
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001149 def set_app_data(self, data):
1150 """
1151 Set the application data (will be returned from get_app_data())
1152
1153 :param data: Any Python object
1154 :return: None
1155 """
1156 self._app_data = data
1157
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001158 def get_cert_store(self):
1159 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001160 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001162 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001163 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001164 store = _lib.SSL_CTX_get_cert_store(self._context)
1165 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001166 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001167 return None
1168
1169 pystore = X509Store.__new__(X509Store)
1170 pystore._store = store
1171 return pystore
1172
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001173 def set_options(self, options):
1174 """
1175 Add options. Options set before are not cleared!
1176
1177 :param options: The options to add.
1178 :return: The new option bitmask.
1179 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001180 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001181 raise TypeError("options must be an integer")
1182
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001183 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001185 def set_mode(self, mode):
1186 """
1187 Add modes via bitmask. Modes set before are not cleared!
1188
1189 :param mode: The mode to add.
1190 :return: The new mode bitmask.
1191 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001192 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001193 raise TypeError("mode must be an integer")
1194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001195 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001196
Cory Benfielde6f35882016-03-29 11:21:04 +01001197 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001198 def set_tlsext_servername_callback(self, callback):
1199 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001200 Specify a callback function to be called when clients specify a server
1201 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001202
1203 :param callback: The callback function. It will be invoked with one
1204 argument, the Connection instance.
1205 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001206 @wraps(callback)
1207 def wrapper(ssl, alert, arg):
1208 callback(Connection._reverse_mapping[ssl])
1209 return 0
1210
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001211 self._tlsext_servername_callback = _ffi.callback(
1212 "int (*)(const SSL *, int *, void *)", wrapper)
1213 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001214 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001215
Cory Benfield10b277f2015-04-13 17:12:42 -04001216 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001217 def set_npn_advertise_callback(self, callback):
1218 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001219 Specify a callback function that will be called when offering `Next
1220 Protocol Negotiation
1221 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001222
1223 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001224 argument, the Connection instance. It should return a list of
1225 bytestrings representing the advertised protocols, like
1226 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001227 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001228 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1229 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001230 _lib.SSL_CTX_set_next_protos_advertised_cb(
1231 self._context, self._npn_advertise_callback, _ffi.NULL)
1232
Cory Benfield10b277f2015-04-13 17:12:42 -04001233 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001234 def set_npn_select_callback(self, callback):
1235 """
1236 Specify a callback function that will be called when a server offers
1237 Next Protocol Negotiation options.
1238
1239 :param callback: The callback function. It will be invoked with two
1240 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001241 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1242 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001243 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001244 self._npn_select_helper = _NpnSelectHelper(callback)
1245 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001246 _lib.SSL_CTX_set_next_proto_select_cb(
1247 self._context, self._npn_select_callback, _ffi.NULL)
1248
Cory Benfield7907e332015-04-13 17:18:25 -04001249 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001250 def set_alpn_protos(self, protos):
1251 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001252 Specify the clients ALPN protocol list.
1253
1254 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001255
1256 :param protos: A list of the protocols to be offered to the server.
1257 This list should be a Python list of bytestrings representing the
1258 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1259 """
1260 # Take the list of protocols and join them together, prefixing them
1261 # with their lengths.
1262 protostr = b''.join(
1263 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1264 )
1265
1266 # Build a C string from the list. We don't need to save this off
1267 # because OpenSSL immediately copies the data out.
1268 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001269 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001270
Cory Benfield7907e332015-04-13 17:18:25 -04001271 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001272 def set_alpn_select_callback(self, callback):
1273 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001274 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001275
1276 :param callback: The callback function. It will be invoked with two
1277 arguments: the Connection, and a list of offered protocols as
1278 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001279 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001280 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001281 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001282 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001283 _lib.SSL_CTX_set_alpn_select_cb(
1284 self._context, self._alpn_select_callback, _ffi.NULL)
1285
Cory Benfield496652a2017-01-24 11:42:56 +00001286 def _set_ocsp_callback(self, helper, data):
1287 """
1288 This internal helper does the common work for
1289 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1290 almost all of it.
1291 """
1292 self._ocsp_helper = helper
1293 self._ocsp_callback = helper.callback
1294 if data is None:
1295 self._ocsp_data = _ffi.NULL
1296 else:
1297 self._ocsp_data = _ffi.new_handle(data)
1298
1299 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1300 self._context, self._ocsp_callback
1301 )
1302 _openssl_assert(rc == 1)
1303 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1304 _openssl_assert(rc == 1)
1305
1306 def set_ocsp_server_callback(self, callback, data=None):
1307 """
1308 Set a callback to provide OCSP data to be stapled to the TLS handshake
1309 on the server side.
1310
1311 :param callback: The callback function. It will be invoked with two
1312 arguments: the Connection, and the optional arbitrary data you have
1313 provided. The callback must return a bytestring that contains the
1314 OCSP data to staple to the handshake. If no OCSP data is available
1315 for this connection, return the empty bytestring.
1316 :param data: Some opaque data that will be passed into the callback
1317 function when called. This can be used to avoid needing to do
1318 complex data lookups or to keep track of what context is being
1319 used. This parameter is optional.
1320 """
1321 helper = _OCSPServerCallbackHelper(callback)
1322 self._set_ocsp_callback(helper, data)
1323
1324 def set_ocsp_client_callback(self, callback, data=None):
1325 """
1326 Set a callback to validate OCSP data stapled to the TLS handshake on
1327 the client side.
1328
1329 :param callback: The callback function. It will be invoked with three
1330 arguments: the Connection, a bytestring containing the stapled OCSP
1331 assertion, and the optional arbitrary data you have provided. The
1332 callback must return a boolean that indicates the result of
1333 validating the OCSP data: ``True`` if the OCSP data is valid and
1334 the certificate can be trusted, or ``False`` if either the OCSP
1335 data is invalid or the certificate has been revoked.
1336 :param data: Some opaque data that will be passed into the callback
1337 function when called. This can be used to avoid needing to do
1338 complex data lookups or to keep track of what context is being
1339 used. This parameter is optional.
1340 """
1341 helper = _OCSPClientCallbackHelper(callback)
1342 self._set_ocsp_callback(helper, data)
1343
Alex Chanc6077062016-11-18 13:53:39 +00001344
Alex Gaynor10d30832017-06-29 15:31:39 -07001345ContextType = deprecated(
1346 Context, __name__,
1347 "ContextType has been deprecated, use Context instead", DeprecationWarning
1348)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001349
1350
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001351class Connection(object):
1352 """
1353 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001354 _reverse_mapping = WeakValueDictionary()
1355
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001356 def __init__(self, context, socket=None):
1357 """
1358 Create a new Connection object, using the given OpenSSL.SSL.Context
1359 instance and socket.
1360
1361 :param context: An SSL Context to use for this connection
1362 :param socket: The socket to use for transport layer
1363 """
1364 if not isinstance(context, Context):
1365 raise TypeError("context must be a Context instance")
1366
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001367 ssl = _lib.SSL_new(context._context)
1368 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001369 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001370 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001371
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001372 # References to strings used for Next Protocol Negotiation. OpenSSL's
1373 # header files suggest that these might get copied at some point, but
1374 # doesn't specify when, so we store them here to make sure they don't
1375 # get freed before OpenSSL uses them.
1376 self._npn_advertise_callback_args = None
1377 self._npn_select_callback_args = None
1378
Cory Benfield12eae892014-06-07 15:42:56 +01001379 # References to strings used for Application Layer Protocol
1380 # Negotiation. These strings get copied at some point but it's well
1381 # after the callback returns, so we have to hang them somewhere to
1382 # avoid them getting freed.
1383 self._alpn_select_callback_args = None
1384
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001386
1387 if socket is None:
1388 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001389 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001390 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001391 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001392
Alex Gaynora829e902016-06-04 18:16:01 -07001393 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1394 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001395
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001396 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001397 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001398 self._into_ssl = None
1399 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001400 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001401 set_result = _lib.SSL_set_fd(
1402 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001403 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001404
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001405 def __getattr__(self, name):
1406 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001407 Look up attributes on the wrapped socket object if they are not found
1408 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001409 """
kjav0b66fa12015-09-02 11:51:26 +01001410 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001411 raise AttributeError("'%s' object has no attribute '%s'" % (
1412 self.__class__.__name__, name
1413 ))
kjav0b66fa12015-09-02 11:51:26 +01001414 else:
1415 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001416
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001417 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001418 if self._context._verify_helper is not None:
1419 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001420 if self._context._npn_advertise_helper is not None:
1421 self._context._npn_advertise_helper.raise_if_problem()
1422 if self._context._npn_select_helper is not None:
1423 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001424 if self._context._alpn_select_helper is not None:
1425 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001426 if self._context._ocsp_helper is not None:
1427 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001428
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001429 error = _lib.SSL_get_error(ssl, result)
1430 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001431 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001432 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001433 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001434 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001435 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001436 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001437 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001438 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001439 elif error == _lib.SSL_ERROR_SYSCALL:
1440 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001441 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001442 if platform == "win32":
1443 errno = _ffi.getwinerror()[0]
1444 else:
1445 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001446
1447 if errno != 0:
1448 raise SysCallError(errno, errorcode.get(errno))
1449 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001451 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001452 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001453 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001454 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001455 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001456 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001457
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001458 def get_context(self):
1459 """
1460 Get session context
1461 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001462 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001464 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001465 """
1466 Switch this connection to a new session context
1467
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001468 :param context: A :py:class:`Context` instance giving the new session
1469 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001471 if not isinstance(context, Context):
1472 raise TypeError("context must be a Context instance")
1473
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001474 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001475 self._context = context
1476
Cory Benfielde6f35882016-03-29 11:21:04 +01001477 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001478 def get_servername(self):
1479 """
1480 Retrieve the servername extension value if provided in the client hello
1481 message, or None if there wasn't one.
1482
1483 :return: A byte string giving the server name or :py:data:`None`.
1484 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001485 name = _lib.SSL_get_servername(
1486 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1487 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001488 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001489 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001490
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001491 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001492
Cory Benfielde6f35882016-03-29 11:21:04 +01001493 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495 """
1496 Set the value of the servername extension to send in the client hello.
1497
1498 :param name: A byte string giving the name.
1499 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001500 if not isinstance(name, bytes):
1501 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001502 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503 raise TypeError("name must not contain NUL byte")
1504
1505 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001506 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001507
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001508 def pending(self):
1509 """
1510 Get the number of bytes that can be safely read from the connection
1511
1512 :return: The number of bytes available in the receive buffer.
1513 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001514 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001515
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001516 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517 """
1518 Send data on the connection. NOTE: If you get one of the WantRead,
1519 WantWrite or WantX509Lookup exceptions on this, you have to call the
1520 method again with the SAME buffer.
1521
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001522 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523 :param flags: (optional) Included for compatibility with the socket
1524 API, the value is ignored
1525 :return: The number of bytes written
1526 """
Abraham Martine82326c2015-02-04 10:18:10 +00001527 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001528 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001529
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001530 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001531 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001532 if isinstance(buf, _buffer):
1533 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001534 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001535 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001536 if len(buf) > 2147483647:
1537 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001539 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001540 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001541 return result
1542 write = send
1543
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001544 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001546 Send "all" data on the connection. This calls send() repeatedly until
1547 all data is sent. If an error occurs, it's impossible to tell how much
1548 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001549
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001550 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001551 :param flags: (optional) Included for compatibility with the socket
1552 API, the value is ignored
1553 :return: The number of bytes written
1554 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001555 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001556
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001557 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001558 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001559 if isinstance(buf, _buffer):
1560 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001561 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001562 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001563
1564 left_to_send = len(buf)
1565 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001566 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567
1568 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001569 # SSL_write's num arg is an int,
1570 # so we cannot send more than 2**31-1 bytes at once.
1571 result = _lib.SSL_write(
1572 self._ssl,
1573 data + total_sent,
1574 min(left_to_send, 2147483647)
1575 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001576 self._raise_ssl_error(self._ssl, result)
1577 total_sent += result
1578 left_to_send -= result
1579
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001580 def recv(self, bufsiz, flags=None):
1581 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001582 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001583
1584 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001585 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1586 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587 :return: The string read from the Connection
1588 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001589 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001590 if flags is not None and flags & socket.MSG_PEEK:
1591 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1592 else:
1593 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001594 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001595 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596 read = recv
1597
Cory Benfield62d10332014-06-15 10:03:41 +01001598 def recv_into(self, buffer, nbytes=None, flags=None):
1599 """
1600 Receive data on the connection and store the data into a buffer rather
1601 than creating a new string.
1602
1603 :param buffer: The buffer to copy into.
1604 :param nbytes: (optional) The maximum number of bytes to read into the
1605 buffer. If not present, defaults to the size of the buffer. If
1606 larger than the size of the buffer, is reduced to the size of the
1607 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001608 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1609 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001610 :return: The number of bytes read into the buffer.
1611 """
1612 if nbytes is None:
1613 nbytes = len(buffer)
1614 else:
1615 nbytes = min(nbytes, len(buffer))
1616
1617 # We need to create a temporary buffer. This is annoying, it would be
1618 # better if we could pass memoryviews straight into the SSL_read call,
1619 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001620 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001621 if flags is not None and flags & socket.MSG_PEEK:
1622 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1623 else:
1624 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001625 self._raise_ssl_error(self._ssl, result)
1626
1627 # This strange line is all to avoid a memory copy. The buffer protocol
1628 # should allow us to assign a CFFI buffer to the LHS of this line, but
1629 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1630 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1631 # memoryview type.
1632 try:
1633 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1634 except NameError:
1635 buffer[:result] = _ffi.buffer(buf, result)
1636
1637 return result
1638
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001640 if _lib.BIO_should_retry(bio):
1641 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001642 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001643 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001644 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001645 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001646 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001647 # TODO: This is untested. I think io_special means the socket
1648 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001649 raise ValueError("BIO_should_io_special")
1650 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001651 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001652 raise ValueError("unknown bio failure")
1653 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001654 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001655 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001658 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001659 When using non-socket connections this function reads the "dirty" data
1660 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661
1662 :param bufsiz: The maximum number of bytes to read
1663 :return: The string read.
1664 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001665 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001667
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001668 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001669 raise TypeError("bufsiz must be an integer")
1670
Cory Benfielde62840e2016-11-28 12:17:08 +00001671 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001672 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001673 if result <= 0:
1674 self._handle_bio_errors(self._from_ssl, result)
1675
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001676 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001677
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001680 When using non-socket connections this function sends "dirty" data that
1681 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682
1683 :param buf: The string to put into the memory BIO.
1684 :return: The number of bytes written
1685 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001686 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001687
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001688 if self._into_ssl is None:
1689 raise TypeError("Connection sock was not None")
1690
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001691 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001692 if result <= 0:
1693 self._handle_bio_errors(self._into_ssl, result)
1694 return result
1695
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 def renegotiate(self):
1697 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001698 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001699
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001700 :return: True if the renegotiation can be started, False otherwise
1701 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001703 if not self.renegotiate_pending():
1704 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1705 return True
1706 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001707
1708 def do_handshake(self):
1709 """
1710 Perform an SSL handshake (usually called after renegotiate() or one of
1711 set_*_state()). This can raise the same exceptions as send and recv.
1712
1713 :return: None.
1714 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001715 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001716 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001717
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001718 def renegotiate_pending(self):
1719 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001720 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721 a renegotiation is finished.
1722
1723 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001724 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001726 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001727
1728 def total_renegotiations(self):
1729 """
1730 Find out the total number of renegotiations.
1731
1732 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001733 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001734 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001735 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001736
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001737 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001738 """
1739 Connect to remote host and set up client-side SSL
1740
1741 :param addr: A remote address
1742 :return: What the socket's connect method returns
1743 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001744 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001746
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001747 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001748 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001749 Connect to remote host and set up client-side SSL. Note that if the
1750 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001751
1752 :param addr: A remove address
1753 :return: What the socket's connect_ex method returns
1754 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755 connect_ex = self._socket.connect_ex
1756 self.set_connect_state()
1757 return connect_ex(addr)
1758
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001759 def accept(self):
1760 """
1761 Accept incoming connection and set up SSL on it
1762
1763 :return: A (conn,addr) pair where conn is a Connection and addr is an
1764 address
1765 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001766 client, addr = self._socket.accept()
1767 conn = Connection(self._context, client)
1768 conn.set_accept_state()
1769 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001770
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001771 def bio_shutdown(self):
1772 """
1773 When using non-socket connections this function signals end of
1774 data on the input for this connection.
1775
1776 :return: None
1777 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001778 if self._from_ssl is None:
1779 raise TypeError("Connection sock was not None")
1780
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001781 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001782
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001783 def shutdown(self):
1784 """
1785 Send closure alert
1786
1787 :return: True if the shutdown completed successfully (i.e. both sides
1788 have sent closure alerts), false otherwise (i.e. you have to
1789 wait for a ZeroReturnError on a recv() method call
1790 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001791 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001793 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001795 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001796 else:
1797 return False
1798
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001799 def get_cipher_list(self):
1800 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001801 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001802
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001803 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001804 """
1805 ciphers = []
1806 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001807 result = _lib.SSL_get_cipher_list(self._ssl, i)
1808 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001810 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001811 return ciphers
1812
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001813 def get_client_ca_list(self):
1814 """
1815 Get CAs whose certificates are suggested for client authentication.
1816
Alex Gaynor62da94d2015-09-05 14:37:34 -04001817 :return: If this is a server connection, a list of X509Names
1818 representing the acceptable CAs as set by
1819 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1820 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1821 connection, the list of such X509Names sent by the server, or an
1822 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001824 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1825 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001826 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001827 return []
1828
1829 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001830 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1831 name = _lib.sk_X509_NAME_value(ca_names, i)
1832 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001833 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001834
1835 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001836 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001837 result.append(pyname)
1838 return result
1839
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001840 def makefile(self):
1841 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001842 The makefile() method is not implemented, since there is no dup
1843 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001844
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001845 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001846 """
Alex Gaynor83284952015-09-05 10:43:30 -04001847 raise NotImplementedError(
1848 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001849
1850 def get_app_data(self):
1851 """
1852 Get application data
1853
1854 :return: The application data
1855 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001856 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001858 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001859 """
1860 Set application data
1861
1862 :param data - The application data
1863 :return: None
1864 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001865 self._app_data = data
1866
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867 def get_shutdown(self):
1868 """
1869 Get shutdown state
1870
Alex Gaynor62da94d2015-09-05 14:37:34 -04001871 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1872 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001873 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001874 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001876 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001877 """
1878 Set shutdown state
1879
1880 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1881 :return: None
1882 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001883 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001884 raise TypeError("state must be an integer")
1885
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001887
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001888 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001890 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001891
1892 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001893 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001894 """
kjavc704a2e2015-09-07 12:12:27 +01001895 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896
1897 def server_random(self):
1898 """
1899 Get a copy of the server hello nonce.
1900
1901 :return: A string representing the state
1902 """
Alex Gaynor93603062016-06-01 20:13:09 -07001903 session = _lib.SSL_get_session(self._ssl)
1904 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001905 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001906 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1907 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001908 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001909 _lib.SSL_get_server_random(self._ssl, outp, length)
1910 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001911
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912 def client_random(self):
1913 """
1914 Get a copy of the client hello nonce.
1915
1916 :return: A string representing the state
1917 """
Alex Gaynor93603062016-06-01 20:13:09 -07001918 session = _lib.SSL_get_session(self._ssl)
1919 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001920 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001921
1922 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1923 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001924 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001925 _lib.SSL_get_client_random(self._ssl, outp, length)
1926 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001927
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001928 def master_key(self):
1929 """
1930 Get a copy of the master key.
1931
1932 :return: A string representing the state
1933 """
Alex Gaynor93603062016-06-01 20:13:09 -07001934 session = _lib.SSL_get_session(self._ssl)
1935 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001936 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001937
1938 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1939 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001940 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001941 _lib.SSL_SESSION_get_master_key(session, outp, length)
1942 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001944 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001945 """
1946 See shutdown(2)
1947
1948 :return: What the socket's shutdown() method returns
1949 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 return self._socket.shutdown(*args, **kwargs)
1951
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952 def get_peer_certificate(self):
1953 """
1954 Retrieve the other side's certificate (if any)
1955
1956 :return: The peer's certificate
1957 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001958 cert = _lib.SSL_get_peer_certificate(self._ssl)
1959 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001960 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001961 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001962 return pycert
1963 return None
1964
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001965 def get_peer_cert_chain(self):
1966 """
1967 Retrieve the other side's certificate (if any)
1968
1969 :return: A list of X509 instances giving the peer's certificate chain,
1970 or None if it does not have one.
1971 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001972 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1973 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001974 return None
1975
1976 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001977 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001978 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001979 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001981 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001982 result.append(pycert)
1983 return result
1984
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001985 def want_read(self):
1986 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001987 Checks if more data has to be read from the transport layer to complete
1988 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989
1990 :return: True iff more data has to be read
1991 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001992 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001993
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994 def want_write(self):
1995 """
1996 Checks if there is data to write to the transport layer to complete an
1997 operation.
1998
1999 :return: True iff there is data to write
2000 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002001 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002002
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002003 def set_accept_state(self):
2004 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002005 Set the connection to work in server mode. The handshake will be
2006 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002007
2008 :return: None
2009 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002010 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002012 def set_connect_state(self):
2013 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002014 Set the connection to work in client mode. The handshake will be
2015 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016
2017 :return: None
2018 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002019 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021 def get_session(self):
2022 """
2023 Returns the Session currently used.
2024
Alex Gaynor62da94d2015-09-05 14:37:34 -04002025 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
2026 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002027 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002028 session = _lib.SSL_get1_session(self._ssl)
2029 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002030 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002031
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002032 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002033 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002034 return pysession
2035
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002036 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002037 """
2038 Set the session to be used when the TLS/SSL connection is established.
2039
2040 :param session: A Session instance representing the session to use.
2041 :returns: None
2042 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002043 if not isinstance(session, Session):
2044 raise TypeError("session must be a Session instance")
2045
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002046 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002047 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002048 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002049
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002050 def _get_finished_message(self, function):
2051 """
2052 Helper to implement :py:meth:`get_finished` and
2053 :py:meth:`get_peer_finished`.
2054
2055 :param function: Either :py:data:`SSL_get_finished`: or
2056 :py:data:`SSL_get_peer_finished`.
2057
2058 :return: :py:data:`None` if the desired message has not yet been
2059 received, otherwise the contents of the message.
2060 :rtype: :py:class:`bytes` or :py:class:`NoneType`
2061 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002062 # The OpenSSL documentation says nothing about what might happen if the
2063 # count argument given is zero. Specifically, it doesn't say whether
2064 # the output buffer may be NULL in that case or not. Inspection of the
2065 # implementation reveals that it calls memcpy() unconditionally.
2066 # Section 7.1.4, paragraph 1 of the C standard suggests that
2067 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2068 # alone desirable) behavior (though it probably does on just about
2069 # every implementation...)
2070 #
2071 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2072 # one might expect) for the initial call so as to be safe against this
2073 # potentially undefined behavior.
2074 empty = _ffi.new("char[]", 0)
2075 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002076 if size == 0:
2077 # No Finished message so far.
2078 return None
2079
Cory Benfielde62840e2016-11-28 12:17:08 +00002080 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002081 function(self._ssl, buf, size)
2082 return _ffi.buffer(buf, size)[:]
2083
Fedor Brunner5747b932014-03-05 14:22:34 +01002084 def get_finished(self):
2085 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002086 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002087
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002088 :return: The contents of the message or :py:obj:`None` if the TLS
2089 handshake has not yet completed.
2090 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002091 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002092 return self._get_finished_message(_lib.SSL_get_finished)
2093
Fedor Brunner5747b932014-03-05 14:22:34 +01002094 def get_peer_finished(self):
2095 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002096 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002097
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002098 :return: The contents of the message or :py:obj:`None` if the TLS
2099 handshake has not yet completed.
2100 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002101 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002102 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002103
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002104 def get_cipher_name(self):
2105 """
2106 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002107
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002108 :returns: The name of the currently used cipher or :py:obj:`None`
2109 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002110 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002111 """
2112 cipher = _lib.SSL_get_current_cipher(self._ssl)
2113 if cipher == _ffi.NULL:
2114 return None
2115 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002116 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2117 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002118
2119 def get_cipher_bits(self):
2120 """
2121 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002122
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002123 :returns: The number of secret bits of the currently used cipher
2124 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002125 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002126 """
2127 cipher = _lib.SSL_get_current_cipher(self._ssl)
2128 if cipher == _ffi.NULL:
2129 return None
2130 else:
2131 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2132
2133 def get_cipher_version(self):
2134 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002135 Obtain the protocol version of the currently used cipher.
2136
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002137 :returns: The protocol name of the currently used cipher
2138 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002139 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002140 """
2141 cipher = _lib.SSL_get_current_cipher(self._ssl)
2142 if cipher == _ffi.NULL:
2143 return None
2144 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002145 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002146 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002147
Jim Shaverabff1882015-05-27 09:15:55 -04002148 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002149 """
2150 Obtain the protocol version of the current connection.
2151
2152 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002153 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002154 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002155 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002156 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002157 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002158 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002159
Jim Shaver208438c2015-05-28 09:52:38 -04002160 def get_protocol_version(self):
2161 """
2162 Obtain the protocol version of the current connection.
2163
2164 :returns: The TLS version of the current connection, for example
2165 the value for TLS 1 would be 0x769.
2166 :rtype: :py:class:`int`
2167 """
2168 version = _lib.SSL_version(self._ssl)
2169 return version
2170
Cory Benfield10b277f2015-04-13 17:12:42 -04002171 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002172 def get_next_proto_negotiated(self):
2173 """
2174 Get the protocol that was negotiated by NPN.
2175 """
2176 data = _ffi.new("unsigned char **")
2177 data_len = _ffi.new("unsigned int *")
2178
2179 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2180
Cory Benfieldcd010f62014-05-15 19:00:27 +01002181 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002182
Cory Benfield7907e332015-04-13 17:18:25 -04002183 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002184 def set_alpn_protos(self, protos):
2185 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002186 Specify the client's ALPN protocol list.
2187
2188 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002189
2190 :param protos: A list of the protocols to be offered to the server.
2191 This list should be a Python list of bytestrings representing the
2192 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2193 """
2194 # Take the list of protocols and join them together, prefixing them
2195 # with their lengths.
2196 protostr = b''.join(
2197 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2198 )
2199
2200 # Build a C string from the list. We don't need to save this off
2201 # because OpenSSL immediately copies the data out.
2202 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002203 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002204
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002205 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002206 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002207 """
2208 Get the protocol that was negotiated by ALPN.
2209 """
Cory Benfield12eae892014-06-07 15:42:56 +01002210 data = _ffi.new("unsigned char **")
2211 data_len = _ffi.new("unsigned int *")
2212
2213 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2214
Cory Benfielde8e9c382015-04-11 17:33:48 -04002215 if not data_len:
2216 return b''
2217
Cory Benfield12eae892014-06-07 15:42:56 +01002218 return _ffi.buffer(data[0], data_len[0])[:]
2219
Cory Benfield496652a2017-01-24 11:42:56 +00002220 def request_ocsp(self):
2221 """
2222 Called to request that the server sends stapled OCSP data, if
2223 available. If this is not called on the client side then the server
2224 will not send OCSP data. Should be used in conjunction with
2225 :meth:`Context.set_ocsp_client_callback`.
2226 """
2227 rc = _lib.SSL_set_tlsext_status_type(
2228 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2229 )
2230 _openssl_assert(rc == 1)
2231
Cory Benfield12eae892014-06-07 15:42:56 +01002232
Alex Gaynor10d30832017-06-29 15:31:39 -07002233ConnectionType = deprecated(
2234 Connection, __name__,
2235 "ConnectionType has been deprecated, use Connection instead",
2236 DeprecationWarning
2237)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002238
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002239# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2240# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002241_lib.SSL_library_init()