blob: 47015606c2dda1a1a69170717cf6b95788c0bf86 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010043/* Include symbols from _socket module */
44#include "socketmodule.h"
45
46static PySocketModule_APIObject PySocketModule;
47
48#if defined(HAVE_POLL_H)
49#include <poll.h>
50#elif defined(HAVE_SYS_POLL_H)
51#include <sys/poll.h>
52#endif
53
54/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
63
64/* SSL error object */
65static PyObject *PySSLErrorObject;
66static PyObject *PySSLZeroReturnErrorObject;
67static PyObject *PySSLWantReadErrorObject;
68static PyObject *PySSLWantWriteErrorObject;
69static PyObject *PySSLSyscallErrorObject;
70static PyObject *PySSLEOFErrorObject;
71
72/* Error mappings */
73static PyObject *err_codes_to_names;
74static PyObject *err_names_to_codes;
75static PyObject *lib_codes_to_names;
76
77struct py_ssl_error_code {
78 const char *mnemonic;
79 int library, reason;
80};
81struct py_ssl_library_code {
82 const char *library;
83 int code;
84};
85
86/* Include generated data (error codes) */
87#include "_ssl_data.h"
88
89/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
90 http://www.openssl.org/news/changelog.html
91 */
92#if OPENSSL_VERSION_NUMBER >= 0x10001000L
93# define HAVE_TLSv1_2 1
94#else
95# define HAVE_TLSv1_2 0
96#endif
97
Antoine Pitrouce852cb2013-03-30 16:45:04 +010098/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
Antoine Pitrou912fbff2013-03-30 16:29:32 +010099 * This includes the SSL_set_SSL_CTX() function.
100 */
101#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
102# define HAVE_SNI 1
103#else
104# define HAVE_SNI 0
105#endif
106
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000107enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000108 /* these mirror ssl.h */
109 PY_SSL_ERROR_NONE,
110 PY_SSL_ERROR_SSL,
111 PY_SSL_ERROR_WANT_READ,
112 PY_SSL_ERROR_WANT_WRITE,
113 PY_SSL_ERROR_WANT_X509_LOOKUP,
114 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
115 PY_SSL_ERROR_ZERO_RETURN,
116 PY_SSL_ERROR_WANT_CONNECT,
117 /* start of non ssl.h errorcodes */
118 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
119 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
120 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000121};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000122
Thomas Woutersed03b412007-08-28 21:37:11 +0000123enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000124 PY_SSL_CLIENT,
125 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000126};
127
128enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000129 PY_SSL_CERT_NONE,
130 PY_SSL_CERT_OPTIONAL,
131 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000132};
133
134enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +0200135#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000136 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200137#endif
138 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140#if HAVE_TLSv1_2
141 PY_SSL_VERSION_TLS1,
142 PY_SSL_VERSION_TLS1_1,
143 PY_SSL_VERSION_TLS1_2
144#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200148
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000149#ifdef WITH_THREAD
150
151/* serves as a flag to see whether we've initialized the SSL thread support. */
152/* 0 means no, greater than 0 means yes */
153
154static unsigned int _ssl_locks_count = 0;
155
156#endif /* def WITH_THREAD */
157
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158/* SSL socket object */
159
160#define X509_NAME_MAXLEN 256
161
162/* RAND_* APIs got added to OpenSSL in 0.9.5 */
163#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
164# define HAVE_OPENSSL_RAND 1
165#else
166# undef HAVE_OPENSSL_RAND
167#endif
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
182/* SSL_get_finished got added to OpenSSL in 0.9.5 */
183#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
184# define HAVE_OPENSSL_FINISHED 1
185#else
186# define HAVE_OPENSSL_FINISHED 0
187#endif
188
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100189/* ECDH support got added to OpenSSL in 0.9.8 */
190#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
191# define OPENSSL_NO_ECDH
192#endif
193
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100194/* compression support got added to OpenSSL in 0.9.8 */
195#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
196# define OPENSSL_NO_COMP
197#endif
198
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100199
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000200typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100203#ifdef OPENSSL_NPN_NEGOTIATED
204 char *npn_protocols;
205 int npn_protocols_len;
206#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100207#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200208 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100209#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000211
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212typedef struct {
213 PyObject_HEAD
214 PyObject *Socket; /* weakref to socket on which we're layered */
215 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100216 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000217 X509 *peer_cert;
218 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200219 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000221
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222static PyTypeObject PySSLContext_Type;
223static PyTypeObject PySSLSocket_Type;
224
225static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
226static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000227static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000228 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
230static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000231
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
233#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000235typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 SOCKET_IS_NONBLOCKING,
237 SOCKET_IS_BLOCKING,
238 SOCKET_HAS_TIMED_OUT,
239 SOCKET_HAS_BEEN_CLOSED,
240 SOCKET_TOO_LARGE_FOR_SELECT,
241 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242} timeout_state;
243
Thomas Woutersed03b412007-08-28 21:37:11 +0000244/* Wrap error strings with filename and line # */
245#define STRINGIFY1(x) #x
246#define STRINGIFY2(x) STRINGIFY1(x)
247#define ERRSTR1(x,y,z) (x ":" y ": " z)
248#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
249
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200250
251/*
252 * SSL errors.
253 */
254
255PyDoc_STRVAR(SSLError_doc,
256"An error occurred in the SSL implementation.");
257
258PyDoc_STRVAR(SSLZeroReturnError_doc,
259"SSL/TLS session closed cleanly.");
260
261PyDoc_STRVAR(SSLWantReadError_doc,
262"Non-blocking SSL socket needs to read more data\n"
263"before the requested operation can be completed.");
264
265PyDoc_STRVAR(SSLWantWriteError_doc,
266"Non-blocking SSL socket needs to write more data\n"
267"before the requested operation can be completed.");
268
269PyDoc_STRVAR(SSLSyscallError_doc,
270"System error when attempting SSL operation.");
271
272PyDoc_STRVAR(SSLEOFError_doc,
273"SSL/TLS connection terminated abruptly.");
274
275static PyObject *
276SSLError_str(PyOSErrorObject *self)
277{
278 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
279 Py_INCREF(self->strerror);
280 return self->strerror;
281 }
282 else
283 return PyObject_Str(self->args);
284}
285
286static PyType_Slot sslerror_type_slots[] = {
287 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
288 {Py_tp_doc, SSLError_doc},
289 {Py_tp_str, SSLError_str},
290 {0, 0},
291};
292
293static PyType_Spec sslerror_type_spec = {
294 "ssl.SSLError",
295 sizeof(PyOSErrorObject),
296 0,
297 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
298 sslerror_type_slots
299};
300
301static void
302fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
303 int lineno, unsigned long errcode)
304{
305 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
306 PyObject *init_value, *msg, *key;
307 _Py_IDENTIFIER(reason);
308 _Py_IDENTIFIER(library);
309
310 if (errcode != 0) {
311 int lib, reason;
312
313 lib = ERR_GET_LIB(errcode);
314 reason = ERR_GET_REASON(errcode);
315 key = Py_BuildValue("ii", lib, reason);
316 if (key == NULL)
317 goto fail;
318 reason_obj = PyDict_GetItem(err_codes_to_names, key);
319 Py_DECREF(key);
320 if (reason_obj == NULL) {
321 /* XXX if reason < 100, it might reflect a library number (!!) */
322 PyErr_Clear();
323 }
324 key = PyLong_FromLong(lib);
325 if (key == NULL)
326 goto fail;
327 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
328 Py_DECREF(key);
329 if (lib_obj == NULL) {
330 PyErr_Clear();
331 }
332 if (errstr == NULL)
333 errstr = ERR_reason_error_string(errcode);
334 }
335 if (errstr == NULL)
336 errstr = "unknown error";
337
338 if (reason_obj && lib_obj)
339 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
340 lib_obj, reason_obj, errstr, lineno);
341 else if (lib_obj)
342 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
343 lib_obj, errstr, lineno);
344 else
345 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
346
347 if (msg == NULL)
348 goto fail;
349 init_value = Py_BuildValue("iN", ssl_errno, msg);
350 err_value = PyObject_CallObject(type, init_value);
351 Py_DECREF(init_value);
352 if (err_value == NULL)
353 goto fail;
354 if (reason_obj == NULL)
355 reason_obj = Py_None;
356 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
357 goto fail;
358 if (lib_obj == NULL)
359 lib_obj = Py_None;
360 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
361 goto fail;
362 PyErr_SetObject(type, err_value);
363fail:
364 Py_XDECREF(err_value);
365}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000366
367static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000368PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200370 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200371 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 int err;
373 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200374 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 if (obj->ssl != NULL) {
380 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 switch (err) {
383 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200384 errstr = "TLS/SSL connection has been closed (EOF)";
385 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 p = PY_SSL_ERROR_ZERO_RETURN;
387 break;
388 case SSL_ERROR_WANT_READ:
389 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200390 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 p = PY_SSL_ERROR_WANT_READ;
392 break;
393 case SSL_ERROR_WANT_WRITE:
394 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 errstr = "The operation did not complete (write)";
397 break;
398 case SSL_ERROR_WANT_X509_LOOKUP:
399 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000400 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 break;
402 case SSL_ERROR_WANT_CONNECT:
403 p = PY_SSL_ERROR_WANT_CONNECT;
404 errstr = "The operation did not complete (connect)";
405 break;
406 case SSL_ERROR_SYSCALL:
407 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 if (e == 0) {
409 PySocketSockObject *s
410 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
411 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200413 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000414 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000416 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000417 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000418 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200419 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000420 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200421 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200424 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 }
427 } else {
428 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 }
430 break;
431 }
432 case SSL_ERROR_SSL:
433 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200435 if (e == 0)
436 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000437 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 break;
439 }
440 default:
441 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
442 errstr = "Invalid error code";
443 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000444 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200445 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000446 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448}
449
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450static PyObject *
451_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
452
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200453 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200455 else
456 errcode = 0;
457 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000458 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460}
461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462/*
463 * SSL objects
464 */
465
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100467newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000468 enum py_ssl_server_or_client socket_type,
469 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000470{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000471 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100472 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200473 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000474
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 if (self == NULL)
477 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 self->peer_cert = NULL;
480 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100482 self->ctx = sslctx;
483 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 /* Make sure the SSL error state is initialized */
486 (void) ERR_get_state();
487 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100492 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200494 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000495#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200496 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000497#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200498 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000499
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100500#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000501 if (server_hostname != NULL)
502 SSL_set_tlsext_host_name(self->ssl, server_hostname);
503#endif
504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 /* If the socket is in non-blocking mode or timeout mode, set the BIO
506 * to non-blocking mode (blocking is the default)
507 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000508 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
510 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
511 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 PySSL_BEGIN_ALLOW_THREADS
514 if (socket_type == PY_SSL_CLIENT)
515 SSL_set_connect_state(self->ssl);
516 else
517 SSL_set_accept_state(self->ssl);
518 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000519
Antoine Pitroud6494802011-07-21 01:11:30 +0200520 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000523}
524
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000525/* SSL object methods */
526
Antoine Pitrou152efa22010-05-16 18:19:27 +0000527static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 int ret;
530 int err;
531 int sockstate, nonblocking;
532 PySocketSockObject *sock
533 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 if (((PyObject*)sock) == Py_None) {
536 _setSSLError("Underlying socket connection gone",
537 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
538 return NULL;
539 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000540 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 /* just in case the blocking state of the socket has been changed */
543 nonblocking = (sock->sock_timeout >= 0.0);
544 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
545 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 /* Actually negotiate SSL connection */
548 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000550 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 ret = SSL_do_handshake(self->ssl);
552 err = SSL_get_error(self->ssl, ret);
553 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000554 if (PyErr_CheckSignals())
555 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 if (err == SSL_ERROR_WANT_READ) {
557 sockstate = check_socket_and_wait_for_timeout(sock, 0);
558 } else if (err == SSL_ERROR_WANT_WRITE) {
559 sockstate = check_socket_and_wait_for_timeout(sock, 1);
560 } else {
561 sockstate = SOCKET_OPERATION_OK;
562 }
563 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000564 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000565 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000566 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
568 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000569 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000570 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
572 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000573 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
576 break;
577 }
578 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 if (ret < 1)
581 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 if (self->peer_cert)
584 X509_free (self->peer_cert);
585 PySSL_BEGIN_ALLOW_THREADS
586 self->peer_cert = SSL_get_peer_certificate(self->ssl);
587 PySSL_END_ALLOW_THREADS
588
589 Py_INCREF(Py_None);
590 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591
592error:
593 Py_DECREF(sock);
594 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000595}
596
Thomas Woutersed03b412007-08-28 21:37:11 +0000597static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 char namebuf[X509_NAME_MAXLEN];
601 int buflen;
602 PyObject *name_obj;
603 PyObject *value_obj;
604 PyObject *attr;
605 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
608 if (buflen < 0) {
609 _setSSLError(NULL, 0, __FILE__, __LINE__);
610 goto fail;
611 }
612 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
613 if (name_obj == NULL)
614 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
617 if (buflen < 0) {
618 _setSSLError(NULL, 0, __FILE__, __LINE__);
619 Py_DECREF(name_obj);
620 goto fail;
621 }
622 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 OPENSSL_free(valuebuf);
625 if (value_obj == NULL) {
626 Py_DECREF(name_obj);
627 goto fail;
628 }
629 attr = PyTuple_New(2);
630 if (attr == NULL) {
631 Py_DECREF(name_obj);
632 Py_DECREF(value_obj);
633 goto fail;
634 }
635 PyTuple_SET_ITEM(attr, 0, name_obj);
636 PyTuple_SET_ITEM(attr, 1, value_obj);
637 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000638
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000641}
642
643static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000645{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
647 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
648 PyObject *rdnt;
649 PyObject *attr = NULL; /* tuple to hold an attribute */
650 int entry_count = X509_NAME_entry_count(xname);
651 X509_NAME_ENTRY *entry;
652 ASN1_OBJECT *name;
653 ASN1_STRING *value;
654 int index_counter;
655 int rdn_level = -1;
656 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 dn = PyList_New(0);
659 if (dn == NULL)
660 return NULL;
661 /* now create another tuple to hold the top-level RDN */
662 rdn = PyList_New(0);
663 if (rdn == NULL)
664 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 for (index_counter = 0;
667 index_counter < entry_count;
668 index_counter++)
669 {
670 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 /* check to see if we've gotten to a new RDN */
673 if (rdn_level >= 0) {
674 if (rdn_level != entry->set) {
675 /* yes, new RDN */
676 /* add old RDN to DN */
677 rdnt = PyList_AsTuple(rdn);
678 Py_DECREF(rdn);
679 if (rdnt == NULL)
680 goto fail0;
681 retcode = PyList_Append(dn, rdnt);
682 Py_DECREF(rdnt);
683 if (retcode < 0)
684 goto fail0;
685 /* create new RDN */
686 rdn = PyList_New(0);
687 if (rdn == NULL)
688 goto fail0;
689 }
690 }
691 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 /* now add this attribute to the current RDN */
694 name = X509_NAME_ENTRY_get_object(entry);
695 value = X509_NAME_ENTRY_get_data(entry);
696 attr = _create_tuple_for_attribute(name, value);
697 /*
698 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
699 entry->set,
700 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
701 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
702 */
703 if (attr == NULL)
704 goto fail1;
705 retcode = PyList_Append(rdn, attr);
706 Py_DECREF(attr);
707 if (retcode < 0)
708 goto fail1;
709 }
710 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100711 if (rdn != NULL) {
712 if (PyList_GET_SIZE(rdn) > 0) {
713 rdnt = PyList_AsTuple(rdn);
714 Py_DECREF(rdn);
715 if (rdnt == NULL)
716 goto fail0;
717 retcode = PyList_Append(dn, rdnt);
718 Py_DECREF(rdnt);
719 if (retcode < 0)
720 goto fail0;
721 }
722 else {
723 Py_DECREF(rdn);
724 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 /* convert list to tuple */
728 rdnt = PyList_AsTuple(dn);
729 Py_DECREF(dn);
730 if (rdnt == NULL)
731 return NULL;
732 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
734 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
737 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 Py_XDECREF(dn);
739 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740}
741
742static PyObject *
743_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* this code follows the procedure outlined in
746 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
747 function to extract the STACK_OF(GENERAL_NAME),
748 then iterates through the stack to add the
749 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 int i, j;
752 PyObject *peer_alt_names = Py_None;
753 PyObject *v, *t;
754 X509_EXTENSION *ext = NULL;
755 GENERAL_NAMES *names = NULL;
756 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000757 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 BIO *biobuf = NULL;
759 char buf[2048];
760 char *vptr;
761 int len;
762 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000763#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000765#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000767#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 if (certificate == NULL)
770 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 /* get a memory buffer */
773 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200775 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 while ((i = X509_get_ext_by_NID(
777 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (peer_alt_names == Py_None) {
780 peer_alt_names = PyList_New(0);
781 if (peer_alt_names == NULL)
782 goto fail;
783 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* now decode the altName */
786 ext = X509_get_ext(certificate, i);
787 if(!(method = X509V3_EXT_get(ext))) {
788 PyErr_SetString
789 (PySSLErrorObject,
790 ERRSTR("No method for internalizing subjectAltName!"));
791 goto fail;
792 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 p = ext->value->data;
795 if (method->it)
796 names = (GENERAL_NAMES*)
797 (ASN1_item_d2i(NULL,
798 &p,
799 ext->value->length,
800 ASN1_ITEM_ptr(method->it)));
801 else
802 names = (GENERAL_NAMES*)
803 (method->d2i(NULL,
804 &p,
805 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200809 int gntype;
810 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200813 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200814 switch (gntype) {
815 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 /* we special-case DirName as a tuple of
817 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 t = PyTuple_New(2);
820 if (t == NULL) {
821 goto fail;
822 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 v = PyUnicode_FromString("DirName");
825 if (v == NULL) {
826 Py_DECREF(t);
827 goto fail;
828 }
829 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 v = _create_tuple_for_X509_NAME (name->d.dirn);
832 if (v == NULL) {
833 Py_DECREF(t);
834 goto fail;
835 }
836 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200837 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000838
Christian Heimes824f7f32013-08-17 00:54:47 +0200839 case GEN_EMAIL:
840 case GEN_DNS:
841 case GEN_URI:
842 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
843 correctly, CVE-2013-4238 */
844 t = PyTuple_New(2);
845 if (t == NULL)
846 goto fail;
847 switch (gntype) {
848 case GEN_EMAIL:
849 v = PyUnicode_FromString("email");
850 as = name->d.rfc822Name;
851 break;
852 case GEN_DNS:
853 v = PyUnicode_FromString("DNS");
854 as = name->d.dNSName;
855 break;
856 case GEN_URI:
857 v = PyUnicode_FromString("URI");
858 as = name->d.uniformResourceIdentifier;
859 break;
860 }
861 if (v == NULL) {
862 Py_DECREF(t);
863 goto fail;
864 }
865 PyTuple_SET_ITEM(t, 0, v);
866 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
867 ASN1_STRING_length(as));
868 if (v == NULL) {
869 Py_DECREF(t);
870 goto fail;
871 }
872 PyTuple_SET_ITEM(t, 1, v);
873 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000874
Christian Heimes824f7f32013-08-17 00:54:47 +0200875 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200877 switch (gntype) {
878 /* check for new general name type */
879 case GEN_OTHERNAME:
880 case GEN_X400:
881 case GEN_EDIPARTY:
882 case GEN_IPADD:
883 case GEN_RID:
884 break;
885 default:
886 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
887 "Unknown general name type %d",
888 gntype) == -1) {
889 goto fail;
890 }
891 break;
892 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 (void) BIO_reset(biobuf);
894 GENERAL_NAME_print(biobuf, name);
895 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
896 if (len < 0) {
897 _setSSLError(NULL, 0, __FILE__, __LINE__);
898 goto fail;
899 }
900 vptr = strchr(buf, ':');
901 if (vptr == NULL)
902 goto fail;
903 t = PyTuple_New(2);
904 if (t == NULL)
905 goto fail;
906 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
907 if (v == NULL) {
908 Py_DECREF(t);
909 goto fail;
910 }
911 PyTuple_SET_ITEM(t, 0, v);
912 v = PyUnicode_FromStringAndSize((vptr + 1),
913 (len - (vptr - buf + 1)));
914 if (v == NULL) {
915 Py_DECREF(t);
916 goto fail;
917 }
918 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200919 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 if (PyList_Append(peer_alt_names, t) < 0) {
925 Py_DECREF(t);
926 goto fail;
927 }
928 Py_DECREF(t);
929 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100930 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 }
932 BIO_free(biobuf);
933 if (peer_alt_names != Py_None) {
934 v = PyList_AsTuple(peer_alt_names);
935 Py_DECREF(peer_alt_names);
936 return v;
937 } else {
938 return peer_alt_names;
939 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000940
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
942 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 if (biobuf != NULL)
944 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 if (peer_alt_names != Py_None) {
947 Py_XDECREF(peer_alt_names);
948 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951}
952
953static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000954_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 PyObject *retval = NULL;
957 BIO *biobuf = NULL;
958 PyObject *peer;
959 PyObject *peer_alt_names = NULL;
960 PyObject *issuer;
961 PyObject *version;
962 PyObject *sn_obj;
963 ASN1_INTEGER *serialNumber;
964 char buf[2048];
965 int len;
966 ASN1_TIME *notBefore, *notAfter;
967 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 retval = PyDict_New();
970 if (retval == NULL)
971 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 peer = _create_tuple_for_X509_NAME(
974 X509_get_subject_name(certificate));
975 if (peer == NULL)
976 goto fail0;
977 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
978 Py_DECREF(peer);
979 goto fail0;
980 }
981 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Antoine Pitroufb046912010-11-09 20:21:19 +0000983 issuer = _create_tuple_for_X509_NAME(
984 X509_get_issuer_name(certificate));
985 if (issuer == NULL)
986 goto fail0;
987 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000989 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000991 Py_DECREF(issuer);
992
993 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200994 if (version == NULL)
995 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000996 if (PyDict_SetItemString(retval, "version", version) < 0) {
997 Py_DECREF(version);
998 goto fail0;
999 }
1000 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 /* get a memory buffer */
1003 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001004
Antoine Pitroufb046912010-11-09 20:21:19 +00001005 (void) BIO_reset(biobuf);
1006 serialNumber = X509_get_serialNumber(certificate);
1007 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1008 i2a_ASN1_INTEGER(biobuf, serialNumber);
1009 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1010 if (len < 0) {
1011 _setSSLError(NULL, 0, __FILE__, __LINE__);
1012 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001014 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1015 if (sn_obj == NULL)
1016 goto fail1;
1017 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1018 Py_DECREF(sn_obj);
1019 goto fail1;
1020 }
1021 Py_DECREF(sn_obj);
1022
1023 (void) BIO_reset(biobuf);
1024 notBefore = X509_get_notBefore(certificate);
1025 ASN1_TIME_print(biobuf, notBefore);
1026 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1027 if (len < 0) {
1028 _setSSLError(NULL, 0, __FILE__, __LINE__);
1029 goto fail1;
1030 }
1031 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1032 if (pnotBefore == NULL)
1033 goto fail1;
1034 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1035 Py_DECREF(pnotBefore);
1036 goto fail1;
1037 }
1038 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 (void) BIO_reset(biobuf);
1041 notAfter = X509_get_notAfter(certificate);
1042 ASN1_TIME_print(biobuf, notAfter);
1043 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1044 if (len < 0) {
1045 _setSSLError(NULL, 0, __FILE__, __LINE__);
1046 goto fail1;
1047 }
1048 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1049 if (pnotAfter == NULL)
1050 goto fail1;
1051 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1052 Py_DECREF(pnotAfter);
1053 goto fail1;
1054 }
1055 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 peer_alt_names = _get_peer_alt_names(certificate);
1060 if (peer_alt_names == NULL)
1061 goto fail1;
1062 else if (peer_alt_names != Py_None) {
1063 if (PyDict_SetItemString(retval, "subjectAltName",
1064 peer_alt_names) < 0) {
1065 Py_DECREF(peer_alt_names);
1066 goto fail1;
1067 }
1068 Py_DECREF(peer_alt_names);
1069 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 BIO_free(biobuf);
1072 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001073
1074 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 if (biobuf != NULL)
1076 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001077 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 Py_XDECREF(retval);
1079 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001080}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001081
Christian Heimes9a5395a2013-06-17 15:44:12 +02001082static PyObject *
1083_certificate_to_der(X509 *certificate)
1084{
1085 unsigned char *bytes_buf = NULL;
1086 int len;
1087 PyObject *retval;
1088
1089 bytes_buf = NULL;
1090 len = i2d_X509(certificate, &bytes_buf);
1091 if (len < 0) {
1092 _setSSLError(NULL, 0, __FILE__, __LINE__);
1093 return NULL;
1094 }
1095 /* this is actually an immutable bytes sequence */
1096 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1097 OPENSSL_free(bytes_buf);
1098 return retval;
1099}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100
1101static PyObject *
1102PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001105 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 X509 *x=NULL;
1107 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108
Antoine Pitroufb046912010-11-09 20:21:19 +00001109 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1110 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1114 PyErr_SetString(PySSLErrorObject,
1115 "Can't malloc memory to read file");
1116 goto fail0;
1117 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Victor Stinner3800e1e2010-05-16 21:23:48 +00001119 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 PyErr_SetString(PySSLErrorObject,
1121 "Can't open file");
1122 goto fail0;
1123 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1126 if (x == NULL) {
1127 PyErr_SetString(PySSLErrorObject,
1128 "Error decoding PEM-encoded file");
1129 goto fail0;
1130 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131
Antoine Pitroufb046912010-11-09 20:21:19 +00001132 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001133 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
1135 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001136 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 if (cert != NULL) BIO_free(cert);
1138 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139}
1140
1141
1142static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001143PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001146 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147
Antoine Pitrou721738f2012-08-15 23:20:39 +02001148 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 if (!self->peer_cert)
1152 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153
Antoine Pitrou721738f2012-08-15 23:20:39 +02001154 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001156 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001158 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 if ((verification & SSL_VERIFY_PEER) == 0)
1160 return PyDict_New();
1161 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001162 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164}
1165
1166PyDoc_STRVAR(PySSL_peercert_doc,
1167"peer_certificate([der=False]) -> certificate\n\
1168\n\
1169Returns the certificate for the peer. If no certificate was provided,\n\
1170returns None. If a certificate was provided, but not validated, returns\n\
1171an empty dictionary. Otherwise returns a dict containing information\n\
1172about the peer certificate.\n\
1173\n\
1174If the optional argument is True, returns a DER-encoded copy of the\n\
1175peer certificate, or None if no certificate was provided. This will\n\
1176return the certificate even if it wasn't validated.");
1177
Antoine Pitrou152efa22010-05-16 18:19:27 +00001178static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001181 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 char *cipher_name;
1183 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001186 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 current = SSL_get_current_cipher(self->ssl);
1188 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001189 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 retval = PyTuple_New(3);
1192 if (retval == NULL)
1193 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 cipher_name = (char *) SSL_CIPHER_get_name(current);
1196 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001197 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 PyTuple_SET_ITEM(retval, 0, Py_None);
1199 } else {
1200 v = PyUnicode_FromString(cipher_name);
1201 if (v == NULL)
1202 goto fail0;
1203 PyTuple_SET_ITEM(retval, 0, v);
1204 }
1205 cipher_protocol = SSL_CIPHER_get_version(current);
1206 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001207 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 PyTuple_SET_ITEM(retval, 1, Py_None);
1209 } else {
1210 v = PyUnicode_FromString(cipher_protocol);
1211 if (v == NULL)
1212 goto fail0;
1213 PyTuple_SET_ITEM(retval, 1, v);
1214 }
1215 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1216 if (v == NULL)
1217 goto fail0;
1218 PyTuple_SET_ITEM(retval, 2, v);
1219 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 Py_DECREF(retval);
1223 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001224}
1225
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001226#ifdef OPENSSL_NPN_NEGOTIATED
1227static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1228 const unsigned char *out;
1229 unsigned int outlen;
1230
Victor Stinner4569cd52013-06-23 14:58:43 +02001231 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001232 &out, &outlen);
1233
1234 if (out == NULL)
1235 Py_RETURN_NONE;
1236 return PyUnicode_FromStringAndSize((char *) out, outlen);
1237}
1238#endif
1239
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001240static PyObject *PySSL_compression(PySSLSocket *self) {
1241#ifdef OPENSSL_NO_COMP
1242 Py_RETURN_NONE;
1243#else
1244 const COMP_METHOD *comp_method;
1245 const char *short_name;
1246
1247 if (self->ssl == NULL)
1248 Py_RETURN_NONE;
1249 comp_method = SSL_get_current_compression(self->ssl);
1250 if (comp_method == NULL || comp_method->type == NID_undef)
1251 Py_RETURN_NONE;
1252 short_name = OBJ_nid2sn(comp_method->type);
1253 if (short_name == NULL)
1254 Py_RETURN_NONE;
1255 return PyUnicode_DecodeFSDefault(short_name);
1256#endif
1257}
1258
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001259static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1260 Py_INCREF(self->ctx);
1261 return self->ctx;
1262}
1263
1264static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1265 void *closure) {
1266
1267 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001268#if !HAVE_SNI
1269 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1270 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001271 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001272#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001273 Py_INCREF(value);
1274 Py_DECREF(self->ctx);
1275 self->ctx = (PySSLContext *) value;
1276 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001277#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001278 } else {
1279 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1280 return -1;
1281 }
1282
1283 return 0;
1284}
1285
1286PyDoc_STRVAR(PySSL_set_context_doc,
1287"_setter_context(ctx)\n\
1288\
1289This changes the context associated with the SSLSocket. This is typically\n\
1290used from within a callback function set by the set_servername_callback\n\
1291on the SSLContext to change the certificate information associated with the\n\
1292SSLSocket before the cryptographic exchange handshake messages\n");
1293
1294
1295
Antoine Pitrou152efa22010-05-16 18:19:27 +00001296static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001297{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 if (self->peer_cert) /* Possible not to have one? */
1299 X509_free (self->peer_cert);
1300 if (self->ssl)
1301 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001303 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001305}
1306
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001307/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001308 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001309 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001310 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001311
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001312static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001313check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001314{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 fd_set fds;
1316 struct timeval tv;
1317 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1320 if (s->sock_timeout < 0.0)
1321 return SOCKET_IS_BLOCKING;
1322 else if (s->sock_timeout == 0.0)
1323 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001324
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 /* Guard against closed socket */
1326 if (s->sock_fd < 0)
1327 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 /* Prefer poll, if available, since you can poll() any fd
1330 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 {
1333 struct pollfd pollfd;
1334 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 pollfd.fd = s->sock_fd;
1337 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 /* s->sock_timeout is in seconds, timeout in ms */
1340 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1341 PySSL_BEGIN_ALLOW_THREADS
1342 rc = poll(&pollfd, 1, timeout);
1343 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 goto normal_return;
1346 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001347#endif
1348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001350 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 /* Construct the arguments to select */
1354 tv.tv_sec = (int)s->sock_timeout;
1355 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1356 FD_ZERO(&fds);
1357 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 /* See if the socket is ready */
1360 PySSL_BEGIN_ALLOW_THREADS
1361 if (writing)
1362 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1363 else
1364 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1365 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001366
Bill Janssen6e027db2007-11-15 22:23:56 +00001367#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001368normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001369#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1371 (when we are able to write or when there's something to read) */
1372 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001373}
1374
Antoine Pitrou152efa22010-05-16 18:19:27 +00001375static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001376{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 Py_buffer buf;
1378 int len;
1379 int sockstate;
1380 int err;
1381 int nonblocking;
1382 PySocketSockObject *sock
1383 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 if (((PyObject*)sock) == Py_None) {
1386 _setSSLError("Underlying socket connection gone",
1387 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1388 return NULL;
1389 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001390 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001392 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1393 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001395 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396
Victor Stinner6efa9652013-06-25 00:42:31 +02001397 if (buf.len > INT_MAX) {
1398 PyErr_Format(PyExc_OverflowError,
1399 "string longer than %d bytes", INT_MAX);
1400 goto error;
1401 }
1402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 /* just in case the blocking state of the socket has been changed */
1404 nonblocking = (sock->sock_timeout >= 0.0);
1405 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1406 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1407
1408 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1409 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001410 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 "The write operation timed out");
1412 goto error;
1413 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1414 PyErr_SetString(PySSLErrorObject,
1415 "Underlying socket has been closed.");
1416 goto error;
1417 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1418 PyErr_SetString(PySSLErrorObject,
1419 "Underlying socket too large for select().");
1420 goto error;
1421 }
1422 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001424 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 err = SSL_get_error(self->ssl, len);
1426 PySSL_END_ALLOW_THREADS
1427 if (PyErr_CheckSignals()) {
1428 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001429 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001431 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001433 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 } else {
1435 sockstate = SOCKET_OPERATION_OK;
1436 }
1437 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001438 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 "The write operation timed out");
1440 goto error;
1441 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1442 PyErr_SetString(PySSLErrorObject,
1443 "Underlying socket has been closed.");
1444 goto error;
1445 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1446 break;
1447 }
1448 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001449
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001450 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 PyBuffer_Release(&buf);
1452 if (len > 0)
1453 return PyLong_FromLong(len);
1454 else
1455 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001456
1457error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001458 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001459 PyBuffer_Release(&buf);
1460 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001461}
1462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001463PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001464"write(s) -> len\n\
1465\n\
1466Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001468
Antoine Pitrou152efa22010-05-16 18:19:27 +00001469static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001470{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 PySSL_BEGIN_ALLOW_THREADS
1474 count = SSL_pending(self->ssl);
1475 PySSL_END_ALLOW_THREADS
1476 if (count < 0)
1477 return PySSL_SetError(self, count, __FILE__, __LINE__);
1478 else
1479 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001480}
1481
1482PyDoc_STRVAR(PySSL_SSLpending_doc,
1483"pending() -> count\n\
1484\n\
1485Returns the number of already decrypted bytes available for read,\n\
1486pending on the connection.\n");
1487
Antoine Pitrou152efa22010-05-16 18:19:27 +00001488static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001489{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 PyObject *dest = NULL;
1491 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001493 int len, count;
1494 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 int sockstate;
1496 int err;
1497 int nonblocking;
1498 PySocketSockObject *sock
1499 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 if (((PyObject*)sock) == Py_None) {
1502 _setSSLError("Underlying socket connection gone",
1503 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1504 return NULL;
1505 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001506 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001508 buf.obj = NULL;
1509 buf.buf = NULL;
1510 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001511 goto error;
1512
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001513 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1514 dest = PyBytes_FromStringAndSize(NULL, len);
1515 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001516 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001517 mem = PyBytes_AS_STRING(dest);
1518 }
1519 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001521 mem = buf.buf;
1522 if (len <= 0 || len > buf.len) {
1523 len = (int) buf.len;
1524 if (buf.len != len) {
1525 PyErr_SetString(PyExc_OverflowError,
1526 "maximum length can't fit in a C 'int'");
1527 goto error;
1528 }
1529 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 }
1531
1532 /* just in case the blocking state of the socket has been changed */
1533 nonblocking = (sock->sock_timeout >= 0.0);
1534 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1535 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1536
1537 /* first check if there are bytes ready to be read */
1538 PySSL_BEGIN_ALLOW_THREADS
1539 count = SSL_pending(self->ssl);
1540 PySSL_END_ALLOW_THREADS
1541
1542 if (!count) {
1543 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1544 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001545 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 "The read operation timed out");
1547 goto error;
1548 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1549 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001550 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 goto error;
1552 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1553 count = 0;
1554 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001555 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 }
1557 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PySSL_BEGIN_ALLOW_THREADS
1559 count = SSL_read(self->ssl, mem, len);
1560 err = SSL_get_error(self->ssl, count);
1561 PySSL_END_ALLOW_THREADS
1562 if (PyErr_CheckSignals())
1563 goto error;
1564 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001565 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001567 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1569 (SSL_get_shutdown(self->ssl) ==
1570 SSL_RECEIVED_SHUTDOWN))
1571 {
1572 count = 0;
1573 goto done;
1574 } else {
1575 sockstate = SOCKET_OPERATION_OK;
1576 }
1577 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001578 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 "The read operation timed out");
1580 goto error;
1581 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1582 break;
1583 }
1584 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1585 if (count <= 0) {
1586 PySSL_SetError(self, count, __FILE__, __LINE__);
1587 goto error;
1588 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001589
1590done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001591 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001593 _PyBytes_Resize(&dest, count);
1594 return dest;
1595 }
1596 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001597 PyBuffer_Release(&buf);
1598 return PyLong_FromLong(count);
1599 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001600
1601error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001602 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001603 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001604 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001605 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001608}
1609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001610PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001611"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001613Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001614
Antoine Pitrou152efa22010-05-16 18:19:27 +00001615static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001616{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 int err, ssl_err, sockstate, nonblocking;
1618 int zeros = 0;
1619 PySocketSockObject *sock
1620 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 /* Guard against closed socket */
1623 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1624 _setSSLError("Underlying socket connection gone",
1625 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1626 return NULL;
1627 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001628 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629
1630 /* Just in case the blocking state of the socket has been changed */
1631 nonblocking = (sock->sock_timeout >= 0.0);
1632 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1633 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1634
1635 while (1) {
1636 PySSL_BEGIN_ALLOW_THREADS
1637 /* Disable read-ahead so that unwrap can work correctly.
1638 * Otherwise OpenSSL might read in too much data,
1639 * eating clear text data that happens to be
1640 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001641 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 * function is used and the shutdown_seen_zero != 0
1643 * condition is met.
1644 */
1645 if (self->shutdown_seen_zero)
1646 SSL_set_read_ahead(self->ssl, 0);
1647 err = SSL_shutdown(self->ssl);
1648 PySSL_END_ALLOW_THREADS
1649 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1650 if (err > 0)
1651 break;
1652 if (err == 0) {
1653 /* Don't loop endlessly; instead preserve legacy
1654 behaviour of trying SSL_shutdown() only twice.
1655 This looks necessary for OpenSSL < 0.9.8m */
1656 if (++zeros > 1)
1657 break;
1658 /* Shutdown was sent, now try receiving */
1659 self->shutdown_seen_zero = 1;
1660 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001661 }
1662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 /* Possibly retry shutdown until timeout or failure */
1664 ssl_err = SSL_get_error(self->ssl, err);
1665 if (ssl_err == SSL_ERROR_WANT_READ)
1666 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1667 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1668 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1669 else
1670 break;
1671 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1672 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001673 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 "The read operation timed out");
1675 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001676 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001678 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001679 }
1680 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1681 PyErr_SetString(PySSLErrorObject,
1682 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001683 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 }
1685 else if (sockstate != SOCKET_OPERATION_OK)
1686 /* Retain the SSL error code */
1687 break;
1688 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001689
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001690 if (err < 0) {
1691 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001694 else
1695 /* It's already INCREF'ed */
1696 return (PyObject *) sock;
1697
1698error:
1699 Py_DECREF(sock);
1700 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001701}
1702
1703PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1704"shutdown(s) -> socket\n\
1705\n\
1706Does the SSL shutdown handshake with the remote end, and returns\n\
1707the underlying socket object.");
1708
Antoine Pitroud6494802011-07-21 01:11:30 +02001709#if HAVE_OPENSSL_FINISHED
1710static PyObject *
1711PySSL_tls_unique_cb(PySSLSocket *self)
1712{
1713 PyObject *retval = NULL;
1714 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001715 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001716
1717 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1718 /* if session is resumed XOR we are the client */
1719 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1720 }
1721 else {
1722 /* if a new session XOR we are the server */
1723 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1724 }
1725
1726 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001727 if (len == 0)
1728 Py_RETURN_NONE;
1729
1730 retval = PyBytes_FromStringAndSize(buf, len);
1731
1732 return retval;
1733}
1734
1735PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1736"tls_unique_cb() -> bytes\n\
1737\n\
1738Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1739\n\
1740If the TLS handshake is not yet complete, None is returned");
1741
1742#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001743
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001744static PyGetSetDef ssl_getsetlist[] = {
1745 {"context", (getter) PySSL_get_context,
1746 (setter) PySSL_set_context, PySSL_set_context_doc},
1747 {NULL}, /* sentinel */
1748};
1749
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1752 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1753 PySSL_SSLwrite_doc},
1754 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1755 PySSL_SSLread_doc},
1756 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1757 PySSL_SSLpending_doc},
1758 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1759 PySSL_peercert_doc},
1760 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001761#ifdef OPENSSL_NPN_NEGOTIATED
1762 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1763#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001764 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1766 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001767#if HAVE_OPENSSL_FINISHED
1768 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1769 PySSL_tls_unique_cb_doc},
1770#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772};
1773
Antoine Pitrou152efa22010-05-16 18:19:27 +00001774static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001776 "_ssl._SSLSocket", /*tp_name*/
1777 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 0, /*tp_itemsize*/
1779 /* methods */
1780 (destructor)PySSL_dealloc, /*tp_dealloc*/
1781 0, /*tp_print*/
1782 0, /*tp_getattr*/
1783 0, /*tp_setattr*/
1784 0, /*tp_reserved*/
1785 0, /*tp_repr*/
1786 0, /*tp_as_number*/
1787 0, /*tp_as_sequence*/
1788 0, /*tp_as_mapping*/
1789 0, /*tp_hash*/
1790 0, /*tp_call*/
1791 0, /*tp_str*/
1792 0, /*tp_getattro*/
1793 0, /*tp_setattro*/
1794 0, /*tp_as_buffer*/
1795 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1796 0, /*tp_doc*/
1797 0, /*tp_traverse*/
1798 0, /*tp_clear*/
1799 0, /*tp_richcompare*/
1800 0, /*tp_weaklistoffset*/
1801 0, /*tp_iter*/
1802 0, /*tp_iternext*/
1803 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001804 0, /*tp_members*/
1805 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001806};
1807
Antoine Pitrou152efa22010-05-16 18:19:27 +00001808
1809/*
1810 * _SSLContext objects
1811 */
1812
1813static PyObject *
1814context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1815{
1816 char *kwlist[] = {"protocol", NULL};
1817 PySSLContext *self;
1818 int proto_version = PY_SSL_VERSION_SSL23;
1819 SSL_CTX *ctx = NULL;
1820
1821 if (!PyArg_ParseTupleAndKeywords(
1822 args, kwds, "i:_SSLContext", kwlist,
1823 &proto_version))
1824 return NULL;
1825
1826 PySSL_BEGIN_ALLOW_THREADS
1827 if (proto_version == PY_SSL_VERSION_TLS1)
1828 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001829#if HAVE_TLSv1_2
1830 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1831 ctx = SSL_CTX_new(TLSv1_1_method());
1832 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1833 ctx = SSL_CTX_new(TLSv1_2_method());
1834#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001835 else if (proto_version == PY_SSL_VERSION_SSL3)
1836 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001837#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001838 else if (proto_version == PY_SSL_VERSION_SSL2)
1839 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001840#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001841 else if (proto_version == PY_SSL_VERSION_SSL23)
1842 ctx = SSL_CTX_new(SSLv23_method());
1843 else
1844 proto_version = -1;
1845 PySSL_END_ALLOW_THREADS
1846
1847 if (proto_version == -1) {
1848 PyErr_SetString(PyExc_ValueError,
1849 "invalid protocol version");
1850 return NULL;
1851 }
1852 if (ctx == NULL) {
1853 PyErr_SetString(PySSLErrorObject,
1854 "failed to allocate SSL context");
1855 return NULL;
1856 }
1857
1858 assert(type != NULL && type->tp_alloc != NULL);
1859 self = (PySSLContext *) type->tp_alloc(type, 0);
1860 if (self == NULL) {
1861 SSL_CTX_free(ctx);
1862 return NULL;
1863 }
1864 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001865#ifdef OPENSSL_NPN_NEGOTIATED
1866 self->npn_protocols = NULL;
1867#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001868#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001869 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001870#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001871 /* Defaults */
1872 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001873 SSL_CTX_set_options(self->ctx,
1874 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001875
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001876#define SID_CTX "Python"
1877 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1878 sizeof(SID_CTX));
1879#undef SID_CTX
1880
Antoine Pitrou152efa22010-05-16 18:19:27 +00001881 return (PyObject *)self;
1882}
1883
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001884static int
1885context_traverse(PySSLContext *self, visitproc visit, void *arg)
1886{
1887#ifndef OPENSSL_NO_TLSEXT
1888 Py_VISIT(self->set_hostname);
1889#endif
1890 return 0;
1891}
1892
1893static int
1894context_clear(PySSLContext *self)
1895{
1896#ifndef OPENSSL_NO_TLSEXT
1897 Py_CLEAR(self->set_hostname);
1898#endif
1899 return 0;
1900}
1901
Antoine Pitrou152efa22010-05-16 18:19:27 +00001902static void
1903context_dealloc(PySSLContext *self)
1904{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001905 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001906 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001907#ifdef OPENSSL_NPN_NEGOTIATED
1908 PyMem_Free(self->npn_protocols);
1909#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001910 Py_TYPE(self)->tp_free(self);
1911}
1912
1913static PyObject *
1914set_ciphers(PySSLContext *self, PyObject *args)
1915{
1916 int ret;
1917 const char *cipherlist;
1918
1919 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1920 return NULL;
1921 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1922 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001923 /* Clearing the error queue is necessary on some OpenSSL versions,
1924 otherwise the error will be reported again when another SSL call
1925 is done. */
1926 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001927 PyErr_SetString(PySSLErrorObject,
1928 "No cipher can be selected.");
1929 return NULL;
1930 }
1931 Py_RETURN_NONE;
1932}
1933
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001934#ifdef OPENSSL_NPN_NEGOTIATED
1935/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1936static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001937_advertiseNPN_cb(SSL *s,
1938 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001939 void *args)
1940{
1941 PySSLContext *ssl_ctx = (PySSLContext *) args;
1942
1943 if (ssl_ctx->npn_protocols == NULL) {
1944 *data = (unsigned char *) "";
1945 *len = 0;
1946 } else {
1947 *data = (unsigned char *) ssl_ctx->npn_protocols;
1948 *len = ssl_ctx->npn_protocols_len;
1949 }
1950
1951 return SSL_TLSEXT_ERR_OK;
1952}
1953/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1954static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001955_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001956 unsigned char **out, unsigned char *outlen,
1957 const unsigned char *server, unsigned int server_len,
1958 void *args)
1959{
1960 PySSLContext *ssl_ctx = (PySSLContext *) args;
1961
1962 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1963 int client_len;
1964
1965 if (client == NULL) {
1966 client = (unsigned char *) "";
1967 client_len = 0;
1968 } else {
1969 client_len = ssl_ctx->npn_protocols_len;
1970 }
1971
1972 SSL_select_next_proto(out, outlen,
1973 server, server_len,
1974 client, client_len);
1975
1976 return SSL_TLSEXT_ERR_OK;
1977}
1978#endif
1979
1980static PyObject *
1981_set_npn_protocols(PySSLContext *self, PyObject *args)
1982{
1983#ifdef OPENSSL_NPN_NEGOTIATED
1984 Py_buffer protos;
1985
1986 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1987 return NULL;
1988
Christian Heimes5cb31c92012-09-20 12:42:54 +02001989 if (self->npn_protocols != NULL) {
1990 PyMem_Free(self->npn_protocols);
1991 }
1992
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001993 self->npn_protocols = PyMem_Malloc(protos.len);
1994 if (self->npn_protocols == NULL) {
1995 PyBuffer_Release(&protos);
1996 return PyErr_NoMemory();
1997 }
1998 memcpy(self->npn_protocols, protos.buf, protos.len);
1999 self->npn_protocols_len = (int) protos.len;
2000
2001 /* set both server and client callbacks, because the context can
2002 * be used to create both types of sockets */
2003 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2004 _advertiseNPN_cb,
2005 self);
2006 SSL_CTX_set_next_proto_select_cb(self->ctx,
2007 _selectNPN_cb,
2008 self);
2009
2010 PyBuffer_Release(&protos);
2011 Py_RETURN_NONE;
2012#else
2013 PyErr_SetString(PyExc_NotImplementedError,
2014 "The NPN extension requires OpenSSL 1.0.1 or later.");
2015 return NULL;
2016#endif
2017}
2018
Antoine Pitrou152efa22010-05-16 18:19:27 +00002019static PyObject *
2020get_verify_mode(PySSLContext *self, void *c)
2021{
2022 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2023 case SSL_VERIFY_NONE:
2024 return PyLong_FromLong(PY_SSL_CERT_NONE);
2025 case SSL_VERIFY_PEER:
2026 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2027 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2028 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2029 }
2030 PyErr_SetString(PySSLErrorObject,
2031 "invalid return value from SSL_CTX_get_verify_mode");
2032 return NULL;
2033}
2034
2035static int
2036set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2037{
2038 int n, mode;
2039 if (!PyArg_Parse(arg, "i", &n))
2040 return -1;
2041 if (n == PY_SSL_CERT_NONE)
2042 mode = SSL_VERIFY_NONE;
2043 else if (n == PY_SSL_CERT_OPTIONAL)
2044 mode = SSL_VERIFY_PEER;
2045 else if (n == PY_SSL_CERT_REQUIRED)
2046 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2047 else {
2048 PyErr_SetString(PyExc_ValueError,
2049 "invalid value for verify_mode");
2050 return -1;
2051 }
2052 SSL_CTX_set_verify(self->ctx, mode, NULL);
2053 return 0;
2054}
2055
2056static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002057get_options(PySSLContext *self, void *c)
2058{
2059 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2060}
2061
2062static int
2063set_options(PySSLContext *self, PyObject *arg, void *c)
2064{
2065 long new_opts, opts, set, clear;
2066 if (!PyArg_Parse(arg, "l", &new_opts))
2067 return -1;
2068 opts = SSL_CTX_get_options(self->ctx);
2069 clear = opts & ~new_opts;
2070 set = ~opts & new_opts;
2071 if (clear) {
2072#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2073 SSL_CTX_clear_options(self->ctx, clear);
2074#else
2075 PyErr_SetString(PyExc_ValueError,
2076 "can't clear options before OpenSSL 0.9.8m");
2077 return -1;
2078#endif
2079 }
2080 if (set)
2081 SSL_CTX_set_options(self->ctx, set);
2082 return 0;
2083}
2084
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002085typedef struct {
2086 PyThreadState *thread_state;
2087 PyObject *callable;
2088 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002089 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002090 int error;
2091} _PySSLPasswordInfo;
2092
2093static int
2094_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2095 const char *bad_type_error)
2096{
2097 /* Set the password and size fields of a _PySSLPasswordInfo struct
2098 from a unicode, bytes, or byte array object.
2099 The password field will be dynamically allocated and must be freed
2100 by the caller */
2101 PyObject *password_bytes = NULL;
2102 const char *data = NULL;
2103 Py_ssize_t size;
2104
2105 if (PyUnicode_Check(password)) {
2106 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2107 if (!password_bytes) {
2108 goto error;
2109 }
2110 data = PyBytes_AS_STRING(password_bytes);
2111 size = PyBytes_GET_SIZE(password_bytes);
2112 } else if (PyBytes_Check(password)) {
2113 data = PyBytes_AS_STRING(password);
2114 size = PyBytes_GET_SIZE(password);
2115 } else if (PyByteArray_Check(password)) {
2116 data = PyByteArray_AS_STRING(password);
2117 size = PyByteArray_GET_SIZE(password);
2118 } else {
2119 PyErr_SetString(PyExc_TypeError, bad_type_error);
2120 goto error;
2121 }
2122
Victor Stinner9ee02032013-06-23 15:08:23 +02002123 if (size > (Py_ssize_t)INT_MAX) {
2124 PyErr_Format(PyExc_ValueError,
2125 "password cannot be longer than %d bytes", INT_MAX);
2126 goto error;
2127 }
2128
Victor Stinner11ebff22013-07-07 17:07:52 +02002129 PyMem_Free(pw_info->password);
2130 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002131 if (!pw_info->password) {
2132 PyErr_SetString(PyExc_MemoryError,
2133 "unable to allocate password buffer");
2134 goto error;
2135 }
2136 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002137 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002138
2139 Py_XDECREF(password_bytes);
2140 return 1;
2141
2142error:
2143 Py_XDECREF(password_bytes);
2144 return 0;
2145}
2146
2147static int
2148_password_callback(char *buf, int size, int rwflag, void *userdata)
2149{
2150 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2151 PyObject *fn_ret = NULL;
2152
2153 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2154
2155 if (pw_info->callable) {
2156 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2157 if (!fn_ret) {
2158 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2159 core python API, so we could use it to add a frame here */
2160 goto error;
2161 }
2162
2163 if (!_pwinfo_set(pw_info, fn_ret,
2164 "password callback must return a string")) {
2165 goto error;
2166 }
2167 Py_CLEAR(fn_ret);
2168 }
2169
2170 if (pw_info->size > size) {
2171 PyErr_Format(PyExc_ValueError,
2172 "password cannot be longer than %d bytes", size);
2173 goto error;
2174 }
2175
2176 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2177 memcpy(buf, pw_info->password, pw_info->size);
2178 return pw_info->size;
2179
2180error:
2181 Py_XDECREF(fn_ret);
2182 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2183 pw_info->error = 1;
2184 return -1;
2185}
2186
Antoine Pitroub5218772010-05-21 09:56:06 +00002187static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002188load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2189{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002190 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2191 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002193 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2194 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2195 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002196 int r;
2197
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002198 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002199 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002200 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002201 "O|OO:load_cert_chain", kwlist,
2202 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002203 return NULL;
2204 if (keyfile == Py_None)
2205 keyfile = NULL;
2206 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2207 PyErr_SetString(PyExc_TypeError,
2208 "certfile should be a valid filesystem path");
2209 return NULL;
2210 }
2211 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2212 PyErr_SetString(PyExc_TypeError,
2213 "keyfile should be a valid filesystem path");
2214 goto error;
2215 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002216 if (password && password != Py_None) {
2217 if (PyCallable_Check(password)) {
2218 pw_info.callable = password;
2219 } else if (!_pwinfo_set(&pw_info, password,
2220 "password should be a string or callable")) {
2221 goto error;
2222 }
2223 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2224 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2225 }
2226 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002227 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2228 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002229 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002230 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002231 if (pw_info.error) {
2232 ERR_clear_error();
2233 /* the password callback has already set the error information */
2234 }
2235 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002236 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002237 PyErr_SetFromErrno(PyExc_IOError);
2238 }
2239 else {
2240 _setSSLError(NULL, 0, __FILE__, __LINE__);
2241 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002242 goto error;
2243 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002244 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002245 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002246 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2247 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002248 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2249 Py_CLEAR(keyfile_bytes);
2250 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002251 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002252 if (pw_info.error) {
2253 ERR_clear_error();
2254 /* the password callback has already set the error information */
2255 }
2256 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002257 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002258 PyErr_SetFromErrno(PyExc_IOError);
2259 }
2260 else {
2261 _setSSLError(NULL, 0, __FILE__, __LINE__);
2262 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002263 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002264 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002265 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002266 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002267 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002268 if (r != 1) {
2269 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002270 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002271 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002272 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2273 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002274 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002275 Py_RETURN_NONE;
2276
2277error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002278 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2279 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002280 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002281 Py_XDECREF(keyfile_bytes);
2282 Py_XDECREF(certfile_bytes);
2283 return NULL;
2284}
2285
2286static PyObject *
2287load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2288{
2289 char *kwlist[] = {"cafile", "capath", NULL};
2290 PyObject *cafile = NULL, *capath = NULL;
2291 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2292 const char *cafile_buf = NULL, *capath_buf = NULL;
2293 int r;
2294
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002295 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2297 "|OO:load_verify_locations", kwlist,
2298 &cafile, &capath))
2299 return NULL;
2300 if (cafile == Py_None)
2301 cafile = NULL;
2302 if (capath == Py_None)
2303 capath = NULL;
2304 if (cafile == NULL && capath == NULL) {
2305 PyErr_SetString(PyExc_TypeError,
2306 "cafile and capath cannot be both omitted");
2307 return NULL;
2308 }
2309 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "cafile should be a valid filesystem path");
2312 return NULL;
2313 }
2314 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002315 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002316 PyErr_SetString(PyExc_TypeError,
2317 "capath should be a valid filesystem path");
2318 return NULL;
2319 }
2320 if (cafile)
2321 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2322 if (capath)
2323 capath_buf = PyBytes_AS_STRING(capath_bytes);
2324 PySSL_BEGIN_ALLOW_THREADS
2325 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2326 PySSL_END_ALLOW_THREADS
2327 Py_XDECREF(cafile_bytes);
2328 Py_XDECREF(capath_bytes);
2329 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002330 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002331 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002332 PyErr_SetFromErrno(PyExc_IOError);
2333 }
2334 else {
2335 _setSSLError(NULL, 0, __FILE__, __LINE__);
2336 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002337 return NULL;
2338 }
2339 Py_RETURN_NONE;
2340}
2341
2342static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002343load_dh_params(PySSLContext *self, PyObject *filepath)
2344{
2345 FILE *f;
2346 DH *dh;
2347
2348 f = _Py_fopen(filepath, "rb");
2349 if (f == NULL) {
2350 if (!PyErr_Occurred())
2351 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2352 return NULL;
2353 }
2354 errno = 0;
2355 PySSL_BEGIN_ALLOW_THREADS
2356 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002357 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002358 PySSL_END_ALLOW_THREADS
2359 if (dh == NULL) {
2360 if (errno != 0) {
2361 ERR_clear_error();
2362 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2363 }
2364 else {
2365 _setSSLError(NULL, 0, __FILE__, __LINE__);
2366 }
2367 return NULL;
2368 }
2369 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2370 _setSSLError(NULL, 0, __FILE__, __LINE__);
2371 DH_free(dh);
2372 Py_RETURN_NONE;
2373}
2374
2375static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002376context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2377{
Antoine Pitroud5323212010-10-22 18:19:07 +00002378 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002379 PySocketSockObject *sock;
2380 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002381 char *hostname = NULL;
2382 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002383
Antoine Pitroud5323212010-10-22 18:19:07 +00002384 /* server_hostname is either None (or absent), or to be encoded
2385 using the idna encoding. */
2386 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002387 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002388 &sock, &server_side,
2389 Py_TYPE(Py_None), &hostname_obj)) {
2390 PyErr_Clear();
2391 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2392 PySocketModule.Sock_Type,
2393 &sock, &server_side,
2394 "idna", &hostname))
2395 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002396#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002397 PyMem_Free(hostname);
2398 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2399 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002401#endif
2402 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002403
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002404 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002405 hostname);
2406 if (hostname != NULL)
2407 PyMem_Free(hostname);
2408 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002409}
2410
Antoine Pitroub0182c82010-10-12 20:09:02 +00002411static PyObject *
2412session_stats(PySSLContext *self, PyObject *unused)
2413{
2414 int r;
2415 PyObject *value, *stats = PyDict_New();
2416 if (!stats)
2417 return NULL;
2418
2419#define ADD_STATS(SSL_NAME, KEY_NAME) \
2420 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2421 if (value == NULL) \
2422 goto error; \
2423 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2424 Py_DECREF(value); \
2425 if (r < 0) \
2426 goto error;
2427
2428 ADD_STATS(number, "number");
2429 ADD_STATS(connect, "connect");
2430 ADD_STATS(connect_good, "connect_good");
2431 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2432 ADD_STATS(accept, "accept");
2433 ADD_STATS(accept_good, "accept_good");
2434 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2435 ADD_STATS(accept, "accept");
2436 ADD_STATS(hits, "hits");
2437 ADD_STATS(misses, "misses");
2438 ADD_STATS(timeouts, "timeouts");
2439 ADD_STATS(cache_full, "cache_full");
2440
2441#undef ADD_STATS
2442
2443 return stats;
2444
2445error:
2446 Py_DECREF(stats);
2447 return NULL;
2448}
2449
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002450static PyObject *
2451set_default_verify_paths(PySSLContext *self, PyObject *unused)
2452{
2453 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2454 _setSSLError(NULL, 0, __FILE__, __LINE__);
2455 return NULL;
2456 }
2457 Py_RETURN_NONE;
2458}
2459
Antoine Pitrou501da612011-12-21 09:27:41 +01002460#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002461static PyObject *
2462set_ecdh_curve(PySSLContext *self, PyObject *name)
2463{
2464 PyObject *name_bytes;
2465 int nid;
2466 EC_KEY *key;
2467
2468 if (!PyUnicode_FSConverter(name, &name_bytes))
2469 return NULL;
2470 assert(PyBytes_Check(name_bytes));
2471 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2472 Py_DECREF(name_bytes);
2473 if (nid == 0) {
2474 PyErr_Format(PyExc_ValueError,
2475 "unknown elliptic curve name %R", name);
2476 return NULL;
2477 }
2478 key = EC_KEY_new_by_curve_name(nid);
2479 if (key == NULL) {
2480 _setSSLError(NULL, 0, __FILE__, __LINE__);
2481 return NULL;
2482 }
2483 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2484 EC_KEY_free(key);
2485 Py_RETURN_NONE;
2486}
Antoine Pitrou501da612011-12-21 09:27:41 +01002487#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002488
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002489#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002490static int
2491_servername_callback(SSL *s, int *al, void *args)
2492{
2493 int ret;
2494 PySSLContext *ssl_ctx = (PySSLContext *) args;
2495 PySSLSocket *ssl;
2496 PyObject *servername_o;
2497 PyObject *servername_idna;
2498 PyObject *result;
2499 /* The high-level ssl.SSLSocket object */
2500 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002501 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002502#ifdef WITH_THREAD
2503 PyGILState_STATE gstate = PyGILState_Ensure();
2504#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002505
2506 if (ssl_ctx->set_hostname == NULL) {
2507 /* remove race condition in this the call back while if removing the
2508 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002509#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002510 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002511#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002512 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002513 }
2514
2515 ssl = SSL_get_app_data(s);
2516 assert(PySSLSocket_Check(ssl));
2517 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2518 Py_INCREF(ssl_socket);
2519 if (ssl_socket == Py_None) {
2520 goto error;
2521 }
Victor Stinner7e001512013-06-25 00:44:31 +02002522
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002523 if (servername == NULL) {
2524 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2525 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002526 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002527 else {
2528 servername_o = PyBytes_FromString(servername);
2529 if (servername_o == NULL) {
2530 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2531 goto error;
2532 }
2533 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2534 if (servername_idna == NULL) {
2535 PyErr_WriteUnraisable(servername_o);
2536 Py_DECREF(servername_o);
2537 goto error;
2538 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002539 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002540 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2541 servername_idna, ssl_ctx, NULL);
2542 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002543 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002544 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002545
2546 if (result == NULL) {
2547 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2548 *al = SSL_AD_HANDSHAKE_FAILURE;
2549 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2550 }
2551 else {
2552 if (result != Py_None) {
2553 *al = (int) PyLong_AsLong(result);
2554 if (PyErr_Occurred()) {
2555 PyErr_WriteUnraisable(result);
2556 *al = SSL_AD_INTERNAL_ERROR;
2557 }
2558 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2559 }
2560 else {
2561 ret = SSL_TLSEXT_ERR_OK;
2562 }
2563 Py_DECREF(result);
2564 }
2565
Stefan Krah20d60802013-01-17 17:07:17 +01002566#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002567 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002568#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002569 return ret;
2570
2571error:
2572 Py_DECREF(ssl_socket);
2573 *al = SSL_AD_INTERNAL_ERROR;
2574 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002575#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002576 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002577#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002578 return ret;
2579}
Antoine Pitroua5963382013-03-30 16:39:00 +01002580#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002581
2582PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2583"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002584\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002585This sets a callback that will be called when a server name is provided by\n\
2586the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002587\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002588If the argument is None then the callback is disabled. The method is called\n\
2589with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002590See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002591
2592static PyObject *
2593set_servername_callback(PySSLContext *self, PyObject *args)
2594{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002595#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002596 PyObject *cb;
2597
2598 if (!PyArg_ParseTuple(args, "O", &cb))
2599 return NULL;
2600
2601 Py_CLEAR(self->set_hostname);
2602 if (cb == Py_None) {
2603 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2604 }
2605 else {
2606 if (!PyCallable_Check(cb)) {
2607 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2608 PyErr_SetString(PyExc_TypeError,
2609 "not a callable object");
2610 return NULL;
2611 }
2612 Py_INCREF(cb);
2613 self->set_hostname = cb;
2614 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2615 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2616 }
2617 Py_RETURN_NONE;
2618#else
2619 PyErr_SetString(PyExc_NotImplementedError,
2620 "The TLS extension servername callback, "
2621 "SSL_CTX_set_tlsext_servername_callback, "
2622 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002623 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002624#endif
2625}
2626
Christian Heimes9a5395a2013-06-17 15:44:12 +02002627PyDoc_STRVAR(PySSL_get_stats_doc,
2628"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2629\n\
2630Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2631CA extension and certificate revocation lists inside the context's cert\n\
2632store.\n\
2633NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2634been used at least once.");
2635
2636static PyObject *
2637cert_store_stats(PySSLContext *self)
2638{
2639 X509_STORE *store;
2640 X509_OBJECT *obj;
2641 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2642
2643 store = SSL_CTX_get_cert_store(self->ctx);
2644 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2645 obj = sk_X509_OBJECT_value(store->objs, i);
2646 switch (obj->type) {
2647 case X509_LU_X509:
2648 x509++;
2649 if (X509_check_ca(obj->data.x509)) {
2650 ca++;
2651 }
2652 break;
2653 case X509_LU_CRL:
2654 crl++;
2655 break;
2656 case X509_LU_PKEY:
2657 pkey++;
2658 break;
2659 default:
2660 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2661 * As far as I can tell they are internal states and never
2662 * stored in a cert store */
2663 break;
2664 }
2665 }
2666 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2667 "x509_ca", ca);
2668}
2669
2670PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2671"get_ca_certs([der=False]) -> list of loaded certificate\n\
2672\n\
2673Returns a list of dicts with information of loaded CA certs. If the\n\
2674optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2675NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2676been used at least once.");
2677
2678static PyObject *
2679get_ca_certs(PySSLContext *self, PyObject *args)
2680{
2681 X509_STORE *store;
2682 PyObject *ci = NULL, *rlist = NULL;
2683 int i;
2684 int binary_mode = 0;
2685
2686 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2687 return NULL;
2688 }
2689
2690 if ((rlist = PyList_New(0)) == NULL) {
2691 return NULL;
2692 }
2693
2694 store = SSL_CTX_get_cert_store(self->ctx);
2695 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2696 X509_OBJECT *obj;
2697 X509 *cert;
2698
2699 obj = sk_X509_OBJECT_value(store->objs, i);
2700 if (obj->type != X509_LU_X509) {
2701 /* not a x509 cert */
2702 continue;
2703 }
2704 /* CA for any purpose */
2705 cert = obj->data.x509;
2706 if (!X509_check_ca(cert)) {
2707 continue;
2708 }
2709 if (binary_mode) {
2710 ci = _certificate_to_der(cert);
2711 } else {
2712 ci = _decode_certificate(cert);
2713 }
2714 if (ci == NULL) {
2715 goto error;
2716 }
2717 if (PyList_Append(rlist, ci) == -1) {
2718 goto error;
2719 }
2720 Py_CLEAR(ci);
2721 }
2722 return rlist;
2723
2724 error:
2725 Py_XDECREF(ci);
2726 Py_XDECREF(rlist);
2727 return NULL;
2728}
2729
2730
Antoine Pitrou152efa22010-05-16 18:19:27 +00002731static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002732 {"options", (getter) get_options,
2733 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734 {"verify_mode", (getter) get_verify_mode,
2735 (setter) set_verify_mode, NULL},
2736 {NULL}, /* sentinel */
2737};
2738
2739static struct PyMethodDef context_methods[] = {
2740 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2741 METH_VARARGS | METH_KEYWORDS, NULL},
2742 {"set_ciphers", (PyCFunction) set_ciphers,
2743 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002744 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2745 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746 {"load_cert_chain", (PyCFunction) load_cert_chain,
2747 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002748 {"load_dh_params", (PyCFunction) load_dh_params,
2749 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002750 {"load_verify_locations", (PyCFunction) load_verify_locations,
2751 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002752 {"session_stats", (PyCFunction) session_stats,
2753 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002754 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2755 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002756#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002757 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2758 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002759#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002760 {"set_servername_callback", (PyCFunction) set_servername_callback,
2761 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002762 {"cert_store_stats", (PyCFunction) cert_store_stats,
2763 METH_NOARGS, PySSL_get_stats_doc},
2764 {"get_ca_certs", (PyCFunction) get_ca_certs,
2765 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002766 {NULL, NULL} /* sentinel */
2767};
2768
2769static PyTypeObject PySSLContext_Type = {
2770 PyVarObject_HEAD_INIT(NULL, 0)
2771 "_ssl._SSLContext", /*tp_name*/
2772 sizeof(PySSLContext), /*tp_basicsize*/
2773 0, /*tp_itemsize*/
2774 (destructor)context_dealloc, /*tp_dealloc*/
2775 0, /*tp_print*/
2776 0, /*tp_getattr*/
2777 0, /*tp_setattr*/
2778 0, /*tp_reserved*/
2779 0, /*tp_repr*/
2780 0, /*tp_as_number*/
2781 0, /*tp_as_sequence*/
2782 0, /*tp_as_mapping*/
2783 0, /*tp_hash*/
2784 0, /*tp_call*/
2785 0, /*tp_str*/
2786 0, /*tp_getattro*/
2787 0, /*tp_setattro*/
2788 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002789 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002791 (traverseproc) context_traverse, /*tp_traverse*/
2792 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 0, /*tp_richcompare*/
2794 0, /*tp_weaklistoffset*/
2795 0, /*tp_iter*/
2796 0, /*tp_iternext*/
2797 context_methods, /*tp_methods*/
2798 0, /*tp_members*/
2799 context_getsetlist, /*tp_getset*/
2800 0, /*tp_base*/
2801 0, /*tp_dict*/
2802 0, /*tp_descr_get*/
2803 0, /*tp_descr_set*/
2804 0, /*tp_dictoffset*/
2805 0, /*tp_init*/
2806 0, /*tp_alloc*/
2807 context_new, /*tp_new*/
2808};
2809
2810
2811
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002812#ifdef HAVE_OPENSSL_RAND
2813
2814/* helper routines for seeding the SSL PRNG */
2815static PyObject *
2816PySSL_RAND_add(PyObject *self, PyObject *args)
2817{
2818 char *buf;
2819 int len;
2820 double entropy;
2821
2822 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002823 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002824 RAND_add(buf, len, entropy);
2825 Py_INCREF(Py_None);
2826 return Py_None;
2827}
2828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002829PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002830"RAND_add(string, entropy)\n\
2831\n\
2832Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002833bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002834
2835static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002836PySSL_RAND(int len, int pseudo)
2837{
2838 int ok;
2839 PyObject *bytes;
2840 unsigned long err;
2841 const char *errstr;
2842 PyObject *v;
2843
2844 bytes = PyBytes_FromStringAndSize(NULL, len);
2845 if (bytes == NULL)
2846 return NULL;
2847 if (pseudo) {
2848 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2849 if (ok == 0 || ok == 1)
2850 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2851 }
2852 else {
2853 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2854 if (ok == 1)
2855 return bytes;
2856 }
2857 Py_DECREF(bytes);
2858
2859 err = ERR_get_error();
2860 errstr = ERR_reason_error_string(err);
2861 v = Py_BuildValue("(ks)", err, errstr);
2862 if (v != NULL) {
2863 PyErr_SetObject(PySSLErrorObject, v);
2864 Py_DECREF(v);
2865 }
2866 return NULL;
2867}
2868
2869static PyObject *
2870PySSL_RAND_bytes(PyObject *self, PyObject *args)
2871{
2872 int len;
2873 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2874 return NULL;
2875 return PySSL_RAND(len, 0);
2876}
2877
2878PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2879"RAND_bytes(n) -> bytes\n\
2880\n\
2881Generate n cryptographically strong pseudo-random bytes.");
2882
2883static PyObject *
2884PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2885{
2886 int len;
2887 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2888 return NULL;
2889 return PySSL_RAND(len, 1);
2890}
2891
2892PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2893"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2894\n\
2895Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2896generated are cryptographically strong.");
2897
2898static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002899PySSL_RAND_status(PyObject *self)
2900{
Christian Heimes217cfd12007-12-02 14:31:20 +00002901 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002902}
2903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002904PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002905"RAND_status() -> 0 or 1\n\
2906\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002907Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2908It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2909using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002910
2911static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002912PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002913{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002914 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002915 int bytes;
2916
Jesus Ceac8754a12012-09-11 02:00:58 +02002917 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002918 PyUnicode_FSConverter, &path))
2919 return NULL;
2920
2921 bytes = RAND_egd(PyBytes_AsString(path));
2922 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002923 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002924 PyErr_SetString(PySSLErrorObject,
2925 "EGD connection failed or EGD did not return "
2926 "enough data to seed the PRNG");
2927 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002928 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002929 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002930}
2931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002932PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002933"RAND_egd(path) -> bytes\n\
2934\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002935Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2936Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002937fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002938
2939#endif
2940
Christian Heimes6d7ad132013-06-09 18:02:55 +02002941PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2942"get_default_verify_paths() -> tuple\n\
2943\n\
2944Return search paths and environment vars that are used by SSLContext's\n\
2945set_default_verify_paths() to load default CAs. The values are\n\
2946'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2947
2948static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002949PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002950{
2951 PyObject *ofile_env = NULL;
2952 PyObject *ofile = NULL;
2953 PyObject *odir_env = NULL;
2954 PyObject *odir = NULL;
2955
2956#define convert(info, target) { \
2957 const char *tmp = (info); \
2958 target = NULL; \
2959 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2960 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2961 target = PyBytes_FromString(tmp); } \
2962 if (!target) goto error; \
2963 } while(0)
2964
2965 convert(X509_get_default_cert_file_env(), ofile_env);
2966 convert(X509_get_default_cert_file(), ofile);
2967 convert(X509_get_default_cert_dir_env(), odir_env);
2968 convert(X509_get_default_cert_dir(), odir);
2969#undef convert
2970
Christian Heimes200bb1b2013-06-14 15:14:29 +02002971 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002972
2973 error:
2974 Py_XDECREF(ofile_env);
2975 Py_XDECREF(ofile);
2976 Py_XDECREF(odir_env);
2977 Py_XDECREF(odir);
2978 return NULL;
2979}
2980
Christian Heimes46bebee2013-06-09 19:03:31 +02002981#ifdef _MSC_VER
2982PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2983"enum_cert_store(store_name, cert_type='certificate') -> []\n\
2984\n\
2985Retrieve certificates from Windows' cert store. store_name may be one of\n\
2986'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
2987cert_type must be either 'certificate' or 'crl'.\n\
2988The function returns a list of (bytes, encoding_type) tuples. The\n\
2989encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
2990PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00002991
Christian Heimes46bebee2013-06-09 19:03:31 +02002992static PyObject *
2993PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
2994{
2995 char *kwlist[] = {"store_name", "cert_type", NULL};
2996 char *store_name;
2997 char *cert_type = "certificate";
2998 HCERTSTORE hStore = NULL;
2999 PyObject *result = NULL;
3000 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3001 int ok = 1;
3002
3003 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3004 kwlist, &store_name, &cert_type)) {
3005 return NULL;
3006 }
3007
3008 if ((strcmp(cert_type, "certificate") != 0) &&
3009 (strcmp(cert_type, "crl") != 0)) {
3010 return PyErr_Format(PyExc_ValueError,
3011 "cert_type must be 'certificate' or 'crl', "
3012 "not %.100s", cert_type);
3013 }
3014
3015 if ((result = PyList_New(0)) == NULL) {
3016 return NULL;
3017 }
3018
3019 if ((hStore = CertOpenSystemStore(NULL, store_name)) == NULL) {
3020 Py_DECREF(result);
3021 return PyErr_SetFromWindowsErr(GetLastError());
3022 }
3023
3024 if (strcmp(cert_type, "certificate") == 0) {
3025 PCCERT_CONTEXT pCertCtx = NULL;
3026 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3027 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3028 pCertCtx->cbCertEncoded);
3029 if (!cert) {
3030 ok = 0;
3031 break;
3032 }
3033 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3034 ok = 0;
3035 break;
3036 }
3037 if ((tup = PyTuple_New(2)) == NULL) {
3038 ok = 0;
3039 break;
3040 }
3041 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3042 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3043
3044 if (PyList_Append(result, tup) < 0) {
3045 ok = 0;
3046 break;
3047 }
3048 Py_CLEAR(tup);
3049 }
3050 if (pCertCtx) {
3051 /* loop ended with an error, need to clean up context manually */
3052 CertFreeCertificateContext(pCertCtx);
3053 }
3054 } else {
3055 PCCRL_CONTEXT pCrlCtx = NULL;
3056 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3057 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3058 pCrlCtx->cbCrlEncoded);
3059 if (!cert) {
3060 ok = 0;
3061 break;
3062 }
3063 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3064 ok = 0;
3065 break;
3066 }
3067 if ((tup = PyTuple_New(2)) == NULL) {
3068 ok = 0;
3069 break;
3070 }
3071 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3072 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3073
3074 if (PyList_Append(result, tup) < 0) {
3075 ok = 0;
3076 break;
3077 }
3078 Py_CLEAR(tup);
3079 }
3080 if (pCrlCtx) {
3081 /* loop ended with an error, need to clean up context manually */
3082 CertFreeCRLContext(pCrlCtx);
3083 }
3084 }
3085
3086 /* In error cases cert, enc and tup may not be NULL */
3087 Py_XDECREF(cert);
3088 Py_XDECREF(enc);
3089 Py_XDECREF(tup);
3090
3091 if (!CertCloseStore(hStore, 0)) {
3092 /* This error case might shadow another exception.*/
3093 Py_DECREF(result);
3094 return PyErr_SetFromWindowsErr(GetLastError());
3095 }
3096 if (ok) {
3097 return result;
3098 } else {
3099 Py_DECREF(result);
3100 return NULL;
3101 }
3102}
3103#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003105/* List of functions exported by this module. */
3106
3107static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003108 {"_test_decode_cert", PySSL_test_decode_certificate,
3109 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003110#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003111 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3112 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003113 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3114 PySSL_RAND_bytes_doc},
3115 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3116 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003117 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003118 PySSL_RAND_egd_doc},
3119 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3120 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003121#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003122 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003123 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003124#ifdef _MSC_VER
3125 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3126 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3127#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003128 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003129};
3130
3131
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003132#ifdef WITH_THREAD
3133
3134/* an implementation of OpenSSL threading operations in terms
3135 of the Python C thread library */
3136
3137static PyThread_type_lock *_ssl_locks = NULL;
3138
3139static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003140 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003141}
3142
Bill Janssen6e027db2007-11-15 22:23:56 +00003143static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003144 (int mode, int n, const char *file, int line) {
3145 /* this function is needed to perform locking on shared data
3146 structures. (Note that OpenSSL uses a number of global data
3147 structures that will be implicitly shared whenever multiple
3148 threads use OpenSSL.) Multi-threaded applications will
3149 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003151 locking_function() must be able to handle up to
3152 CRYPTO_num_locks() different mutex locks. It sets the n-th
3153 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003155 file and line are the file number of the function setting the
3156 lock. They can be useful for debugging.
3157 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003159 if ((_ssl_locks == NULL) ||
3160 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3161 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003162
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003163 if (mode & CRYPTO_LOCK) {
3164 PyThread_acquire_lock(_ssl_locks[n], 1);
3165 } else {
3166 PyThread_release_lock(_ssl_locks[n]);
3167 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003168}
3169
3170static int _setup_ssl_threads(void) {
3171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003172 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003174 if (_ssl_locks == NULL) {
3175 _ssl_locks_count = CRYPTO_num_locks();
3176 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003177 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003178 if (_ssl_locks == NULL)
3179 return 0;
3180 memset(_ssl_locks, 0,
3181 sizeof(PyThread_type_lock) * _ssl_locks_count);
3182 for (i = 0; i < _ssl_locks_count; i++) {
3183 _ssl_locks[i] = PyThread_allocate_lock();
3184 if (_ssl_locks[i] == NULL) {
3185 unsigned int j;
3186 for (j = 0; j < i; j++) {
3187 PyThread_free_lock(_ssl_locks[j]);
3188 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003189 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003190 return 0;
3191 }
3192 }
3193 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
3194 CRYPTO_set_id_callback(_ssl_thread_id_function);
3195 }
3196 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003197}
3198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003199#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003201PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003202"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003203for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003204
Martin v. Löwis1a214512008-06-11 05:26:20 +00003205
3206static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003207 PyModuleDef_HEAD_INIT,
3208 "_ssl",
3209 module_doc,
3210 -1,
3211 PySSL_methods,
3212 NULL,
3213 NULL,
3214 NULL,
3215 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003216};
3217
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003218
3219static void
3220parse_openssl_version(unsigned long libver,
3221 unsigned int *major, unsigned int *minor,
3222 unsigned int *fix, unsigned int *patch,
3223 unsigned int *status)
3224{
3225 *status = libver & 0xF;
3226 libver >>= 4;
3227 *patch = libver & 0xFF;
3228 libver >>= 8;
3229 *fix = libver & 0xFF;
3230 libver >>= 8;
3231 *minor = libver & 0xFF;
3232 libver >>= 8;
3233 *major = libver & 0xFF;
3234}
3235
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003236PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003237PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003238{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003239 PyObject *m, *d, *r;
3240 unsigned long libver;
3241 unsigned int major, minor, fix, patch, status;
3242 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003243 struct py_ssl_error_code *errcode;
3244 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003245
Antoine Pitrou152efa22010-05-16 18:19:27 +00003246 if (PyType_Ready(&PySSLContext_Type) < 0)
3247 return NULL;
3248 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003249 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003251 m = PyModule_Create(&_sslmodule);
3252 if (m == NULL)
3253 return NULL;
3254 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003256 /* Load _socket module and its C API */
3257 socket_api = PySocketModule_ImportModuleAndAPI();
3258 if (!socket_api)
3259 return NULL;
3260 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003262 /* Init OpenSSL */
3263 SSL_load_error_strings();
3264 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003265#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003266 /* note that this will start threading if not already started */
3267 if (!_setup_ssl_threads()) {
3268 return NULL;
3269 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003270#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003271 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003273 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003274 sslerror_type_slots[0].pfunc = PyExc_OSError;
3275 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003276 if (PySSLErrorObject == NULL)
3277 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003278
Antoine Pitrou41032a62011-10-27 23:56:55 +02003279 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3280 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3281 PySSLErrorObject, NULL);
3282 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3283 "ssl.SSLWantReadError", SSLWantReadError_doc,
3284 PySSLErrorObject, NULL);
3285 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3286 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3287 PySSLErrorObject, NULL);
3288 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3289 "ssl.SSLSyscallError", SSLSyscallError_doc,
3290 PySSLErrorObject, NULL);
3291 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3292 "ssl.SSLEOFError", SSLEOFError_doc,
3293 PySSLErrorObject, NULL);
3294 if (PySSLZeroReturnErrorObject == NULL
3295 || PySSLWantReadErrorObject == NULL
3296 || PySSLWantWriteErrorObject == NULL
3297 || PySSLSyscallErrorObject == NULL
3298 || PySSLEOFErrorObject == NULL)
3299 return NULL;
3300 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3301 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3302 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3303 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3304 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3305 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003306 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003307 if (PyDict_SetItemString(d, "_SSLContext",
3308 (PyObject *)&PySSLContext_Type) != 0)
3309 return NULL;
3310 if (PyDict_SetItemString(d, "_SSLSocket",
3311 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003312 return NULL;
3313 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3314 PY_SSL_ERROR_ZERO_RETURN);
3315 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3316 PY_SSL_ERROR_WANT_READ);
3317 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3318 PY_SSL_ERROR_WANT_WRITE);
3319 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3320 PY_SSL_ERROR_WANT_X509_LOOKUP);
3321 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3322 PY_SSL_ERROR_SYSCALL);
3323 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3324 PY_SSL_ERROR_SSL);
3325 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3326 PY_SSL_ERROR_WANT_CONNECT);
3327 /* non ssl.h errorcodes */
3328 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3329 PY_SSL_ERROR_EOF);
3330 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3331 PY_SSL_ERROR_INVALID_ERROR_CODE);
3332 /* cert requirements */
3333 PyModule_AddIntConstant(m, "CERT_NONE",
3334 PY_SSL_CERT_NONE);
3335 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3336 PY_SSL_CERT_OPTIONAL);
3337 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3338 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003339
Christian Heimes46bebee2013-06-09 19:03:31 +02003340#ifdef _MSC_VER
3341 /* Windows dwCertEncodingType */
3342 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3343 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3344#endif
3345
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003346 /* Alert Descriptions from ssl.h */
3347 /* note RESERVED constants no longer intended for use have been removed */
3348 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3349
3350#define ADD_AD_CONSTANT(s) \
3351 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3352 SSL_AD_##s)
3353
3354 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3355 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3356 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3357 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3358 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3359 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3360 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3361 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3362 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3363 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3364 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3365 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3366 ADD_AD_CONSTANT(UNKNOWN_CA);
3367 ADD_AD_CONSTANT(ACCESS_DENIED);
3368 ADD_AD_CONSTANT(DECODE_ERROR);
3369 ADD_AD_CONSTANT(DECRYPT_ERROR);
3370 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3371 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3372 ADD_AD_CONSTANT(INTERNAL_ERROR);
3373 ADD_AD_CONSTANT(USER_CANCELLED);
3374 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003375 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003376#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3377 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3378#endif
3379#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3380 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3381#endif
3382#ifdef SSL_AD_UNRECOGNIZED_NAME
3383 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3384#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003385#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3386 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3387#endif
3388#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3389 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3390#endif
3391#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3392 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3393#endif
3394
3395#undef ADD_AD_CONSTANT
3396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003397 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003398#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003399 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3400 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003401#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003402 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3403 PY_SSL_VERSION_SSL3);
3404 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3405 PY_SSL_VERSION_SSL23);
3406 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3407 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003408#if HAVE_TLSv1_2
3409 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3410 PY_SSL_VERSION_TLS1_1);
3411 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3412 PY_SSL_VERSION_TLS1_2);
3413#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003414
Antoine Pitroub5218772010-05-21 09:56:06 +00003415 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003416 PyModule_AddIntConstant(m, "OP_ALL",
3417 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003418 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3419 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3420 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003421#if HAVE_TLSv1_2
3422 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3423 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3424#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003425 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3426 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003427 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003428#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003429 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003430#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003431#ifdef SSL_OP_NO_COMPRESSION
3432 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3433 SSL_OP_NO_COMPRESSION);
3434#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003435
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003436#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003437 r = Py_True;
3438#else
3439 r = Py_False;
3440#endif
3441 Py_INCREF(r);
3442 PyModule_AddObject(m, "HAS_SNI", r);
3443
Antoine Pitroud6494802011-07-21 01:11:30 +02003444#if HAVE_OPENSSL_FINISHED
3445 r = Py_True;
3446#else
3447 r = Py_False;
3448#endif
3449 Py_INCREF(r);
3450 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3451
Antoine Pitrou501da612011-12-21 09:27:41 +01003452#ifdef OPENSSL_NO_ECDH
3453 r = Py_False;
3454#else
3455 r = Py_True;
3456#endif
3457 Py_INCREF(r);
3458 PyModule_AddObject(m, "HAS_ECDH", r);
3459
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003460#ifdef OPENSSL_NPN_NEGOTIATED
3461 r = Py_True;
3462#else
3463 r = Py_False;
3464#endif
3465 Py_INCREF(r);
3466 PyModule_AddObject(m, "HAS_NPN", r);
3467
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003468 /* Mappings for error codes */
3469 err_codes_to_names = PyDict_New();
3470 err_names_to_codes = PyDict_New();
3471 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3472 return NULL;
3473 errcode = error_codes;
3474 while (errcode->mnemonic != NULL) {
3475 PyObject *mnemo, *key;
3476 mnemo = PyUnicode_FromString(errcode->mnemonic);
3477 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3478 if (mnemo == NULL || key == NULL)
3479 return NULL;
3480 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3481 return NULL;
3482 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3483 return NULL;
3484 Py_DECREF(key);
3485 Py_DECREF(mnemo);
3486 errcode++;
3487 }
3488 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3489 return NULL;
3490 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3491 return NULL;
3492
3493 lib_codes_to_names = PyDict_New();
3494 if (lib_codes_to_names == NULL)
3495 return NULL;
3496 libcode = library_codes;
3497 while (libcode->library != NULL) {
3498 PyObject *mnemo, *key;
3499 key = PyLong_FromLong(libcode->code);
3500 mnemo = PyUnicode_FromString(libcode->library);
3501 if (key == NULL || mnemo == NULL)
3502 return NULL;
3503 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3504 return NULL;
3505 Py_DECREF(key);
3506 Py_DECREF(mnemo);
3507 libcode++;
3508 }
3509 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3510 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003511
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003512 /* OpenSSL version */
3513 /* SSLeay() gives us the version of the library linked against,
3514 which could be different from the headers version.
3515 */
3516 libver = SSLeay();
3517 r = PyLong_FromUnsignedLong(libver);
3518 if (r == NULL)
3519 return NULL;
3520 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3521 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003522 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003523 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3524 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3525 return NULL;
3526 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3527 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3528 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003529
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003530 libver = OPENSSL_VERSION_NUMBER;
3531 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3532 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3533 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3534 return NULL;
3535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003536 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003537}