blob: a35c29934425c9f2052e1719b8cf63ea8f9d300d [file] [log] [blame]
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08001
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002from functools import wraps, partial
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08003from itertools import count
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08004from weakref import WeakValueDictionary
5from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08006
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05007from OpenSSL._util import (
8 ffi as _ffi,
9 lib as _lib,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050010 exception_from_error_queue as _exception_from_error_queue)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080011
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080012from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050013 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080014
15_unspecified = object()
16
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050017try:
18 _memoryview = memoryview
19except NameError:
20 class _memoryview(object):
21 pass
22
23
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050024OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
25SSLEAY_VERSION = _lib.SSLEAY_VERSION
26SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
27SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
28SSLEAY_DIR = _lib.SSLEAY_DIR
29SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080030
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050031SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
32RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080033
34SSLv2_METHOD = 1
35SSLv3_METHOD = 2
36SSLv23_METHOD = 3
37TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050038TLSv1_1_METHOD = 5
39TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080040
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050041OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
42OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
43OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050044
45OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
46OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080047
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050048MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080049
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050050OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
51OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
52OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
53OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
54OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
55OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
56OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
57OP_MSIE_SSLV2_RSA_PADDING = getattr(_lib, "SSL_OP_MSIE_SSLV2_RSA_PADDING", 0)
58OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
59OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
60OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
61OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
62OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
63OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
64OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
65OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
66OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
67OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG= _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
68OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080069
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050070OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
71OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
72OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080073
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050074OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080075
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050076VERIFY_PEER = _lib.SSL_VERIFY_PEER
77VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
78VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
79VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080080
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050081SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
82SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
83SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
84SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
85SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
86SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
87SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
88SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -080089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050090SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
91SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
92SSL_ST_MASK = _lib.SSL_ST_MASK
93SSL_ST_INIT = _lib.SSL_ST_INIT
94SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
95SSL_ST_OK = _lib.SSL_ST_OK
96SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098SSL_CB_LOOP = _lib.SSL_CB_LOOP
99SSL_CB_EXIT = _lib.SSL_CB_EXIT
100SSL_CB_READ = _lib.SSL_CB_READ
101SSL_CB_WRITE = _lib.SSL_CB_WRITE
102SSL_CB_ALERT = _lib.SSL_CB_ALERT
103SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
104SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
105SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
106SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
107SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
108SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
109SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
110SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800111
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800112
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500113class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500114 """
115 An error occurred in an `OpenSSL.SSL` API.
116 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500117
118
119
120_raise_current_error = partial(_exception_from_error_queue, Error)
121
122
123class WantReadError(Error):
124 pass
125
126
127
128class WantWriteError(Error):
129 pass
130
131
132
133class WantX509LookupError(Error):
134 pass
135
136
137
138class ZeroReturnError(Error):
139 pass
140
141
142
143class SysCallError(Error):
144 pass
145
146
147
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800148class _VerifyHelper(object):
149 def __init__(self, connection, callback):
150 self._problems = []
151
152 @wraps(callback)
153 def wrapper(ok, store_ctx):
154 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500155 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
156 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
157 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800158
159 try:
160 result = callback(connection, cert, error_number, error_depth, ok)
161 except Exception as e:
162 self._problems.append(e)
163 return 0
164 else:
165 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500166 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800167 return 1
168 else:
169 return 0
170
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500171 self.callback = _ffi.callback(
172 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800173
174
175 def raise_if_problem(self):
176 if self._problems:
177 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500178 _raise_current_error()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800179 except Error:
180 pass
181 raise self._problems.pop(0)
182
183
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800184
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800185def _asFileDescriptor(obj):
186 fd = None
187
188 if not isinstance(obj, int):
189 meth = getattr(obj, "fileno", None)
190 if meth is not None:
191 obj = meth()
192
193 if isinstance(obj, int):
194 fd = obj
195
196 if not isinstance(fd, int):
197 raise TypeError("argument must be an int, or have a fileno() method.")
198 elif fd < 0:
199 raise ValueError(
200 "file descriptor cannot be a negative integer (%i)" % (fd,))
201
202 return fd
203
204
205
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800206def SSLeay_version(type):
207 """
208 Return a string describing the version of OpenSSL in use.
209
210 :param type: One of the SSLEAY_ constants defined in this module.
211 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500212 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800213
214
215
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800216class Session(object):
217 pass
218
219
220
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800221class Context(object):
222 """
223 :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting up
224 new SSL connections.
225 """
226 _methods = {
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500227 SSLv3_METHOD: "SSLv3_method",
228 SSLv23_METHOD: "SSLv23_method",
229 TLSv1_METHOD: "TLSv1_method",
230 TLSv1_1_METHOD: "TLSv1_1_method",
231 TLSv1_2_METHOD: "TLSv1_2_method",
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800232 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500233 _methods = dict(
234 (identifier, getattr(_lib, name))
235 for (identifier, name) in _methods.items()
236 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800237
Jean-Paul Calderone63157872013-03-20 16:43:38 -0700238
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800239 def __init__(self, method):
240 """
241 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
242 TLSv1_METHOD.
243 """
244 if not isinstance(method, int):
245 raise TypeError("method must be an integer")
246
247 try:
248 method_func = self._methods[method]
249 except KeyError:
250 raise ValueError("No such protocol")
251
252 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500253 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500254 # TODO: This is untested.
255 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800256
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500257 context = _lib.SSL_CTX_new(method_obj)
258 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500259 # TODO: This is untested.
260 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500261 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800262
263 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800264 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800265 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800266 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800267 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800268 self._verify_callback = None
269 self._info_callback = None
270 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800271 self._app_data = None
272
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800273 # SSL_CTX_set_app_data(self->ctx, self);
274 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
275 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
276 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500277 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800278
279
280 def load_verify_locations(self, cafile, capath=None):
281 """
282 Let SSL know where we can find trusted certificates for the certificate
283 chain
284
285 :param cafile: In which file we can find the certificates
286 :param capath: In which directory we can find the certificates
287 :return: None
288 """
289 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500290 cafile = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800291 elif not isinstance(cafile, bytes):
292 raise TypeError("cafile must be None or a byte string")
293
294 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500295 capath = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800296 elif not isinstance(capath, bytes):
297 raise TypeError("capath must be None or a byte string")
298
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500299 load_result = _lib.SSL_CTX_load_verify_locations(self._context, cafile, capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800300 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500301 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800302
303
304 def _wrap_callback(self, callback):
305 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800306 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800307 return callback(size, verify, self._passphrase_userdata)
308 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800309 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800310
311
312 def set_passwd_cb(self, callback, userdata=None):
313 """
314 Set the passphrase callback
315
316 :param callback: The Python callback to use
317 :param userdata: (optional) A Python object which will be given as
318 argument to the callback
319 :return: None
320 """
321 if not callable(callback):
322 raise TypeError("callback must be callable")
323
324 self._passphrase_helper = self._wrap_callback(callback)
325 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500326 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800327 self._context, self._passphrase_callback)
328 self._passphrase_userdata = userdata
329
330
331 def set_default_verify_paths(self):
332 """
333 Use the platform-specific CA certificate locations
334
335 :return: None
336 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500337 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800338 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500339 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500340 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800341
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800342
343 def use_certificate_chain_file(self, certfile):
344 """
345 Load a certificate chain from a file
346
347 :param certfile: The name of the certificate chain file
348 :return: None
349 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800350 if not isinstance(certfile, bytes):
351 raise TypeError("certfile must be a byte string")
352
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500353 result = _lib.SSL_CTX_use_certificate_chain_file(self._context, certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800354 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500355 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800356
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800357
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800358 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800359 """
360 Load a certificate from a file
361
362 :param certfile: The name of the certificate file
363 :param filetype: (optional) The encoding of the file, default is PEM
364 :return: None
365 """
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800366 if not isinstance(certfile, bytes):
367 raise TypeError("certfile must be a byte string")
368 if not isinstance(filetype, int):
369 raise TypeError("filetype must be an integer")
370
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500371 use_result = _lib.SSL_CTX_use_certificate_file(self._context, certfile, filetype)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800372 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500373 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800374
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800375
376 def use_certificate(self, cert):
377 """
378 Load a certificate from a X509 object
379
380 :param cert: The X509 object
381 :return: None
382 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800383 if not isinstance(cert, X509):
384 raise TypeError("cert must be an X509 instance")
385
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500386 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800387 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500388 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800389
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800390
391 def add_extra_chain_cert(self, certobj):
392 """
393 Add certificate to chain
394
395 :param certobj: The X509 certificate object to add to the chain
396 :return: None
397 """
398 if not isinstance(certobj, X509):
399 raise TypeError("certobj must be an X509 instance")
400
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500401 copy = _lib.X509_dup(certobj._x509)
402 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800403 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500404 # TODO: This is untested.
405 _lib.X509_free(copy)
406 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800407
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800408
409 def _raise_passphrase_exception(self):
410 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500411 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800412 exception = self._passphrase_helper.raise_if_problem(Error)
413 if exception is not None:
414 raise exception
415
416
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800417 def use_privatekey_file(self, keyfile, filetype=_unspecified):
418 """
419 Load a private key from a file
420
421 :param keyfile: The name of the key file
422 :param filetype: (optional) The encoding of the file, default is PEM
423 :return: None
424 """
425 if not isinstance(keyfile, bytes):
426 raise TypeError("keyfile must be a byte string")
427
428 if filetype is _unspecified:
429 filetype = FILETYPE_PEM
430 elif not isinstance(filetype, int):
431 raise TypeError("filetype must be an integer")
432
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500433 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800434 self._context, keyfile, filetype)
435 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800436 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800437
438
439 def use_privatekey(self, pkey):
440 """
441 Load a private key from a PKey object
442
443 :param pkey: The PKey object
444 :return: None
445 """
446 if not isinstance(pkey, PKey):
447 raise TypeError("pkey must be a PKey instance")
448
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500449 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800450 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800451 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800452
453
454 def check_privatekey(self):
455 """
456 Check that the private key and certificate match up
457
458 :return: None (raises an exception if something's wrong)
459 """
460
461 def load_client_ca(self, cafile):
462 """
463 Load the trusted certificates that will be sent to the client (basically
464 telling the client "These are the guys I trust"). Does not actually
465 imply any of the certificates are trusted; that must be configured
466 separately.
467
468 :param cafile: The name of the certificates file
469 :return: None
470 """
471
472 def set_session_id(self, buf):
473 """
474 Set the session identifier. This is needed if you want to do session
475 resumption.
476
477 :param buf: A Python object that can be safely converted to a string
478 :returns: None
479 """
480
481 def set_session_cache_mode(self, mode):
482 """
483 Enable/disable session caching and specify the mode used.
484
485 :param mode: One or more of the SESS_CACHE_* flags (combine using
486 bitwise or)
487 :returns: The previously set caching mode.
488 """
489 if not isinstance(mode, int):
490 raise TypeError("mode must be an integer")
491
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500492 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800493
494
495 def get_session_cache_mode(self):
496 """
497 :returns: The currently used cache mode.
498 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500499 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800500
501
502 def set_verify(self, mode, callback):
503 """
504 Set the verify mode and verify callback
505
506 :param mode: The verify mode, this is either VERIFY_NONE or
507 VERIFY_PEER combined with possible other flags
508 :param callback: The Python callback to use
509 :return: None
510
511 See SSL_CTX_set_verify(3SSL) for further details.
512 """
513 if not isinstance(mode, int):
514 raise TypeError("mode must be an integer")
515
516 if not callable(callback):
517 raise TypeError("callback must be callable")
518
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800519 self._verify_helper = _VerifyHelper(self, callback)
520 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500521 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800522
523
524 def set_verify_depth(self, depth):
525 """
526 Set the verify depth
527
528 :param depth: An integer specifying the verify depth
529 :return: None
530 """
531 if not isinstance(depth, int):
532 raise TypeError("depth must be an integer")
533
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500534 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800535
536
537 def get_verify_mode(self):
538 """
539 Get the verify mode
540
541 :return: The verify mode
542 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500543 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800544
545
546 def get_verify_depth(self):
547 """
548 Get the verify depth
549
550 :return: The verify depth
551 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500552 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800553
554
555 def load_tmp_dh(self, dhfile):
556 """
557 Load parameters for Ephemeral Diffie-Hellman
558
559 :param dhfile: The file to load EDH parameters from
560 :return: None
561 """
562 if not isinstance(dhfile, bytes):
563 raise TypeError("dhfile must be a byte string")
564
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500565 bio = _lib.BIO_new_file(dhfile, "r")
566 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500567 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500568 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800569
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500570 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
571 dh = _ffi.gc(dh, _lib.DH_free)
572 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800573
574
575 def set_cipher_list(self, cipher_list):
576 """
577 Change the cipher list
578
579 :param cipher_list: A cipher list, see ciphers(1)
580 :return: None
581 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800582 if not isinstance(cipher_list, bytes):
583 raise TypeError("cipher_list must be a byte string")
584
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500585 result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800586 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500587 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800588
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800589
590 def set_client_ca_list(self, certificate_authorities):
591 """
592 Set the list of preferred client certificate signers for this server context.
593
594 This list of certificate authorities will be sent to the client when the
595 server requests a client certificate.
596
597 :param certificate_authorities: a sequence of X509Names.
598 :return: None
599 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500600 name_stack = _lib.sk_X509_NAME_new_null()
601 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500602 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500603 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800604
605 try:
606 for ca_name in certificate_authorities:
607 if not isinstance(ca_name, X509Name):
608 raise TypeError(
609 "client CAs must be X509Name objects, not %s objects" % (
610 type(ca_name).__name__,))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500611 copy = _lib.X509_NAME_dup(ca_name._name)
612 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500613 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500614 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500615 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800616 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500617 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500618 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800619 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500620 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800621 raise
622
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500623 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800624
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800625
626 def add_client_ca(self, certificate_authority):
627 """
628 Add the CA certificate to the list of preferred signers for this context.
629
630 The list of certificate authorities will be sent to the client when the
631 server requests a client certificate.
632
633 :param certificate_authority: certificate authority's X509 certificate.
634 :return: None
635 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800636 if not isinstance(certificate_authority, X509):
637 raise TypeError("certificate_authority must be an X509 instance")
638
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500639 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800640 self._context, certificate_authority._x509)
641 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500642 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500643 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800644
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645
646 def set_timeout(self, timeout):
647 """
648 Set session timeout
649
650 :param timeout: The timeout in seconds
651 :return: The previous session timeout
652 """
653 if not isinstance(timeout, int):
654 raise TypeError("timeout must be an integer")
655
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500656 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657
658
659 def get_timeout(self):
660 """
661 Get the session timeout
662
663 :return: The session timeout
664 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500665 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666
667
668 def set_info_callback(self, callback):
669 """
670 Set the info callback
671
672 :param callback: The Python callback to use
673 :return: None
674 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800675 @wraps(callback)
676 def wrapper(ssl, where, return_code):
677 callback(self, where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500678 self._info_callback = _ffi.callback(
679 "void (*)(const SSL *, int, int)", wrapper)
680 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800681
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682
683 def get_app_data(self):
684 """
685 Get the application data (supplied via set_app_data())
686
687 :return: The application data
688 """
689 return self._app_data
690
691
692 def set_app_data(self, data):
693 """
694 Set the application data (will be returned from get_app_data())
695
696 :param data: Any Python object
697 :return: None
698 """
699 self._app_data = data
700
701
702 def get_cert_store(self):
703 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500704 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500706 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500708 store = _lib.SSL_CTX_get_cert_store(self._context)
709 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500710 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800711 return None
712
713 pystore = X509Store.__new__(X509Store)
714 pystore._store = store
715 return pystore
716
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800717
718 def set_options(self, options):
719 """
720 Add options. Options set before are not cleared!
721
722 :param options: The options to add.
723 :return: The new option bitmask.
724 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800725 if not isinstance(options, int):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800726 raise TypeError("options must be an integer")
727
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500728 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729
730
731 def set_mode(self, mode):
732 """
733 Add modes via bitmask. Modes set before are not cleared!
734
735 :param mode: The mode to add.
736 :return: The new mode bitmask.
737 """
738 if not isinstance(mode, int):
739 raise TypeError("mode must be an integer")
740
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500741 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800742
743
744 def set_tlsext_servername_callback(self, callback):
745 """
746 Specify a callback function to be called when clients specify a server name.
747
748 :param callback: The callback function. It will be invoked with one
749 argument, the Connection instance.
750 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800751 @wraps(callback)
752 def wrapper(ssl, alert, arg):
753 callback(Connection._reverse_mapping[ssl])
754 return 0
755
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500756 self._tlsext_servername_callback = _ffi.callback(
757 "int (*)(const SSL *, int *, void *)", wrapper)
758 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800759 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800760
761ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800762
763
764
765class Connection(object):
766 """
767 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800768 _reverse_mapping = WeakValueDictionary()
769
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800770 def __init__(self, context, socket=None):
771 """
772 Create a new Connection object, using the given OpenSSL.SSL.Context
773 instance and socket.
774
775 :param context: An SSL Context to use for this connection
776 :param socket: The socket to use for transport layer
777 """
778 if not isinstance(context, Context):
779 raise TypeError("context must be a Context instance")
780
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500781 ssl = _lib.SSL_new(context._context)
782 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800783 self._context = context
784
785 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800786
787 if socket is None:
788 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -0800789 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500790 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
791 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800792
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500793 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500794 # TODO: This is untested.
795 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800796
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500797 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800798 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800799 self._into_ssl = None
800 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800801 self._socket = socket
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500802 set_result = _lib.SSL_set_fd(self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800803 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500804 # TODO: This is untested.
805 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800806
807
808 def __getattr__(self, name):
809 """
810 Look up attributes on the wrapped socket object if they are not found on
811 the Connection object.
812 """
813 return getattr(self._socket, name)
814
815
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800816 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800817 if self._context._verify_helper is not None:
818 self._context._verify_helper.raise_if_problem()
819
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500820 error = _lib.SSL_get_error(ssl, result)
821 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800822 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500823 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700824 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500825 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800826 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500827 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500828 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700829 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500830 elif error == _lib.SSL_ERROR_SYSCALL:
831 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800832 if result < 0:
833 raise SysCallError(
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500834 _ffi.errno, errorcode[_ffi.errno])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800835 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700836 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800837 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500838 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500839 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500840 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700841 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800842 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500843 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800844
845
846 def get_context(self):
847 """
848 Get session context
849 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800850 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800851
852
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800853 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800854 """
855 Switch this connection to a new session context
856
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800857 :param context: A :py:class:`Context` instance giving the new session
858 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800859 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800860 if not isinstance(context, Context):
861 raise TypeError("context must be a Context instance")
862
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500863 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800864 self._context = context
865
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800866
867 def get_servername(self):
868 """
869 Retrieve the servername extension value if provided in the client hello
870 message, or None if there wasn't one.
871
872 :return: A byte string giving the server name or :py:data:`None`.
873 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500874 name = _lib.SSL_get_servername(self._ssl, _lib.TLSEXT_NAMETYPE_host_name)
875 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800876 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800877
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500878 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800879
880
881 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800882 """
883 Set the value of the servername extension to send in the client hello.
884
885 :param name: A byte string giving the name.
886 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800887 if not isinstance(name, bytes):
888 raise TypeError("name must be a byte string")
889 elif "\0" in name:
890 raise TypeError("name must not contain NUL byte")
891
892 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500893 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800894
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800895
896 def pending(self):
897 """
898 Get the number of bytes that can be safely read from the connection
899
900 :return: The number of bytes available in the receive buffer.
901 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500902 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800903
904
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800905 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800906 """
907 Send data on the connection. NOTE: If you get one of the WantRead,
908 WantWrite or WantX509Lookup exceptions on this, you have to call the
909 method again with the SAME buffer.
910
911 :param buf: The string to send
912 :param flags: (optional) Included for compatibility with the socket
913 API, the value is ignored
914 :return: The number of bytes written
915 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500916 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800917 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800918 if not isinstance(buf, bytes):
919 raise TypeError("data must be a byte string")
920 if not isinstance(flags, int):
921 raise TypeError("flags must be an integer")
922
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500923 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800924 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800925 return result
926 write = send
927
928
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800929 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800930 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800931 Send "all" data on the connection. This calls send() repeatedly until
932 all data is sent. If an error occurs, it's impossible to tell how much
933 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800934
935 :param buf: The string to send
936 :param flags: (optional) Included for compatibility with the socket
937 API, the value is ignored
938 :return: The number of bytes written
939 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500940 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800941 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800942 if not isinstance(buf, bytes):
943 raise TypeError("buf must be a byte string")
944 if not isinstance(flags, int):
945 raise TypeError("flags must be an integer")
946
947 left_to_send = len(buf)
948 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500949 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800950
951 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500952 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800953 self._raise_ssl_error(self._ssl, result)
954 total_sent += result
955 left_to_send -= result
956
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800957
958 def recv(self, bufsiz, flags=None):
959 """
960 Receive data on the connection. NOTE: If you get one of the WantRead,
961 WantWrite or WantX509Lookup exceptions on this, you have to call the
962 method again with the SAME buffer.
963
964 :param bufsiz: The maximum number of bytes to read
965 :param flags: (optional) Included for compatibility with the socket
966 API, the value is ignored
967 :return: The string read from the Connection
968 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500969 buf = _ffi.new("char[]", bufsiz)
970 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800971 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500972 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800973 read = recv
974
975
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800976 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500977 if _lib.BIO_should_retry(bio):
978 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800979 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500980 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500981 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700982 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500983 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500984 # TODO: This is untested. I think io_special means the socket
985 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700986 raise ValueError("BIO_should_io_special")
987 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500988 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700989 raise ValueError("unknown bio failure")
990 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500991 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500992 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800993
994
995 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800996 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800997 When using non-socket connections this function reads the "dirty" data
998 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800999
1000 :param bufsiz: The maximum number of bytes to read
1001 :return: The string read.
1002 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001003 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001004 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001005
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001006 if not isinstance(bufsiz, int):
1007 raise TypeError("bufsiz must be an integer")
1008
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001009 buf = _ffi.new("char[]", bufsiz)
1010 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001011 if result <= 0:
1012 self._handle_bio_errors(self._from_ssl, result)
1013
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001014 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001015
1016
1017 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001018 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001019 When using non-socket connections this function sends "dirty" data that
1020 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001021
1022 :param buf: The string to put into the memory BIO.
1023 :return: The number of bytes written
1024 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001025 if self._into_ssl is None:
1026 raise TypeError("Connection sock was not None")
1027
1028 if not isinstance(buf, bytes):
1029 raise TypeError("buf must be a byte string")
1030
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001031 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001032 if result <= 0:
1033 self._handle_bio_errors(self._into_ssl, result)
1034 return result
1035
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001036
1037 def renegotiate(self):
1038 """
1039 Renegotiate the session
1040
1041 :return: True if the renegotiation can be started, false otherwise
1042 """
1043
1044 def do_handshake(self):
1045 """
1046 Perform an SSL handshake (usually called after renegotiate() or one of
1047 set_*_state()). This can raise the same exceptions as send and recv.
1048
1049 :return: None.
1050 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001051 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001052 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001053
1054
1055 def renegotiate_pending(self):
1056 """
1057 Check if there's a renegotiation in progress, it will return false once
1058 a renegotiation is finished.
1059
1060 :return: Whether there's a renegotiation in progress
1061 """
1062
1063 def total_renegotiations(self):
1064 """
1065 Find out the total number of renegotiations.
1066
1067 :return: The number of renegotiations.
1068 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001069 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001070
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001071
1072 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001073 """
1074 Connect to remote host and set up client-side SSL
1075
1076 :param addr: A remote address
1077 :return: What the socket's connect method returns
1078 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001080 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001081
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001082
1083 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001084 """
1085 Connect to remote host and set up client-side SSL. Note that if the socket's
1086 connect_ex method doesn't return 0, SSL won't be initialized.
1087
1088 :param addr: A remove address
1089 :return: What the socket's connect_ex method returns
1090 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001091 connect_ex = self._socket.connect_ex
1092 self.set_connect_state()
1093 return connect_ex(addr)
1094
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001095
1096 def accept(self):
1097 """
1098 Accept incoming connection and set up SSL on it
1099
1100 :return: A (conn,addr) pair where conn is a Connection and addr is an
1101 address
1102 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001103 client, addr = self._socket.accept()
1104 conn = Connection(self._context, client)
1105 conn.set_accept_state()
1106 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001107
1108
1109 def bio_shutdown(self):
1110 """
1111 When using non-socket connections this function signals end of
1112 data on the input for this connection.
1113
1114 :return: None
1115 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001116 if self._from_ssl is None:
1117 raise TypeError("Connection sock was not None")
1118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001119 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001120
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001121
1122 def shutdown(self):
1123 """
1124 Send closure alert
1125
1126 :return: True if the shutdown completed successfully (i.e. both sides
1127 have sent closure alerts), false otherwise (i.e. you have to
1128 wait for a ZeroReturnError on a recv() method call
1129 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001130 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131 if result < 0:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001132 # TODO: This is untested.
1133 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001134 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001135 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001136 else:
1137 return False
1138
1139
1140 def get_cipher_list(self):
1141 """
1142 Get the session cipher list
1143
1144 :return: A list of cipher strings
1145 """
1146 ciphers = []
1147 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 result = _lib.SSL_get_cipher_list(self._ssl, i)
1149 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001150 break
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001151 ciphers.append(_ffi.string(result))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001152 return ciphers
1153
1154
1155 def get_client_ca_list(self):
1156 """
1157 Get CAs whose certificates are suggested for client authentication.
1158
1159 :return: If this is a server connection, a list of X509Names representing
1160 the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1161 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,
1162 the list of such X509Names sent by the server, or an empty list if that
1163 has not yet happened.
1164 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1166 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001167 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001168 return []
1169
1170 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1172 name = _lib.sk_X509_NAME_value(ca_names, i)
1173 copy = _lib.X509_NAME_dup(name)
1174 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001175 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001176 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001177
1178 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001180 result.append(pyname)
1181 return result
1182
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001183
1184 def makefile(self):
1185 """
1186 The makefile() method is not implemented, since there is no dup semantics
1187 for SSL connections
1188
1189 :raise NotImplementedError
1190 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191 raise NotImplementedError("Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001192
1193
1194 def get_app_data(self):
1195 """
1196 Get application data
1197
1198 :return: The application data
1199 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001200 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001201
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001202
1203 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001204 """
1205 Set application data
1206
1207 :param data - The application data
1208 :return: None
1209 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001210 self._app_data = data
1211
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001212
1213 def get_shutdown(self):
1214 """
1215 Get shutdown state
1216
1217 :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1218 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001219 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001220
1221
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001222 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001223 """
1224 Set shutdown state
1225
1226 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1227 :return: None
1228 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001229 if not isinstance(state, int):
1230 raise TypeError("state must be an integer")
1231
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001232 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001233
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001234
1235 def state_string(self):
1236 """
1237 Get a verbose state description
1238
1239 :return: A string representing the state
1240 """
1241
1242 def server_random(self):
1243 """
1244 Get a copy of the server hello nonce.
1245
1246 :return: A string representing the state
1247 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001248 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001249 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001250 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001251 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001252 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001253
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001254
1255 def client_random(self):
1256 """
1257 Get a copy of the client hello nonce.
1258
1259 :return: A string representing the state
1260 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001261 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001262 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001263 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001264 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001265 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001266
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001267
1268 def master_key(self):
1269 """
1270 Get a copy of the master key.
1271
1272 :return: A string representing the state
1273 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001274 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001275 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001276 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001277 self._ssl.session.master_key,
1278 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001279
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001280
1281 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001282 """
1283 See shutdown(2)
1284
1285 :return: What the socket's shutdown() method returns
1286 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001287 return self._socket.shutdown(*args, **kwargs)
1288
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001289
1290 def get_peer_certificate(self):
1291 """
1292 Retrieve the other side's certificate (if any)
1293
1294 :return: The peer's certificate
1295 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001296 cert = _lib.SSL_get_peer_certificate(self._ssl)
1297 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001298 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001299 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001300 return pycert
1301 return None
1302
1303
1304 def get_peer_cert_chain(self):
1305 """
1306 Retrieve the other side's certificate (if any)
1307
1308 :return: A list of X509 instances giving the peer's certificate chain,
1309 or None if it does not have one.
1310 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001311 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1312 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001313 return None
1314
1315 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001316 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001317 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001319 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001321 result.append(pycert)
1322 return result
1323
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001324
1325 def want_read(self):
1326 """
1327 Checks if more data has to be read from the transport layer to complete an
1328 operation.
1329
1330 :return: True iff more data has to be read
1331 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001332 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001333
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001334
1335 def want_write(self):
1336 """
1337 Checks if there is data to write to the transport layer to complete an
1338 operation.
1339
1340 :return: True iff there is data to write
1341 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001342 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001343
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001344
1345 def set_accept_state(self):
1346 """
1347 Set the connection to work in server mode. The handshake will be handled
1348 automatically by read/write.
1349
1350 :return: None
1351 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001352 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001353
1354
1355 def set_connect_state(self):
1356 """
1357 Set the connection to work in client mode. The handshake will be handled
1358 automatically by read/write.
1359
1360 :return: None
1361 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001362 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001363
1364
1365 def get_session(self):
1366 """
1367 Returns the Session currently used.
1368
1369 @return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if
1370 no session exists.
1371 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001372 session = _lib.SSL_get1_session(self._ssl)
1373 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001374 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001375
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001376 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001377 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001378 return pysession
1379
1380
1381 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001382 """
1383 Set the session to be used when the TLS/SSL connection is established.
1384
1385 :param session: A Session instance representing the session to use.
1386 :returns: None
1387 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001388 if not isinstance(session, Session):
1389 raise TypeError("session must be a Session instance")
1390
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001391 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001392 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001393 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001394
1395ConnectionType = Connection