blob: 805693b0b44d1af0fa63c423e2b8b64d426da911 [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 Calderone0d7e8a12014-01-08 16:54:13 -050048try:
49 MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
50except AttributeError:
51 pass
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080052
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050053OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
54OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
55OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
56OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
57OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
58OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
59OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050060try:
61 OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
62except AttributeError:
63 pass
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050064OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
65OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
66OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
67OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
68OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
69OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
70OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
71OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
72OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
73OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG= _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
Jean-Paul Calderonec1780342014-01-08 16:59:03 -050074try:
75 OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
76except AttributeError:
77 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080078
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050079OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
80OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
81OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080082
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050083OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080084
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050085VERIFY_PEER = _lib.SSL_VERIFY_PEER
86VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
87VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
88VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050090SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
91SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
92SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
93SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
94SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
95SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
96SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
97SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -080098
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050099SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
100SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
101SSL_ST_MASK = _lib.SSL_ST_MASK
102SSL_ST_INIT = _lib.SSL_ST_INIT
103SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
104SSL_ST_OK = _lib.SSL_ST_OK
105SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500107SSL_CB_LOOP = _lib.SSL_CB_LOOP
108SSL_CB_EXIT = _lib.SSL_CB_EXIT
109SSL_CB_READ = _lib.SSL_CB_READ
110SSL_CB_WRITE = _lib.SSL_CB_WRITE
111SSL_CB_ALERT = _lib.SSL_CB_ALERT
112SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
113SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
114SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
115SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
116SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
117SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
118SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
119SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800120
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800121
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500122class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500123 """
124 An error occurred in an `OpenSSL.SSL` API.
125 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500126
127
128
129_raise_current_error = partial(_exception_from_error_queue, Error)
130
131
132class WantReadError(Error):
133 pass
134
135
136
137class WantWriteError(Error):
138 pass
139
140
141
142class WantX509LookupError(Error):
143 pass
144
145
146
147class ZeroReturnError(Error):
148 pass
149
150
151
152class SysCallError(Error):
153 pass
154
155
156
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800157class _VerifyHelper(object):
158 def __init__(self, connection, callback):
159 self._problems = []
160
161 @wraps(callback)
162 def wrapper(ok, store_ctx):
163 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
165 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
166 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800167
168 try:
169 result = callback(connection, cert, error_number, error_depth, ok)
170 except Exception as e:
171 self._problems.append(e)
172 return 0
173 else:
174 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500175 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800176 return 1
177 else:
178 return 0
179
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180 self.callback = _ffi.callback(
181 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800182
183
184 def raise_if_problem(self):
185 if self._problems:
186 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500187 _raise_current_error()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800188 except Error:
189 pass
190 raise self._problems.pop(0)
191
192
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800193
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800194def _asFileDescriptor(obj):
195 fd = None
196
197 if not isinstance(obj, int):
198 meth = getattr(obj, "fileno", None)
199 if meth is not None:
200 obj = meth()
201
202 if isinstance(obj, int):
203 fd = obj
204
205 if not isinstance(fd, int):
206 raise TypeError("argument must be an int, or have a fileno() method.")
207 elif fd < 0:
208 raise ValueError(
209 "file descriptor cannot be a negative integer (%i)" % (fd,))
210
211 return fd
212
213
214
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800215def SSLeay_version(type):
216 """
217 Return a string describing the version of OpenSSL in use.
218
219 :param type: One of the SSLEAY_ constants defined in this module.
220 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500221 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800222
223
224
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800225class Session(object):
226 pass
227
228
229
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800230class Context(object):
231 """
232 :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting up
233 new SSL connections.
234 """
235 _methods = {
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500236 SSLv3_METHOD: "SSLv3_method",
237 SSLv23_METHOD: "SSLv23_method",
238 TLSv1_METHOD: "TLSv1_method",
239 TLSv1_1_METHOD: "TLSv1_1_method",
240 TLSv1_2_METHOD: "TLSv1_2_method",
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800241 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500242 _methods = dict(
243 (identifier, getattr(_lib, name))
244 for (identifier, name) in _methods.items()
245 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800246
Jean-Paul Calderone63157872013-03-20 16:43:38 -0700247
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800248 def __init__(self, method):
249 """
250 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
251 TLSv1_METHOD.
252 """
253 if not isinstance(method, int):
254 raise TypeError("method must be an integer")
255
256 try:
257 method_func = self._methods[method]
258 except KeyError:
259 raise ValueError("No such protocol")
260
261 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500262 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500263 # TODO: This is untested.
264 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800265
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500266 context = _lib.SSL_CTX_new(method_obj)
267 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500268 # TODO: This is untested.
269 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500270 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800271
272 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800273 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800274 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800275 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800276 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800277 self._verify_callback = None
278 self._info_callback = None
279 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800280 self._app_data = None
281
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800282 # SSL_CTX_set_app_data(self->ctx, self);
283 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
284 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
285 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500286 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800287
288
289 def load_verify_locations(self, cafile, capath=None):
290 """
291 Let SSL know where we can find trusted certificates for the certificate
292 chain
293
294 :param cafile: In which file we can find the certificates
295 :param capath: In which directory we can find the certificates
296 :return: None
297 """
298 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500299 cafile = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800300 elif not isinstance(cafile, bytes):
301 raise TypeError("cafile must be None or a byte string")
302
303 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500304 capath = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800305 elif not isinstance(capath, bytes):
306 raise TypeError("capath must be None or a byte string")
307
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500308 load_result = _lib.SSL_CTX_load_verify_locations(self._context, cafile, capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800309 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500310 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800311
312
313 def _wrap_callback(self, callback):
314 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800315 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800316 return callback(size, verify, self._passphrase_userdata)
317 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800318 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800319
320
321 def set_passwd_cb(self, callback, userdata=None):
322 """
323 Set the passphrase callback
324
325 :param callback: The Python callback to use
326 :param userdata: (optional) A Python object which will be given as
327 argument to the callback
328 :return: None
329 """
330 if not callable(callback):
331 raise TypeError("callback must be callable")
332
333 self._passphrase_helper = self._wrap_callback(callback)
334 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500335 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800336 self._context, self._passphrase_callback)
337 self._passphrase_userdata = userdata
338
339
340 def set_default_verify_paths(self):
341 """
342 Use the platform-specific CA certificate locations
343
344 :return: None
345 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500346 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800347 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500348 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500349 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800350
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800351
352 def use_certificate_chain_file(self, certfile):
353 """
354 Load a certificate chain from a file
355
356 :param certfile: The name of the certificate chain file
357 :return: None
358 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800359 if not isinstance(certfile, bytes):
360 raise TypeError("certfile must be a byte string")
361
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500362 result = _lib.SSL_CTX_use_certificate_chain_file(self._context, certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800363 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500364 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800365
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800366
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800367 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800368 """
369 Load a certificate from a file
370
371 :param certfile: The name of the certificate file
372 :param filetype: (optional) The encoding of the file, default is PEM
373 :return: None
374 """
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800375 if not isinstance(certfile, bytes):
376 raise TypeError("certfile must be a byte string")
377 if not isinstance(filetype, int):
378 raise TypeError("filetype must be an integer")
379
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500380 use_result = _lib.SSL_CTX_use_certificate_file(self._context, certfile, filetype)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800381 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500382 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800383
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800384
385 def use_certificate(self, cert):
386 """
387 Load a certificate from a X509 object
388
389 :param cert: The X509 object
390 :return: None
391 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800392 if not isinstance(cert, X509):
393 raise TypeError("cert must be an X509 instance")
394
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500395 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800396 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500397 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800398
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800399
400 def add_extra_chain_cert(self, certobj):
401 """
402 Add certificate to chain
403
404 :param certobj: The X509 certificate object to add to the chain
405 :return: None
406 """
407 if not isinstance(certobj, X509):
408 raise TypeError("certobj must be an X509 instance")
409
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500410 copy = _lib.X509_dup(certobj._x509)
411 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800412 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500413 # TODO: This is untested.
414 _lib.X509_free(copy)
415 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800416
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800417
418 def _raise_passphrase_exception(self):
419 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500420 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800421 exception = self._passphrase_helper.raise_if_problem(Error)
422 if exception is not None:
423 raise exception
424
425
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800426 def use_privatekey_file(self, keyfile, filetype=_unspecified):
427 """
428 Load a private key from a file
429
430 :param keyfile: The name of the key file
431 :param filetype: (optional) The encoding of the file, default is PEM
432 :return: None
433 """
434 if not isinstance(keyfile, bytes):
435 raise TypeError("keyfile must be a byte string")
436
437 if filetype is _unspecified:
438 filetype = FILETYPE_PEM
439 elif not isinstance(filetype, int):
440 raise TypeError("filetype must be an integer")
441
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500442 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800443 self._context, keyfile, filetype)
444 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800445 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800446
447
448 def use_privatekey(self, pkey):
449 """
450 Load a private key from a PKey object
451
452 :param pkey: The PKey object
453 :return: None
454 """
455 if not isinstance(pkey, PKey):
456 raise TypeError("pkey must be a PKey instance")
457
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500458 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800459 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800460 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800461
462
463 def check_privatekey(self):
464 """
465 Check that the private key and certificate match up
466
467 :return: None (raises an exception if something's wrong)
468 """
469
470 def load_client_ca(self, cafile):
471 """
472 Load the trusted certificates that will be sent to the client (basically
473 telling the client "These are the guys I trust"). Does not actually
474 imply any of the certificates are trusted; that must be configured
475 separately.
476
477 :param cafile: The name of the certificates file
478 :return: None
479 """
480
481 def set_session_id(self, buf):
482 """
483 Set the session identifier. This is needed if you want to do session
484 resumption.
485
486 :param buf: A Python object that can be safely converted to a string
487 :returns: None
488 """
489
490 def set_session_cache_mode(self, mode):
491 """
492 Enable/disable session caching and specify the mode used.
493
494 :param mode: One or more of the SESS_CACHE_* flags (combine using
495 bitwise or)
496 :returns: The previously set caching mode.
497 """
498 if not isinstance(mode, int):
499 raise TypeError("mode must be an integer")
500
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500501 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800502
503
504 def get_session_cache_mode(self):
505 """
506 :returns: The currently used cache mode.
507 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500508 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800509
510
511 def set_verify(self, mode, callback):
512 """
513 Set the verify mode and verify callback
514
515 :param mode: The verify mode, this is either VERIFY_NONE or
516 VERIFY_PEER combined with possible other flags
517 :param callback: The Python callback to use
518 :return: None
519
520 See SSL_CTX_set_verify(3SSL) for further details.
521 """
522 if not isinstance(mode, int):
523 raise TypeError("mode must be an integer")
524
525 if not callable(callback):
526 raise TypeError("callback must be callable")
527
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800528 self._verify_helper = _VerifyHelper(self, callback)
529 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500530 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800531
532
533 def set_verify_depth(self, depth):
534 """
535 Set the verify depth
536
537 :param depth: An integer specifying the verify depth
538 :return: None
539 """
540 if not isinstance(depth, int):
541 raise TypeError("depth must be an integer")
542
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500543 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800544
545
546 def get_verify_mode(self):
547 """
548 Get the verify mode
549
550 :return: The verify mode
551 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500552 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800553
554
555 def get_verify_depth(self):
556 """
557 Get the verify depth
558
559 :return: The verify depth
560 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500561 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800562
563
564 def load_tmp_dh(self, dhfile):
565 """
566 Load parameters for Ephemeral Diffie-Hellman
567
568 :param dhfile: The file to load EDH parameters from
569 :return: None
570 """
571 if not isinstance(dhfile, bytes):
572 raise TypeError("dhfile must be a byte string")
573
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500574 bio = _lib.BIO_new_file(dhfile, "r")
575 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500576 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500577 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800578
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500579 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
580 dh = _ffi.gc(dh, _lib.DH_free)
581 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800582
583
584 def set_cipher_list(self, cipher_list):
585 """
586 Change the cipher list
587
588 :param cipher_list: A cipher list, see ciphers(1)
589 :return: None
590 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800591 if not isinstance(cipher_list, bytes):
592 raise TypeError("cipher_list must be a byte string")
593
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500594 result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800595 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500596 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800597
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800598
599 def set_client_ca_list(self, certificate_authorities):
600 """
601 Set the list of preferred client certificate signers for this server context.
602
603 This list of certificate authorities will be sent to the client when the
604 server requests a client certificate.
605
606 :param certificate_authorities: a sequence of X509Names.
607 :return: None
608 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500609 name_stack = _lib.sk_X509_NAME_new_null()
610 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500611 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500612 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800613
614 try:
615 for ca_name in certificate_authorities:
616 if not isinstance(ca_name, X509Name):
617 raise TypeError(
618 "client CAs must be X509Name objects, not %s objects" % (
619 type(ca_name).__name__,))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500620 copy = _lib.X509_NAME_dup(ca_name._name)
621 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500622 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500623 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500624 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800625 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500626 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500627 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800628 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500629 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800630 raise
631
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800633
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800634
635 def add_client_ca(self, certificate_authority):
636 """
637 Add the CA certificate to the list of preferred signers for this context.
638
639 The list of certificate authorities will be sent to the client when the
640 server requests a client certificate.
641
642 :param certificate_authority: certificate authority's X509 certificate.
643 :return: None
644 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800645 if not isinstance(certificate_authority, X509):
646 raise TypeError("certificate_authority must be an X509 instance")
647
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500648 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800649 self._context, certificate_authority._x509)
650 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500651 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500652 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800653
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800654
655 def set_timeout(self, timeout):
656 """
657 Set session timeout
658
659 :param timeout: The timeout in seconds
660 :return: The previous session timeout
661 """
662 if not isinstance(timeout, int):
663 raise TypeError("timeout must be an integer")
664
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500665 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666
667
668 def get_timeout(self):
669 """
670 Get the session timeout
671
672 :return: The session timeout
673 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500674 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800675
676
677 def set_info_callback(self, callback):
678 """
679 Set the info callback
680
681 :param callback: The Python callback to use
682 :return: None
683 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800684 @wraps(callback)
685 def wrapper(ssl, where, return_code):
686 callback(self, where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500687 self._info_callback = _ffi.callback(
688 "void (*)(const SSL *, int, int)", wrapper)
689 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800690
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691
692 def get_app_data(self):
693 """
694 Get the application data (supplied via set_app_data())
695
696 :return: The application data
697 """
698 return self._app_data
699
700
701 def set_app_data(self, data):
702 """
703 Set the application data (will be returned from get_app_data())
704
705 :param data: Any Python object
706 :return: None
707 """
708 self._app_data = data
709
710
711 def get_cert_store(self):
712 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500713 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500715 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 store = _lib.SSL_CTX_get_cert_store(self._context)
718 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500719 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800720 return None
721
722 pystore = X509Store.__new__(X509Store)
723 pystore._store = store
724 return pystore
725
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800726
727 def set_options(self, options):
728 """
729 Add options. Options set before are not cleared!
730
731 :param options: The options to add.
732 :return: The new option bitmask.
733 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800734 if not isinstance(options, int):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 raise TypeError("options must be an integer")
736
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500737 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738
739
740 def set_mode(self, mode):
741 """
742 Add modes via bitmask. Modes set before are not cleared!
743
744 :param mode: The mode to add.
745 :return: The new mode bitmask.
746 """
747 if not isinstance(mode, int):
748 raise TypeError("mode must be an integer")
749
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500750 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800751
752
753 def set_tlsext_servername_callback(self, callback):
754 """
755 Specify a callback function to be called when clients specify a server name.
756
757 :param callback: The callback function. It will be invoked with one
758 argument, the Connection instance.
759 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800760 @wraps(callback)
761 def wrapper(ssl, alert, arg):
762 callback(Connection._reverse_mapping[ssl])
763 return 0
764
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500765 self._tlsext_servername_callback = _ffi.callback(
766 "int (*)(const SSL *, int *, void *)", wrapper)
767 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800768 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769
770ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800771
772
773
774class Connection(object):
775 """
776 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800777 _reverse_mapping = WeakValueDictionary()
778
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800779 def __init__(self, context, socket=None):
780 """
781 Create a new Connection object, using the given OpenSSL.SSL.Context
782 instance and socket.
783
784 :param context: An SSL Context to use for this connection
785 :param socket: The socket to use for transport layer
786 """
787 if not isinstance(context, Context):
788 raise TypeError("context must be a Context instance")
789
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500790 ssl = _lib.SSL_new(context._context)
791 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800792 self._context = context
793
794 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800795
796 if socket is None:
797 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -0800798 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500799 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
800 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800801
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500802 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500803 # TODO: This is untested.
804 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800805
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500806 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800807 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800808 self._into_ssl = None
809 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800810 self._socket = socket
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 set_result = _lib.SSL_set_fd(self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800812 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500813 # TODO: This is untested.
814 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800815
816
817 def __getattr__(self, name):
818 """
819 Look up attributes on the wrapped socket object if they are not found on
820 the Connection object.
821 """
822 return getattr(self._socket, name)
823
824
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800825 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800826 if self._context._verify_helper is not None:
827 self._context._verify_helper.raise_if_problem()
828
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500829 error = _lib.SSL_get_error(ssl, result)
830 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800831 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500832 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700833 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500834 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800835 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500836 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500837 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700838 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500839 elif error == _lib.SSL_ERROR_SYSCALL:
840 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800841 if result < 0:
842 raise SysCallError(
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500843 _ffi.errno, errorcode[_ffi.errno])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800844 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700845 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800846 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500847 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500848 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500849 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700850 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800851 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500852 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800853
854
855 def get_context(self):
856 """
857 Get session context
858 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800859 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800860
861
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800862 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800863 """
864 Switch this connection to a new session context
865
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800866 :param context: A :py:class:`Context` instance giving the new session
867 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800868 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800869 if not isinstance(context, Context):
870 raise TypeError("context must be a Context instance")
871
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800873 self._context = context
874
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800875
876 def get_servername(self):
877 """
878 Retrieve the servername extension value if provided in the client hello
879 message, or None if there wasn't one.
880
881 :return: A byte string giving the server name or :py:data:`None`.
882 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500883 name = _lib.SSL_get_servername(self._ssl, _lib.TLSEXT_NAMETYPE_host_name)
884 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800885 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800886
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500887 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800888
889
890 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800891 """
892 Set the value of the servername extension to send in the client hello.
893
894 :param name: A byte string giving the name.
895 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800896 if not isinstance(name, bytes):
897 raise TypeError("name must be a byte string")
898 elif "\0" in name:
899 raise TypeError("name must not contain NUL byte")
900
901 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500902 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800903
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800904
905 def pending(self):
906 """
907 Get the number of bytes that can be safely read from the connection
908
909 :return: The number of bytes available in the receive buffer.
910 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500911 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800912
913
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800914 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800915 """
916 Send data on the connection. NOTE: If you get one of the WantRead,
917 WantWrite or WantX509Lookup exceptions on this, you have to call the
918 method again with the SAME buffer.
919
920 :param buf: The string to send
921 :param flags: (optional) Included for compatibility with the socket
922 API, the value is ignored
923 :return: The number of bytes written
924 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500925 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800926 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800927 if not isinstance(buf, bytes):
928 raise TypeError("data must be a byte string")
929 if not isinstance(flags, int):
930 raise TypeError("flags must be an integer")
931
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500932 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800933 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800934 return result
935 write = send
936
937
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800938 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800939 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800940 Send "all" data on the connection. This calls send() repeatedly until
941 all data is sent. If an error occurs, it's impossible to tell how much
942 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800943
944 :param buf: The string to send
945 :param flags: (optional) Included for compatibility with the socket
946 API, the value is ignored
947 :return: The number of bytes written
948 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -0500949 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800950 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800951 if not isinstance(buf, bytes):
952 raise TypeError("buf must be a byte string")
953 if not isinstance(flags, int):
954 raise TypeError("flags must be an integer")
955
956 left_to_send = len(buf)
957 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500958 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800959
960 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800962 self._raise_ssl_error(self._ssl, result)
963 total_sent += result
964 left_to_send -= result
965
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800966
967 def recv(self, bufsiz, flags=None):
968 """
969 Receive data on the connection. NOTE: If you get one of the WantRead,
970 WantWrite or WantX509Lookup exceptions on this, you have to call the
971 method again with the SAME buffer.
972
973 :param bufsiz: The maximum number of bytes to read
974 :param flags: (optional) Included for compatibility with the socket
975 API, the value is ignored
976 :return: The string read from the Connection
977 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500978 buf = _ffi.new("char[]", bufsiz)
979 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800980 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500981 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800982 read = recv
983
984
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800985 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500986 if _lib.BIO_should_retry(bio):
987 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800988 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500989 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500990 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700991 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500992 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500993 # TODO: This is untested. I think io_special means the socket
994 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700995 raise ValueError("BIO_should_io_special")
996 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500997 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700998 raise ValueError("unknown bio failure")
999 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001000 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001001 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001002
1003
1004 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001005 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001006 When using non-socket connections this function reads the "dirty" data
1007 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001008
1009 :param bufsiz: The maximum number of bytes to read
1010 :return: The string read.
1011 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001012 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001013 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001014
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001015 if not isinstance(bufsiz, int):
1016 raise TypeError("bufsiz must be an integer")
1017
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001018 buf = _ffi.new("char[]", bufsiz)
1019 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001020 if result <= 0:
1021 self._handle_bio_errors(self._from_ssl, result)
1022
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001023 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001024
1025
1026 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001027 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001028 When using non-socket connections this function sends "dirty" data that
1029 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001030
1031 :param buf: The string to put into the memory BIO.
1032 :return: The number of bytes written
1033 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001034 if self._into_ssl is None:
1035 raise TypeError("Connection sock was not None")
1036
1037 if not isinstance(buf, bytes):
1038 raise TypeError("buf must be a byte string")
1039
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001040 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001041 if result <= 0:
1042 self._handle_bio_errors(self._into_ssl, result)
1043 return result
1044
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001045
1046 def renegotiate(self):
1047 """
1048 Renegotiate the session
1049
1050 :return: True if the renegotiation can be started, false otherwise
1051 """
1052
1053 def do_handshake(self):
1054 """
1055 Perform an SSL handshake (usually called after renegotiate() or one of
1056 set_*_state()). This can raise the same exceptions as send and recv.
1057
1058 :return: None.
1059 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001060 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001061 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001062
1063
1064 def renegotiate_pending(self):
1065 """
1066 Check if there's a renegotiation in progress, it will return false once
1067 a renegotiation is finished.
1068
1069 :return: Whether there's a renegotiation in progress
1070 """
1071
1072 def total_renegotiations(self):
1073 """
1074 Find out the total number of renegotiations.
1075
1076 :return: The number of renegotiations.
1077 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001078 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001079
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001080
1081 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001082 """
1083 Connect to remote host and set up client-side SSL
1084
1085 :param addr: A remote address
1086 :return: What the socket's connect method returns
1087 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001089 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001090
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001091
1092 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001093 """
1094 Connect to remote host and set up client-side SSL. Note that if the socket's
1095 connect_ex method doesn't return 0, SSL won't be initialized.
1096
1097 :param addr: A remove address
1098 :return: What the socket's connect_ex method returns
1099 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001100 connect_ex = self._socket.connect_ex
1101 self.set_connect_state()
1102 return connect_ex(addr)
1103
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001104
1105 def accept(self):
1106 """
1107 Accept incoming connection and set up SSL on it
1108
1109 :return: A (conn,addr) pair where conn is a Connection and addr is an
1110 address
1111 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001112 client, addr = self._socket.accept()
1113 conn = Connection(self._context, client)
1114 conn.set_accept_state()
1115 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001116
1117
1118 def bio_shutdown(self):
1119 """
1120 When using non-socket connections this function signals end of
1121 data on the input for this connection.
1122
1123 :return: None
1124 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001125 if self._from_ssl is None:
1126 raise TypeError("Connection sock was not None")
1127
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001128 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001129
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001130
1131 def shutdown(self):
1132 """
1133 Send closure alert
1134
1135 :return: True if the shutdown completed successfully (i.e. both sides
1136 have sent closure alerts), false otherwise (i.e. you have to
1137 wait for a ZeroReturnError on a recv() method call
1138 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001139 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001140 if result < 0:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001141 # TODO: This is untested.
1142 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001143 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001144 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001145 else:
1146 return False
1147
1148
1149 def get_cipher_list(self):
1150 """
1151 Get the session cipher list
1152
1153 :return: A list of cipher strings
1154 """
1155 ciphers = []
1156 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 result = _lib.SSL_get_cipher_list(self._ssl, i)
1158 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001159 break
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 ciphers.append(_ffi.string(result))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001161 return ciphers
1162
1163
1164 def get_client_ca_list(self):
1165 """
1166 Get CAs whose certificates are suggested for client authentication.
1167
1168 :return: If this is a server connection, a list of X509Names representing
1169 the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1170 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,
1171 the list of such X509Names sent by the server, or an empty list if that
1172 has not yet happened.
1173 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001174 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1175 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001176 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001177 return []
1178
1179 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001180 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1181 name = _lib.sk_X509_NAME_value(ca_names, i)
1182 copy = _lib.X509_NAME_dup(name)
1183 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001184 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001185 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001186
1187 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001188 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001189 result.append(pyname)
1190 return result
1191
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001192
1193 def makefile(self):
1194 """
1195 The makefile() method is not implemented, since there is no dup semantics
1196 for SSL connections
1197
1198 :raise NotImplementedError
1199 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001200 raise NotImplementedError("Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001201
1202
1203 def get_app_data(self):
1204 """
1205 Get application data
1206
1207 :return: The application data
1208 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001209 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001210
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001211
1212 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001213 """
1214 Set application data
1215
1216 :param data - The application data
1217 :return: None
1218 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001219 self._app_data = data
1220
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001221
1222 def get_shutdown(self):
1223 """
1224 Get shutdown state
1225
1226 :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1227 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001228 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001229
1230
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001231 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001232 """
1233 Set shutdown state
1234
1235 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1236 :return: None
1237 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001238 if not isinstance(state, int):
1239 raise TypeError("state must be an integer")
1240
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001241 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001242
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001243
1244 def state_string(self):
1245 """
1246 Get a verbose state description
1247
1248 :return: A string representing the state
1249 """
1250
1251 def server_random(self):
1252 """
1253 Get a copy of the server hello nonce.
1254
1255 :return: A string representing the state
1256 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001257 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001258 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001259 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001260 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001261 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001262
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001263
1264 def client_random(self):
1265 """
1266 Get a copy of the client hello nonce.
1267
1268 :return: A string representing the state
1269 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001270 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001271 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001272 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001273 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001274 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001275
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001276
1277 def master_key(self):
1278 """
1279 Get a copy of the master key.
1280
1281 :return: A string representing the state
1282 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001283 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001284 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001285 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001286 self._ssl.session.master_key,
1287 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001288
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001289
1290 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001291 """
1292 See shutdown(2)
1293
1294 :return: What the socket's shutdown() method returns
1295 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001296 return self._socket.shutdown(*args, **kwargs)
1297
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001298
1299 def get_peer_certificate(self):
1300 """
1301 Retrieve the other side's certificate (if any)
1302
1303 :return: The peer's certificate
1304 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001305 cert = _lib.SSL_get_peer_certificate(self._ssl)
1306 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001307 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001308 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001309 return pycert
1310 return None
1311
1312
1313 def get_peer_cert_chain(self):
1314 """
1315 Retrieve the other side's certificate (if any)
1316
1317 :return: A list of X509 instances giving the peer's certificate chain,
1318 or None if it does not have one.
1319 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1321 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001322 return None
1323
1324 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001325 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001326 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001327 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001328 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001329 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001330 result.append(pycert)
1331 return result
1332
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001333
1334 def want_read(self):
1335 """
1336 Checks if more data has to be read from the transport layer to complete an
1337 operation.
1338
1339 :return: True iff more data has to be read
1340 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001341 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001342
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001343
1344 def want_write(self):
1345 """
1346 Checks if there is data to write to the transport layer to complete an
1347 operation.
1348
1349 :return: True iff there is data to write
1350 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001352
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001353
1354 def set_accept_state(self):
1355 """
1356 Set the connection to work in server mode. The handshake will be handled
1357 automatically by read/write.
1358
1359 :return: None
1360 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001362
1363
1364 def set_connect_state(self):
1365 """
1366 Set the connection to work in client mode. The handshake will be handled
1367 automatically by read/write.
1368
1369 :return: None
1370 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001371 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001372
1373
1374 def get_session(self):
1375 """
1376 Returns the Session currently used.
1377
1378 @return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if
1379 no session exists.
1380 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001381 session = _lib.SSL_get1_session(self._ssl)
1382 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001383 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001384
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001386 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001387 return pysession
1388
1389
1390 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001391 """
1392 Set the session to be used when the TLS/SSL connection is established.
1393
1394 :param session: A Session instance representing the session to use.
1395 :returns: None
1396 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001397 if not isinstance(session, Session):
1398 raise TypeError("session must be a Session instance")
1399
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001400 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001401 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001402 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001403
1404ConnectionType = Connection