blob: ff3ef9eeeb198c2dbcda0e391f1aac986777222d [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++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 name = sk_GENERAL_NAME_value(names, j);
812 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 /* we special-case DirName as a tuple of
815 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 t = PyTuple_New(2);
818 if (t == NULL) {
819 goto fail;
820 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 v = PyUnicode_FromString("DirName");
823 if (v == NULL) {
824 Py_DECREF(t);
825 goto fail;
826 }
827 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 v = _create_tuple_for_X509_NAME (name->d.dirn);
830 if (v == NULL) {
831 Py_DECREF(t);
832 goto fail;
833 }
834 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 (void) BIO_reset(biobuf);
841 GENERAL_NAME_print(biobuf, name);
842 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
843 if (len < 0) {
844 _setSSLError(NULL, 0, __FILE__, __LINE__);
845 goto fail;
846 }
847 vptr = strchr(buf, ':');
848 if (vptr == NULL)
849 goto fail;
850 t = PyTuple_New(2);
851 if (t == NULL)
852 goto fail;
853 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
854 if (v == NULL) {
855 Py_DECREF(t);
856 goto fail;
857 }
858 PyTuple_SET_ITEM(t, 0, v);
859 v = PyUnicode_FromStringAndSize((vptr + 1),
860 (len - (vptr - buf + 1)));
861 if (v == NULL) {
862 Py_DECREF(t);
863 goto fail;
864 }
865 PyTuple_SET_ITEM(t, 1, v);
866 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 if (PyList_Append(peer_alt_names, t) < 0) {
871 Py_DECREF(t);
872 goto fail;
873 }
874 Py_DECREF(t);
875 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100876 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 }
878 BIO_free(biobuf);
879 if (peer_alt_names != Py_None) {
880 v = PyList_AsTuple(peer_alt_names);
881 Py_DECREF(peer_alt_names);
882 return v;
883 } else {
884 return peer_alt_names;
885 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000886
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
888 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 if (biobuf != NULL)
890 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 if (peer_alt_names != Py_None) {
893 Py_XDECREF(peer_alt_names);
894 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897}
898
899static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000900_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 PyObject *retval = NULL;
903 BIO *biobuf = NULL;
904 PyObject *peer;
905 PyObject *peer_alt_names = NULL;
906 PyObject *issuer;
907 PyObject *version;
908 PyObject *sn_obj;
909 ASN1_INTEGER *serialNumber;
910 char buf[2048];
911 int len;
912 ASN1_TIME *notBefore, *notAfter;
913 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 retval = PyDict_New();
916 if (retval == NULL)
917 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 peer = _create_tuple_for_X509_NAME(
920 X509_get_subject_name(certificate));
921 if (peer == NULL)
922 goto fail0;
923 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
924 Py_DECREF(peer);
925 goto fail0;
926 }
927 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000928
Antoine Pitroufb046912010-11-09 20:21:19 +0000929 issuer = _create_tuple_for_X509_NAME(
930 X509_get_issuer_name(certificate));
931 if (issuer == NULL)
932 goto fail0;
933 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000935 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000937 Py_DECREF(issuer);
938
939 version = PyLong_FromLong(X509_get_version(certificate) + 1);
940 if (PyDict_SetItemString(retval, "version", version) < 0) {
941 Py_DECREF(version);
942 goto fail0;
943 }
944 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 /* get a memory buffer */
947 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000948
Antoine Pitroufb046912010-11-09 20:21:19 +0000949 (void) BIO_reset(biobuf);
950 serialNumber = X509_get_serialNumber(certificate);
951 /* should not exceed 20 octets, 160 bits, so buf is big enough */
952 i2a_ASN1_INTEGER(biobuf, serialNumber);
953 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
954 if (len < 0) {
955 _setSSLError(NULL, 0, __FILE__, __LINE__);
956 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000958 sn_obj = PyUnicode_FromStringAndSize(buf, len);
959 if (sn_obj == NULL)
960 goto fail1;
961 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
962 Py_DECREF(sn_obj);
963 goto fail1;
964 }
965 Py_DECREF(sn_obj);
966
967 (void) BIO_reset(biobuf);
968 notBefore = X509_get_notBefore(certificate);
969 ASN1_TIME_print(biobuf, notBefore);
970 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
971 if (len < 0) {
972 _setSSLError(NULL, 0, __FILE__, __LINE__);
973 goto fail1;
974 }
975 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
976 if (pnotBefore == NULL)
977 goto fail1;
978 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
979 Py_DECREF(pnotBefore);
980 goto fail1;
981 }
982 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 (void) BIO_reset(biobuf);
985 notAfter = X509_get_notAfter(certificate);
986 ASN1_TIME_print(biobuf, notAfter);
987 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
988 if (len < 0) {
989 _setSSLError(NULL, 0, __FILE__, __LINE__);
990 goto fail1;
991 }
992 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
993 if (pnotAfter == NULL)
994 goto fail1;
995 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
996 Py_DECREF(pnotAfter);
997 goto fail1;
998 }
999 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 peer_alt_names = _get_peer_alt_names(certificate);
1004 if (peer_alt_names == NULL)
1005 goto fail1;
1006 else if (peer_alt_names != Py_None) {
1007 if (PyDict_SetItemString(retval, "subjectAltName",
1008 peer_alt_names) < 0) {
1009 Py_DECREF(peer_alt_names);
1010 goto fail1;
1011 }
1012 Py_DECREF(peer_alt_names);
1013 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 BIO_free(biobuf);
1016 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001017
1018 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 if (biobuf != NULL)
1020 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001021 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 Py_XDECREF(retval);
1023 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001024}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001025
Christian Heimes9a5395a2013-06-17 15:44:12 +02001026static PyObject *
1027_certificate_to_der(X509 *certificate)
1028{
1029 unsigned char *bytes_buf = NULL;
1030 int len;
1031 PyObject *retval;
1032
1033 bytes_buf = NULL;
1034 len = i2d_X509(certificate, &bytes_buf);
1035 if (len < 0) {
1036 _setSSLError(NULL, 0, __FILE__, __LINE__);
1037 return NULL;
1038 }
1039 /* this is actually an immutable bytes sequence */
1040 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1041 OPENSSL_free(bytes_buf);
1042 return retval;
1043}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
1045static PyObject *
1046PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001049 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 X509 *x=NULL;
1051 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitroufb046912010-11-09 20:21:19 +00001053 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1054 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1058 PyErr_SetString(PySSLErrorObject,
1059 "Can't malloc memory to read file");
1060 goto fail0;
1061 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062
Victor Stinner3800e1e2010-05-16 21:23:48 +00001063 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 PyErr_SetString(PySSLErrorObject,
1065 "Can't open file");
1066 goto fail0;
1067 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1070 if (x == NULL) {
1071 PyErr_SetString(PySSLErrorObject,
1072 "Error decoding PEM-encoded file");
1073 goto fail0;
1074 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroufb046912010-11-09 20:21:19 +00001076 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001077 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
1079 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001080 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 if (cert != NULL) BIO_free(cert);
1082 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083}
1084
1085
1086static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001087PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001090 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitrou721738f2012-08-15 23:20:39 +02001092 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 if (!self->peer_cert)
1096 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001097
Antoine Pitrou721738f2012-08-15 23:20:39 +02001098 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001100 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001102 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 if ((verification & SSL_VERIFY_PEER) == 0)
1104 return PyDict_New();
1105 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001106 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108}
1109
1110PyDoc_STRVAR(PySSL_peercert_doc,
1111"peer_certificate([der=False]) -> certificate\n\
1112\n\
1113Returns the certificate for the peer. If no certificate was provided,\n\
1114returns None. If a certificate was provided, but not validated, returns\n\
1115an empty dictionary. Otherwise returns a dict containing information\n\
1116about the peer certificate.\n\
1117\n\
1118If the optional argument is True, returns a DER-encoded copy of the\n\
1119peer certificate, or None if no certificate was provided. This will\n\
1120return the certificate even if it wasn't validated.");
1121
Antoine Pitrou152efa22010-05-16 18:19:27 +00001122static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001125 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 char *cipher_name;
1127 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001130 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 current = SSL_get_current_cipher(self->ssl);
1132 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001133 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 retval = PyTuple_New(3);
1136 if (retval == NULL)
1137 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 cipher_name = (char *) SSL_CIPHER_get_name(current);
1140 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001141 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 PyTuple_SET_ITEM(retval, 0, Py_None);
1143 } else {
1144 v = PyUnicode_FromString(cipher_name);
1145 if (v == NULL)
1146 goto fail0;
1147 PyTuple_SET_ITEM(retval, 0, v);
1148 }
1149 cipher_protocol = SSL_CIPHER_get_version(current);
1150 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001151 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 PyTuple_SET_ITEM(retval, 1, Py_None);
1153 } else {
1154 v = PyUnicode_FromString(cipher_protocol);
1155 if (v == NULL)
1156 goto fail0;
1157 PyTuple_SET_ITEM(retval, 1, v);
1158 }
1159 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1160 if (v == NULL)
1161 goto fail0;
1162 PyTuple_SET_ITEM(retval, 2, v);
1163 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001164
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001165 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 Py_DECREF(retval);
1167 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168}
1169
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001170#ifdef OPENSSL_NPN_NEGOTIATED
1171static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1172 const unsigned char *out;
1173 unsigned int outlen;
1174
Victor Stinner4569cd52013-06-23 14:58:43 +02001175 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001176 &out, &outlen);
1177
1178 if (out == NULL)
1179 Py_RETURN_NONE;
1180 return PyUnicode_FromStringAndSize((char *) out, outlen);
1181}
1182#endif
1183
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001184static PyObject *PySSL_compression(PySSLSocket *self) {
1185#ifdef OPENSSL_NO_COMP
1186 Py_RETURN_NONE;
1187#else
1188 const COMP_METHOD *comp_method;
1189 const char *short_name;
1190
1191 if (self->ssl == NULL)
1192 Py_RETURN_NONE;
1193 comp_method = SSL_get_current_compression(self->ssl);
1194 if (comp_method == NULL || comp_method->type == NID_undef)
1195 Py_RETURN_NONE;
1196 short_name = OBJ_nid2sn(comp_method->type);
1197 if (short_name == NULL)
1198 Py_RETURN_NONE;
1199 return PyUnicode_DecodeFSDefault(short_name);
1200#endif
1201}
1202
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001203static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1204 Py_INCREF(self->ctx);
1205 return self->ctx;
1206}
1207
1208static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1209 void *closure) {
1210
1211 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001212#if !HAVE_SNI
1213 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1214 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001215 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001216#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001217 Py_INCREF(value);
1218 Py_DECREF(self->ctx);
1219 self->ctx = (PySSLContext *) value;
1220 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001221#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001222 } else {
1223 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1224 return -1;
1225 }
1226
1227 return 0;
1228}
1229
1230PyDoc_STRVAR(PySSL_set_context_doc,
1231"_setter_context(ctx)\n\
1232\
1233This changes the context associated with the SSLSocket. This is typically\n\
1234used from within a callback function set by the set_servername_callback\n\
1235on the SSLContext to change the certificate information associated with the\n\
1236SSLSocket before the cryptographic exchange handshake messages\n");
1237
1238
1239
Antoine Pitrou152efa22010-05-16 18:19:27 +00001240static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001241{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 if (self->peer_cert) /* Possible not to have one? */
1243 X509_free (self->peer_cert);
1244 if (self->ssl)
1245 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001247 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001249}
1250
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001251/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001252 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001253 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001254 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001255
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001256static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001257check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001258{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 fd_set fds;
1260 struct timeval tv;
1261 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1264 if (s->sock_timeout < 0.0)
1265 return SOCKET_IS_BLOCKING;
1266 else if (s->sock_timeout == 0.0)
1267 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 /* Guard against closed socket */
1270 if (s->sock_fd < 0)
1271 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 /* Prefer poll, if available, since you can poll() any fd
1274 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001275#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 {
1277 struct pollfd pollfd;
1278 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 pollfd.fd = s->sock_fd;
1281 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 /* s->sock_timeout is in seconds, timeout in ms */
1284 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1285 PySSL_BEGIN_ALLOW_THREADS
1286 rc = poll(&pollfd, 1, timeout);
1287 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 goto normal_return;
1290 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291#endif
1292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001294 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 /* Construct the arguments to select */
1298 tv.tv_sec = (int)s->sock_timeout;
1299 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1300 FD_ZERO(&fds);
1301 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 /* See if the socket is ready */
1304 PySSL_BEGIN_ALLOW_THREADS
1305 if (writing)
1306 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1307 else
1308 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1309 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001310
Bill Janssen6e027db2007-11-15 22:23:56 +00001311#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001312normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001313#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1315 (when we are able to write or when there's something to read) */
1316 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001317}
1318
Antoine Pitrou152efa22010-05-16 18:19:27 +00001319static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001320{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 Py_buffer buf;
1322 int len;
1323 int sockstate;
1324 int err;
1325 int nonblocking;
1326 PySocketSockObject *sock
1327 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 if (((PyObject*)sock) == Py_None) {
1330 _setSSLError("Underlying socket connection gone",
1331 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1332 return NULL;
1333 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001334 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001336 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1337 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340
Victor Stinner6efa9652013-06-25 00:42:31 +02001341 if (buf.len > INT_MAX) {
1342 PyErr_Format(PyExc_OverflowError,
1343 "string longer than %d bytes", INT_MAX);
1344 goto error;
1345 }
1346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 /* just in case the blocking state of the socket has been changed */
1348 nonblocking = (sock->sock_timeout >= 0.0);
1349 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1350 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1351
1352 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1353 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001354 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 "The write operation timed out");
1356 goto error;
1357 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1358 PyErr_SetString(PySSLErrorObject,
1359 "Underlying socket has been closed.");
1360 goto error;
1361 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1362 PyErr_SetString(PySSLErrorObject,
1363 "Underlying socket too large for select().");
1364 goto error;
1365 }
1366 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001368 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 err = SSL_get_error(self->ssl, len);
1370 PySSL_END_ALLOW_THREADS
1371 if (PyErr_CheckSignals()) {
1372 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001373 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001375 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001377 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 } else {
1379 sockstate = SOCKET_OPERATION_OK;
1380 }
1381 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001382 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 "The write operation timed out");
1384 goto error;
1385 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1386 PyErr_SetString(PySSLErrorObject,
1387 "Underlying socket has been closed.");
1388 goto error;
1389 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1390 break;
1391 }
1392 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001393
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001394 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 PyBuffer_Release(&buf);
1396 if (len > 0)
1397 return PyLong_FromLong(len);
1398 else
1399 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001400
1401error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001402 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 PyBuffer_Release(&buf);
1404 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001405}
1406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001407PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001408"write(s) -> len\n\
1409\n\
1410Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001411of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001412
Antoine Pitrou152efa22010-05-16 18:19:27 +00001413static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001414{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 PySSL_BEGIN_ALLOW_THREADS
1418 count = SSL_pending(self->ssl);
1419 PySSL_END_ALLOW_THREADS
1420 if (count < 0)
1421 return PySSL_SetError(self, count, __FILE__, __LINE__);
1422 else
1423 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001424}
1425
1426PyDoc_STRVAR(PySSL_SSLpending_doc,
1427"pending() -> count\n\
1428\n\
1429Returns the number of already decrypted bytes available for read,\n\
1430pending on the connection.\n");
1431
Antoine Pitrou152efa22010-05-16 18:19:27 +00001432static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001433{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 PyObject *dest = NULL;
1435 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001437 int len, count;
1438 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 int sockstate;
1440 int err;
1441 int nonblocking;
1442 PySocketSockObject *sock
1443 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 if (((PyObject*)sock) == Py_None) {
1446 _setSSLError("Underlying socket connection gone",
1447 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1448 return NULL;
1449 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001450 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001452 buf.obj = NULL;
1453 buf.buf = NULL;
1454 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001455 goto error;
1456
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001457 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1458 dest = PyBytes_FromStringAndSize(NULL, len);
1459 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001460 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001461 mem = PyBytes_AS_STRING(dest);
1462 }
1463 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001465 mem = buf.buf;
1466 if (len <= 0 || len > buf.len) {
1467 len = (int) buf.len;
1468 if (buf.len != len) {
1469 PyErr_SetString(PyExc_OverflowError,
1470 "maximum length can't fit in a C 'int'");
1471 goto error;
1472 }
1473 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001474 }
1475
1476 /* just in case the blocking state of the socket has been changed */
1477 nonblocking = (sock->sock_timeout >= 0.0);
1478 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1479 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1480
1481 /* first check if there are bytes ready to be read */
1482 PySSL_BEGIN_ALLOW_THREADS
1483 count = SSL_pending(self->ssl);
1484 PySSL_END_ALLOW_THREADS
1485
1486 if (!count) {
1487 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1488 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001489 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 "The read operation timed out");
1491 goto error;
1492 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1493 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001494 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 goto error;
1496 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1497 count = 0;
1498 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001499 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 }
1501 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 PySSL_BEGIN_ALLOW_THREADS
1503 count = SSL_read(self->ssl, mem, len);
1504 err = SSL_get_error(self->ssl, count);
1505 PySSL_END_ALLOW_THREADS
1506 if (PyErr_CheckSignals())
1507 goto error;
1508 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001509 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001511 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1513 (SSL_get_shutdown(self->ssl) ==
1514 SSL_RECEIVED_SHUTDOWN))
1515 {
1516 count = 0;
1517 goto done;
1518 } else {
1519 sockstate = SOCKET_OPERATION_OK;
1520 }
1521 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001522 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 "The read operation timed out");
1524 goto error;
1525 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1526 break;
1527 }
1528 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1529 if (count <= 0) {
1530 PySSL_SetError(self, count, __FILE__, __LINE__);
1531 goto error;
1532 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001533
1534done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001535 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001537 _PyBytes_Resize(&dest, count);
1538 return dest;
1539 }
1540 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyBuffer_Release(&buf);
1542 return PyLong_FromLong(count);
1543 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001544
1545error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001546 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001547 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001548 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001549 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001552}
1553
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001555"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001556\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001557Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001558
Antoine Pitrou152efa22010-05-16 18:19:27 +00001559static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001560{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 int err, ssl_err, sockstate, nonblocking;
1562 int zeros = 0;
1563 PySocketSockObject *sock
1564 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 /* Guard against closed socket */
1567 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1568 _setSSLError("Underlying socket connection gone",
1569 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1570 return NULL;
1571 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001572 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573
1574 /* Just in case the blocking state of the socket has been changed */
1575 nonblocking = (sock->sock_timeout >= 0.0);
1576 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1577 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1578
1579 while (1) {
1580 PySSL_BEGIN_ALLOW_THREADS
1581 /* Disable read-ahead so that unwrap can work correctly.
1582 * Otherwise OpenSSL might read in too much data,
1583 * eating clear text data that happens to be
1584 * transmitted after the SSL shutdown.
1585 * Should be safe to call repeatedly everytime this
1586 * function is used and the shutdown_seen_zero != 0
1587 * condition is met.
1588 */
1589 if (self->shutdown_seen_zero)
1590 SSL_set_read_ahead(self->ssl, 0);
1591 err = SSL_shutdown(self->ssl);
1592 PySSL_END_ALLOW_THREADS
1593 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1594 if (err > 0)
1595 break;
1596 if (err == 0) {
1597 /* Don't loop endlessly; instead preserve legacy
1598 behaviour of trying SSL_shutdown() only twice.
1599 This looks necessary for OpenSSL < 0.9.8m */
1600 if (++zeros > 1)
1601 break;
1602 /* Shutdown was sent, now try receiving */
1603 self->shutdown_seen_zero = 1;
1604 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001605 }
1606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 /* Possibly retry shutdown until timeout or failure */
1608 ssl_err = SSL_get_error(self->ssl, err);
1609 if (ssl_err == SSL_ERROR_WANT_READ)
1610 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1611 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1612 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1613 else
1614 break;
1615 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1616 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001617 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 "The read operation timed out");
1619 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001620 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001622 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 }
1624 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1625 PyErr_SetString(PySSLErrorObject,
1626 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001627 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 }
1629 else if (sockstate != SOCKET_OPERATION_OK)
1630 /* Retain the SSL error code */
1631 break;
1632 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001633
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001634 if (err < 0) {
1635 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001637 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001638 else
1639 /* It's already INCREF'ed */
1640 return (PyObject *) sock;
1641
1642error:
1643 Py_DECREF(sock);
1644 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001645}
1646
1647PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1648"shutdown(s) -> socket\n\
1649\n\
1650Does the SSL shutdown handshake with the remote end, and returns\n\
1651the underlying socket object.");
1652
Antoine Pitroud6494802011-07-21 01:11:30 +02001653#if HAVE_OPENSSL_FINISHED
1654static PyObject *
1655PySSL_tls_unique_cb(PySSLSocket *self)
1656{
1657 PyObject *retval = NULL;
1658 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001659 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001660
1661 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1662 /* if session is resumed XOR we are the client */
1663 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1664 }
1665 else {
1666 /* if a new session XOR we are the server */
1667 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1668 }
1669
1670 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001671 if (len == 0)
1672 Py_RETURN_NONE;
1673
1674 retval = PyBytes_FromStringAndSize(buf, len);
1675
1676 return retval;
1677}
1678
1679PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1680"tls_unique_cb() -> bytes\n\
1681\n\
1682Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1683\n\
1684If the TLS handshake is not yet complete, None is returned");
1685
1686#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001687
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001688static PyGetSetDef ssl_getsetlist[] = {
1689 {"context", (getter) PySSL_get_context,
1690 (setter) PySSL_set_context, PySSL_set_context_doc},
1691 {NULL}, /* sentinel */
1692};
1693
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001694static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1696 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1697 PySSL_SSLwrite_doc},
1698 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1699 PySSL_SSLread_doc},
1700 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1701 PySSL_SSLpending_doc},
1702 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1703 PySSL_peercert_doc},
1704 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001705#ifdef OPENSSL_NPN_NEGOTIATED
1706 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1707#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001708 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1710 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001711#if HAVE_OPENSSL_FINISHED
1712 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1713 PySSL_tls_unique_cb_doc},
1714#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001716};
1717
Antoine Pitrou152efa22010-05-16 18:19:27 +00001718static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001720 "_ssl._SSLSocket", /*tp_name*/
1721 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 0, /*tp_itemsize*/
1723 /* methods */
1724 (destructor)PySSL_dealloc, /*tp_dealloc*/
1725 0, /*tp_print*/
1726 0, /*tp_getattr*/
1727 0, /*tp_setattr*/
1728 0, /*tp_reserved*/
1729 0, /*tp_repr*/
1730 0, /*tp_as_number*/
1731 0, /*tp_as_sequence*/
1732 0, /*tp_as_mapping*/
1733 0, /*tp_hash*/
1734 0, /*tp_call*/
1735 0, /*tp_str*/
1736 0, /*tp_getattro*/
1737 0, /*tp_setattro*/
1738 0, /*tp_as_buffer*/
1739 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1740 0, /*tp_doc*/
1741 0, /*tp_traverse*/
1742 0, /*tp_clear*/
1743 0, /*tp_richcompare*/
1744 0, /*tp_weaklistoffset*/
1745 0, /*tp_iter*/
1746 0, /*tp_iternext*/
1747 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001748 0, /*tp_members*/
1749 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750};
1751
Antoine Pitrou152efa22010-05-16 18:19:27 +00001752
1753/*
1754 * _SSLContext objects
1755 */
1756
1757static PyObject *
1758context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1759{
1760 char *kwlist[] = {"protocol", NULL};
1761 PySSLContext *self;
1762 int proto_version = PY_SSL_VERSION_SSL23;
1763 SSL_CTX *ctx = NULL;
1764
1765 if (!PyArg_ParseTupleAndKeywords(
1766 args, kwds, "i:_SSLContext", kwlist,
1767 &proto_version))
1768 return NULL;
1769
1770 PySSL_BEGIN_ALLOW_THREADS
1771 if (proto_version == PY_SSL_VERSION_TLS1)
1772 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001773#if HAVE_TLSv1_2
1774 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1775 ctx = SSL_CTX_new(TLSv1_1_method());
1776 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1777 ctx = SSL_CTX_new(TLSv1_2_method());
1778#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001779 else if (proto_version == PY_SSL_VERSION_SSL3)
1780 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001781#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001782 else if (proto_version == PY_SSL_VERSION_SSL2)
1783 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001784#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001785 else if (proto_version == PY_SSL_VERSION_SSL23)
1786 ctx = SSL_CTX_new(SSLv23_method());
1787 else
1788 proto_version = -1;
1789 PySSL_END_ALLOW_THREADS
1790
1791 if (proto_version == -1) {
1792 PyErr_SetString(PyExc_ValueError,
1793 "invalid protocol version");
1794 return NULL;
1795 }
1796 if (ctx == NULL) {
1797 PyErr_SetString(PySSLErrorObject,
1798 "failed to allocate SSL context");
1799 return NULL;
1800 }
1801
1802 assert(type != NULL && type->tp_alloc != NULL);
1803 self = (PySSLContext *) type->tp_alloc(type, 0);
1804 if (self == NULL) {
1805 SSL_CTX_free(ctx);
1806 return NULL;
1807 }
1808 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001809#ifdef OPENSSL_NPN_NEGOTIATED
1810 self->npn_protocols = NULL;
1811#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001812#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001813 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001814#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001815 /* Defaults */
1816 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001817 SSL_CTX_set_options(self->ctx,
1818 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001819
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001820#define SID_CTX "Python"
1821 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1822 sizeof(SID_CTX));
1823#undef SID_CTX
1824
Antoine Pitrou152efa22010-05-16 18:19:27 +00001825 return (PyObject *)self;
1826}
1827
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001828static int
1829context_traverse(PySSLContext *self, visitproc visit, void *arg)
1830{
1831#ifndef OPENSSL_NO_TLSEXT
1832 Py_VISIT(self->set_hostname);
1833#endif
1834 return 0;
1835}
1836
1837static int
1838context_clear(PySSLContext *self)
1839{
1840#ifndef OPENSSL_NO_TLSEXT
1841 Py_CLEAR(self->set_hostname);
1842#endif
1843 return 0;
1844}
1845
Antoine Pitrou152efa22010-05-16 18:19:27 +00001846static void
1847context_dealloc(PySSLContext *self)
1848{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001849 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001850 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001851#ifdef OPENSSL_NPN_NEGOTIATED
1852 PyMem_Free(self->npn_protocols);
1853#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001854 Py_TYPE(self)->tp_free(self);
1855}
1856
1857static PyObject *
1858set_ciphers(PySSLContext *self, PyObject *args)
1859{
1860 int ret;
1861 const char *cipherlist;
1862
1863 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1864 return NULL;
1865 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1866 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001867 /* Clearing the error queue is necessary on some OpenSSL versions,
1868 otherwise the error will be reported again when another SSL call
1869 is done. */
1870 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001871 PyErr_SetString(PySSLErrorObject,
1872 "No cipher can be selected.");
1873 return NULL;
1874 }
1875 Py_RETURN_NONE;
1876}
1877
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001878#ifdef OPENSSL_NPN_NEGOTIATED
1879/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1880static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001881_advertiseNPN_cb(SSL *s,
1882 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001883 void *args)
1884{
1885 PySSLContext *ssl_ctx = (PySSLContext *) args;
1886
1887 if (ssl_ctx->npn_protocols == NULL) {
1888 *data = (unsigned char *) "";
1889 *len = 0;
1890 } else {
1891 *data = (unsigned char *) ssl_ctx->npn_protocols;
1892 *len = ssl_ctx->npn_protocols_len;
1893 }
1894
1895 return SSL_TLSEXT_ERR_OK;
1896}
1897/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1898static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001899_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001900 unsigned char **out, unsigned char *outlen,
1901 const unsigned char *server, unsigned int server_len,
1902 void *args)
1903{
1904 PySSLContext *ssl_ctx = (PySSLContext *) args;
1905
1906 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1907 int client_len;
1908
1909 if (client == NULL) {
1910 client = (unsigned char *) "";
1911 client_len = 0;
1912 } else {
1913 client_len = ssl_ctx->npn_protocols_len;
1914 }
1915
1916 SSL_select_next_proto(out, outlen,
1917 server, server_len,
1918 client, client_len);
1919
1920 return SSL_TLSEXT_ERR_OK;
1921}
1922#endif
1923
1924static PyObject *
1925_set_npn_protocols(PySSLContext *self, PyObject *args)
1926{
1927#ifdef OPENSSL_NPN_NEGOTIATED
1928 Py_buffer protos;
1929
1930 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1931 return NULL;
1932
Christian Heimes5cb31c92012-09-20 12:42:54 +02001933 if (self->npn_protocols != NULL) {
1934 PyMem_Free(self->npn_protocols);
1935 }
1936
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001937 self->npn_protocols = PyMem_Malloc(protos.len);
1938 if (self->npn_protocols == NULL) {
1939 PyBuffer_Release(&protos);
1940 return PyErr_NoMemory();
1941 }
1942 memcpy(self->npn_protocols, protos.buf, protos.len);
1943 self->npn_protocols_len = (int) protos.len;
1944
1945 /* set both server and client callbacks, because the context can
1946 * be used to create both types of sockets */
1947 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1948 _advertiseNPN_cb,
1949 self);
1950 SSL_CTX_set_next_proto_select_cb(self->ctx,
1951 _selectNPN_cb,
1952 self);
1953
1954 PyBuffer_Release(&protos);
1955 Py_RETURN_NONE;
1956#else
1957 PyErr_SetString(PyExc_NotImplementedError,
1958 "The NPN extension requires OpenSSL 1.0.1 or later.");
1959 return NULL;
1960#endif
1961}
1962
Antoine Pitrou152efa22010-05-16 18:19:27 +00001963static PyObject *
1964get_verify_mode(PySSLContext *self, void *c)
1965{
1966 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1967 case SSL_VERIFY_NONE:
1968 return PyLong_FromLong(PY_SSL_CERT_NONE);
1969 case SSL_VERIFY_PEER:
1970 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1971 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1972 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1973 }
1974 PyErr_SetString(PySSLErrorObject,
1975 "invalid return value from SSL_CTX_get_verify_mode");
1976 return NULL;
1977}
1978
1979static int
1980set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1981{
1982 int n, mode;
1983 if (!PyArg_Parse(arg, "i", &n))
1984 return -1;
1985 if (n == PY_SSL_CERT_NONE)
1986 mode = SSL_VERIFY_NONE;
1987 else if (n == PY_SSL_CERT_OPTIONAL)
1988 mode = SSL_VERIFY_PEER;
1989 else if (n == PY_SSL_CERT_REQUIRED)
1990 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1991 else {
1992 PyErr_SetString(PyExc_ValueError,
1993 "invalid value for verify_mode");
1994 return -1;
1995 }
1996 SSL_CTX_set_verify(self->ctx, mode, NULL);
1997 return 0;
1998}
1999
2000static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002001get_options(PySSLContext *self, void *c)
2002{
2003 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2004}
2005
2006static int
2007set_options(PySSLContext *self, PyObject *arg, void *c)
2008{
2009 long new_opts, opts, set, clear;
2010 if (!PyArg_Parse(arg, "l", &new_opts))
2011 return -1;
2012 opts = SSL_CTX_get_options(self->ctx);
2013 clear = opts & ~new_opts;
2014 set = ~opts & new_opts;
2015 if (clear) {
2016#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2017 SSL_CTX_clear_options(self->ctx, clear);
2018#else
2019 PyErr_SetString(PyExc_ValueError,
2020 "can't clear options before OpenSSL 0.9.8m");
2021 return -1;
2022#endif
2023 }
2024 if (set)
2025 SSL_CTX_set_options(self->ctx, set);
2026 return 0;
2027}
2028
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002029typedef struct {
2030 PyThreadState *thread_state;
2031 PyObject *callable;
2032 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002033 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002034 int error;
2035} _PySSLPasswordInfo;
2036
2037static int
2038_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2039 const char *bad_type_error)
2040{
2041 /* Set the password and size fields of a _PySSLPasswordInfo struct
2042 from a unicode, bytes, or byte array object.
2043 The password field will be dynamically allocated and must be freed
2044 by the caller */
2045 PyObject *password_bytes = NULL;
2046 const char *data = NULL;
2047 Py_ssize_t size;
2048
2049 if (PyUnicode_Check(password)) {
2050 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2051 if (!password_bytes) {
2052 goto error;
2053 }
2054 data = PyBytes_AS_STRING(password_bytes);
2055 size = PyBytes_GET_SIZE(password_bytes);
2056 } else if (PyBytes_Check(password)) {
2057 data = PyBytes_AS_STRING(password);
2058 size = PyBytes_GET_SIZE(password);
2059 } else if (PyByteArray_Check(password)) {
2060 data = PyByteArray_AS_STRING(password);
2061 size = PyByteArray_GET_SIZE(password);
2062 } else {
2063 PyErr_SetString(PyExc_TypeError, bad_type_error);
2064 goto error;
2065 }
2066
Victor Stinner9ee02032013-06-23 15:08:23 +02002067 if (size > (Py_ssize_t)INT_MAX) {
2068 PyErr_Format(PyExc_ValueError,
2069 "password cannot be longer than %d bytes", INT_MAX);
2070 goto error;
2071 }
2072
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002073 free(pw_info->password);
2074 pw_info->password = malloc(size);
2075 if (!pw_info->password) {
2076 PyErr_SetString(PyExc_MemoryError,
2077 "unable to allocate password buffer");
2078 goto error;
2079 }
2080 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002081 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002082
2083 Py_XDECREF(password_bytes);
2084 return 1;
2085
2086error:
2087 Py_XDECREF(password_bytes);
2088 return 0;
2089}
2090
2091static int
2092_password_callback(char *buf, int size, int rwflag, void *userdata)
2093{
2094 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2095 PyObject *fn_ret = NULL;
2096
2097 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2098
2099 if (pw_info->callable) {
2100 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2101 if (!fn_ret) {
2102 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2103 core python API, so we could use it to add a frame here */
2104 goto error;
2105 }
2106
2107 if (!_pwinfo_set(pw_info, fn_ret,
2108 "password callback must return a string")) {
2109 goto error;
2110 }
2111 Py_CLEAR(fn_ret);
2112 }
2113
2114 if (pw_info->size > size) {
2115 PyErr_Format(PyExc_ValueError,
2116 "password cannot be longer than %d bytes", size);
2117 goto error;
2118 }
2119
2120 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2121 memcpy(buf, pw_info->password, pw_info->size);
2122 return pw_info->size;
2123
2124error:
2125 Py_XDECREF(fn_ret);
2126 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2127 pw_info->error = 1;
2128 return -1;
2129}
2130
Antoine Pitroub5218772010-05-21 09:56:06 +00002131static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002132load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2133{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002134 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2135 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002137 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2138 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2139 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140 int r;
2141
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002142 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002143 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002144 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002145 "O|OO:load_cert_chain", kwlist,
2146 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002147 return NULL;
2148 if (keyfile == Py_None)
2149 keyfile = NULL;
2150 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2151 PyErr_SetString(PyExc_TypeError,
2152 "certfile should be a valid filesystem path");
2153 return NULL;
2154 }
2155 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2156 PyErr_SetString(PyExc_TypeError,
2157 "keyfile should be a valid filesystem path");
2158 goto error;
2159 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002160 if (password && password != Py_None) {
2161 if (PyCallable_Check(password)) {
2162 pw_info.callable = password;
2163 } else if (!_pwinfo_set(&pw_info, password,
2164 "password should be a string or callable")) {
2165 goto error;
2166 }
2167 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2168 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2169 }
2170 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002171 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2172 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002173 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002174 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002175 if (pw_info.error) {
2176 ERR_clear_error();
2177 /* the password callback has already set the error information */
2178 }
2179 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002180 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002181 PyErr_SetFromErrno(PyExc_IOError);
2182 }
2183 else {
2184 _setSSLError(NULL, 0, __FILE__, __LINE__);
2185 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002186 goto error;
2187 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002188 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002189 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002190 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2191 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002192 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2193 Py_CLEAR(keyfile_bytes);
2194 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002195 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002196 if (pw_info.error) {
2197 ERR_clear_error();
2198 /* the password callback has already set the error information */
2199 }
2200 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002201 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002202 PyErr_SetFromErrno(PyExc_IOError);
2203 }
2204 else {
2205 _setSSLError(NULL, 0, __FILE__, __LINE__);
2206 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002207 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002208 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002209 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002211 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 if (r != 1) {
2213 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002214 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002215 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002216 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2217 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2218 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002219 Py_RETURN_NONE;
2220
2221error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002222 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2223 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2224 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002225 Py_XDECREF(keyfile_bytes);
2226 Py_XDECREF(certfile_bytes);
2227 return NULL;
2228}
2229
2230static PyObject *
2231load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2232{
2233 char *kwlist[] = {"cafile", "capath", NULL};
2234 PyObject *cafile = NULL, *capath = NULL;
2235 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2236 const char *cafile_buf = NULL, *capath_buf = NULL;
2237 int r;
2238
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002239 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002240 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2241 "|OO:load_verify_locations", kwlist,
2242 &cafile, &capath))
2243 return NULL;
2244 if (cafile == Py_None)
2245 cafile = NULL;
2246 if (capath == Py_None)
2247 capath = NULL;
2248 if (cafile == NULL && capath == NULL) {
2249 PyErr_SetString(PyExc_TypeError,
2250 "cafile and capath cannot be both omitted");
2251 return NULL;
2252 }
2253 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2254 PyErr_SetString(PyExc_TypeError,
2255 "cafile should be a valid filesystem path");
2256 return NULL;
2257 }
2258 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002259 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002260 PyErr_SetString(PyExc_TypeError,
2261 "capath should be a valid filesystem path");
2262 return NULL;
2263 }
2264 if (cafile)
2265 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2266 if (capath)
2267 capath_buf = PyBytes_AS_STRING(capath_bytes);
2268 PySSL_BEGIN_ALLOW_THREADS
2269 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2270 PySSL_END_ALLOW_THREADS
2271 Py_XDECREF(cafile_bytes);
2272 Py_XDECREF(capath_bytes);
2273 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002274 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002275 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002276 PyErr_SetFromErrno(PyExc_IOError);
2277 }
2278 else {
2279 _setSSLError(NULL, 0, __FILE__, __LINE__);
2280 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002281 return NULL;
2282 }
2283 Py_RETURN_NONE;
2284}
2285
2286static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002287load_dh_params(PySSLContext *self, PyObject *filepath)
2288{
2289 FILE *f;
2290 DH *dh;
2291
2292 f = _Py_fopen(filepath, "rb");
2293 if (f == NULL) {
2294 if (!PyErr_Occurred())
2295 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2296 return NULL;
2297 }
2298 errno = 0;
2299 PySSL_BEGIN_ALLOW_THREADS
2300 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002301 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002302 PySSL_END_ALLOW_THREADS
2303 if (dh == NULL) {
2304 if (errno != 0) {
2305 ERR_clear_error();
2306 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2307 }
2308 else {
2309 _setSSLError(NULL, 0, __FILE__, __LINE__);
2310 }
2311 return NULL;
2312 }
2313 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2314 _setSSLError(NULL, 0, __FILE__, __LINE__);
2315 DH_free(dh);
2316 Py_RETURN_NONE;
2317}
2318
2319static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002320context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2321{
Antoine Pitroud5323212010-10-22 18:19:07 +00002322 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002323 PySocketSockObject *sock;
2324 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002325 char *hostname = NULL;
2326 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002327
Antoine Pitroud5323212010-10-22 18:19:07 +00002328 /* server_hostname is either None (or absent), or to be encoded
2329 using the idna encoding. */
2330 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002332 &sock, &server_side,
2333 Py_TYPE(Py_None), &hostname_obj)) {
2334 PyErr_Clear();
2335 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2336 PySocketModule.Sock_Type,
2337 &sock, &server_side,
2338 "idna", &hostname))
2339 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002340#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002341 PyMem_Free(hostname);
2342 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2343 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002344 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002345#endif
2346 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002347
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002348 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002349 hostname);
2350 if (hostname != NULL)
2351 PyMem_Free(hostname);
2352 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002353}
2354
Antoine Pitroub0182c82010-10-12 20:09:02 +00002355static PyObject *
2356session_stats(PySSLContext *self, PyObject *unused)
2357{
2358 int r;
2359 PyObject *value, *stats = PyDict_New();
2360 if (!stats)
2361 return NULL;
2362
2363#define ADD_STATS(SSL_NAME, KEY_NAME) \
2364 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2365 if (value == NULL) \
2366 goto error; \
2367 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2368 Py_DECREF(value); \
2369 if (r < 0) \
2370 goto error;
2371
2372 ADD_STATS(number, "number");
2373 ADD_STATS(connect, "connect");
2374 ADD_STATS(connect_good, "connect_good");
2375 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2376 ADD_STATS(accept, "accept");
2377 ADD_STATS(accept_good, "accept_good");
2378 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2379 ADD_STATS(accept, "accept");
2380 ADD_STATS(hits, "hits");
2381 ADD_STATS(misses, "misses");
2382 ADD_STATS(timeouts, "timeouts");
2383 ADD_STATS(cache_full, "cache_full");
2384
2385#undef ADD_STATS
2386
2387 return stats;
2388
2389error:
2390 Py_DECREF(stats);
2391 return NULL;
2392}
2393
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002394static PyObject *
2395set_default_verify_paths(PySSLContext *self, PyObject *unused)
2396{
2397 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2398 _setSSLError(NULL, 0, __FILE__, __LINE__);
2399 return NULL;
2400 }
2401 Py_RETURN_NONE;
2402}
2403
Antoine Pitrou501da612011-12-21 09:27:41 +01002404#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002405static PyObject *
2406set_ecdh_curve(PySSLContext *self, PyObject *name)
2407{
2408 PyObject *name_bytes;
2409 int nid;
2410 EC_KEY *key;
2411
2412 if (!PyUnicode_FSConverter(name, &name_bytes))
2413 return NULL;
2414 assert(PyBytes_Check(name_bytes));
2415 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2416 Py_DECREF(name_bytes);
2417 if (nid == 0) {
2418 PyErr_Format(PyExc_ValueError,
2419 "unknown elliptic curve name %R", name);
2420 return NULL;
2421 }
2422 key = EC_KEY_new_by_curve_name(nid);
2423 if (key == NULL) {
2424 _setSSLError(NULL, 0, __FILE__, __LINE__);
2425 return NULL;
2426 }
2427 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2428 EC_KEY_free(key);
2429 Py_RETURN_NONE;
2430}
Antoine Pitrou501da612011-12-21 09:27:41 +01002431#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002432
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002433#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002434static int
2435_servername_callback(SSL *s, int *al, void *args)
2436{
2437 int ret;
2438 PySSLContext *ssl_ctx = (PySSLContext *) args;
2439 PySSLSocket *ssl;
2440 PyObject *servername_o;
2441 PyObject *servername_idna;
2442 PyObject *result;
2443 /* The high-level ssl.SSLSocket object */
2444 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002445 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002446#ifdef WITH_THREAD
2447 PyGILState_STATE gstate = PyGILState_Ensure();
2448#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002449
2450 if (ssl_ctx->set_hostname == NULL) {
2451 /* remove race condition in this the call back while if removing the
2452 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002453#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002454 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002455#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002456 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002457 }
2458
2459 ssl = SSL_get_app_data(s);
2460 assert(PySSLSocket_Check(ssl));
2461 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2462 Py_INCREF(ssl_socket);
2463 if (ssl_socket == Py_None) {
2464 goto error;
2465 }
Victor Stinner7e001512013-06-25 00:44:31 +02002466
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002467 if (servername == NULL) {
2468 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2469 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002470 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002471 else {
2472 servername_o = PyBytes_FromString(servername);
2473 if (servername_o == NULL) {
2474 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2475 goto error;
2476 }
2477 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2478 if (servername_idna == NULL) {
2479 PyErr_WriteUnraisable(servername_o);
2480 Py_DECREF(servername_o);
2481 goto error;
2482 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002483 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002484 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2485 servername_idna, ssl_ctx, NULL);
2486 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002487 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002488 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002489
2490 if (result == NULL) {
2491 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2492 *al = SSL_AD_HANDSHAKE_FAILURE;
2493 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2494 }
2495 else {
2496 if (result != Py_None) {
2497 *al = (int) PyLong_AsLong(result);
2498 if (PyErr_Occurred()) {
2499 PyErr_WriteUnraisable(result);
2500 *al = SSL_AD_INTERNAL_ERROR;
2501 }
2502 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2503 }
2504 else {
2505 ret = SSL_TLSEXT_ERR_OK;
2506 }
2507 Py_DECREF(result);
2508 }
2509
Stefan Krah20d60802013-01-17 17:07:17 +01002510#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002511 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002512#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002513 return ret;
2514
2515error:
2516 Py_DECREF(ssl_socket);
2517 *al = SSL_AD_INTERNAL_ERROR;
2518 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002519#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002520 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002521#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002522 return ret;
2523}
Antoine Pitroua5963382013-03-30 16:39:00 +01002524#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002525
2526PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2527"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002528\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002529This sets a callback that will be called when a server name is provided by\n\
2530the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002531\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002532If the argument is None then the callback is disabled. The method is called\n\
2533with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002534See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002535
2536static PyObject *
2537set_servername_callback(PySSLContext *self, PyObject *args)
2538{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002539#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002540 PyObject *cb;
2541
2542 if (!PyArg_ParseTuple(args, "O", &cb))
2543 return NULL;
2544
2545 Py_CLEAR(self->set_hostname);
2546 if (cb == Py_None) {
2547 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2548 }
2549 else {
2550 if (!PyCallable_Check(cb)) {
2551 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2552 PyErr_SetString(PyExc_TypeError,
2553 "not a callable object");
2554 return NULL;
2555 }
2556 Py_INCREF(cb);
2557 self->set_hostname = cb;
2558 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2559 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2560 }
2561 Py_RETURN_NONE;
2562#else
2563 PyErr_SetString(PyExc_NotImplementedError,
2564 "The TLS extension servername callback, "
2565 "SSL_CTX_set_tlsext_servername_callback, "
2566 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002567 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002568#endif
2569}
2570
Christian Heimes9a5395a2013-06-17 15:44:12 +02002571PyDoc_STRVAR(PySSL_get_stats_doc,
2572"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2573\n\
2574Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2575CA extension and certificate revocation lists inside the context's cert\n\
2576store.\n\
2577NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2578been used at least once.");
2579
2580static PyObject *
2581cert_store_stats(PySSLContext *self)
2582{
2583 X509_STORE *store;
2584 X509_OBJECT *obj;
2585 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2586
2587 store = SSL_CTX_get_cert_store(self->ctx);
2588 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2589 obj = sk_X509_OBJECT_value(store->objs, i);
2590 switch (obj->type) {
2591 case X509_LU_X509:
2592 x509++;
2593 if (X509_check_ca(obj->data.x509)) {
2594 ca++;
2595 }
2596 break;
2597 case X509_LU_CRL:
2598 crl++;
2599 break;
2600 case X509_LU_PKEY:
2601 pkey++;
2602 break;
2603 default:
2604 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2605 * As far as I can tell they are internal states and never
2606 * stored in a cert store */
2607 break;
2608 }
2609 }
2610 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2611 "x509_ca", ca);
2612}
2613
2614PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2615"get_ca_certs([der=False]) -> list of loaded certificate\n\
2616\n\
2617Returns a list of dicts with information of loaded CA certs. If the\n\
2618optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2619NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2620been used at least once.");
2621
2622static PyObject *
2623get_ca_certs(PySSLContext *self, PyObject *args)
2624{
2625 X509_STORE *store;
2626 PyObject *ci = NULL, *rlist = NULL;
2627 int i;
2628 int binary_mode = 0;
2629
2630 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2631 return NULL;
2632 }
2633
2634 if ((rlist = PyList_New(0)) == NULL) {
2635 return NULL;
2636 }
2637
2638 store = SSL_CTX_get_cert_store(self->ctx);
2639 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2640 X509_OBJECT *obj;
2641 X509 *cert;
2642
2643 obj = sk_X509_OBJECT_value(store->objs, i);
2644 if (obj->type != X509_LU_X509) {
2645 /* not a x509 cert */
2646 continue;
2647 }
2648 /* CA for any purpose */
2649 cert = obj->data.x509;
2650 if (!X509_check_ca(cert)) {
2651 continue;
2652 }
2653 if (binary_mode) {
2654 ci = _certificate_to_der(cert);
2655 } else {
2656 ci = _decode_certificate(cert);
2657 }
2658 if (ci == NULL) {
2659 goto error;
2660 }
2661 if (PyList_Append(rlist, ci) == -1) {
2662 goto error;
2663 }
2664 Py_CLEAR(ci);
2665 }
2666 return rlist;
2667
2668 error:
2669 Py_XDECREF(ci);
2670 Py_XDECREF(rlist);
2671 return NULL;
2672}
2673
2674
Antoine Pitrou152efa22010-05-16 18:19:27 +00002675static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002676 {"options", (getter) get_options,
2677 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002678 {"verify_mode", (getter) get_verify_mode,
2679 (setter) set_verify_mode, NULL},
2680 {NULL}, /* sentinel */
2681};
2682
2683static struct PyMethodDef context_methods[] = {
2684 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2685 METH_VARARGS | METH_KEYWORDS, NULL},
2686 {"set_ciphers", (PyCFunction) set_ciphers,
2687 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002688 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2689 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002690 {"load_cert_chain", (PyCFunction) load_cert_chain,
2691 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002692 {"load_dh_params", (PyCFunction) load_dh_params,
2693 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002694 {"load_verify_locations", (PyCFunction) load_verify_locations,
2695 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002696 {"session_stats", (PyCFunction) session_stats,
2697 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002698 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2699 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002700#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002701 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2702 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002703#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002704 {"set_servername_callback", (PyCFunction) set_servername_callback,
2705 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002706 {"cert_store_stats", (PyCFunction) cert_store_stats,
2707 METH_NOARGS, PySSL_get_stats_doc},
2708 {"get_ca_certs", (PyCFunction) get_ca_certs,
2709 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002710 {NULL, NULL} /* sentinel */
2711};
2712
2713static PyTypeObject PySSLContext_Type = {
2714 PyVarObject_HEAD_INIT(NULL, 0)
2715 "_ssl._SSLContext", /*tp_name*/
2716 sizeof(PySSLContext), /*tp_basicsize*/
2717 0, /*tp_itemsize*/
2718 (destructor)context_dealloc, /*tp_dealloc*/
2719 0, /*tp_print*/
2720 0, /*tp_getattr*/
2721 0, /*tp_setattr*/
2722 0, /*tp_reserved*/
2723 0, /*tp_repr*/
2724 0, /*tp_as_number*/
2725 0, /*tp_as_sequence*/
2726 0, /*tp_as_mapping*/
2727 0, /*tp_hash*/
2728 0, /*tp_call*/
2729 0, /*tp_str*/
2730 0, /*tp_getattro*/
2731 0, /*tp_setattro*/
2732 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002735 (traverseproc) context_traverse, /*tp_traverse*/
2736 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002737 0, /*tp_richcompare*/
2738 0, /*tp_weaklistoffset*/
2739 0, /*tp_iter*/
2740 0, /*tp_iternext*/
2741 context_methods, /*tp_methods*/
2742 0, /*tp_members*/
2743 context_getsetlist, /*tp_getset*/
2744 0, /*tp_base*/
2745 0, /*tp_dict*/
2746 0, /*tp_descr_get*/
2747 0, /*tp_descr_set*/
2748 0, /*tp_dictoffset*/
2749 0, /*tp_init*/
2750 0, /*tp_alloc*/
2751 context_new, /*tp_new*/
2752};
2753
2754
2755
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002756#ifdef HAVE_OPENSSL_RAND
2757
2758/* helper routines for seeding the SSL PRNG */
2759static PyObject *
2760PySSL_RAND_add(PyObject *self, PyObject *args)
2761{
2762 char *buf;
2763 int len;
2764 double entropy;
2765
2766 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002767 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002768 RAND_add(buf, len, entropy);
2769 Py_INCREF(Py_None);
2770 return Py_None;
2771}
2772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002773PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002774"RAND_add(string, entropy)\n\
2775\n\
2776Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002777bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002778
2779static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002780PySSL_RAND(int len, int pseudo)
2781{
2782 int ok;
2783 PyObject *bytes;
2784 unsigned long err;
2785 const char *errstr;
2786 PyObject *v;
2787
2788 bytes = PyBytes_FromStringAndSize(NULL, len);
2789 if (bytes == NULL)
2790 return NULL;
2791 if (pseudo) {
2792 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2793 if (ok == 0 || ok == 1)
2794 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2795 }
2796 else {
2797 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2798 if (ok == 1)
2799 return bytes;
2800 }
2801 Py_DECREF(bytes);
2802
2803 err = ERR_get_error();
2804 errstr = ERR_reason_error_string(err);
2805 v = Py_BuildValue("(ks)", err, errstr);
2806 if (v != NULL) {
2807 PyErr_SetObject(PySSLErrorObject, v);
2808 Py_DECREF(v);
2809 }
2810 return NULL;
2811}
2812
2813static PyObject *
2814PySSL_RAND_bytes(PyObject *self, PyObject *args)
2815{
2816 int len;
2817 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2818 return NULL;
2819 return PySSL_RAND(len, 0);
2820}
2821
2822PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2823"RAND_bytes(n) -> bytes\n\
2824\n\
2825Generate n cryptographically strong pseudo-random bytes.");
2826
2827static PyObject *
2828PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2829{
2830 int len;
2831 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2832 return NULL;
2833 return PySSL_RAND(len, 1);
2834}
2835
2836PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2837"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2838\n\
2839Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2840generated are cryptographically strong.");
2841
2842static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002843PySSL_RAND_status(PyObject *self)
2844{
Christian Heimes217cfd12007-12-02 14:31:20 +00002845 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002846}
2847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002848PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849"RAND_status() -> 0 or 1\n\
2850\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002851Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2852It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2853using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002854
2855static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002856PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002857{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002858 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002859 int bytes;
2860
Jesus Ceac8754a12012-09-11 02:00:58 +02002861 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002862 PyUnicode_FSConverter, &path))
2863 return NULL;
2864
2865 bytes = RAND_egd(PyBytes_AsString(path));
2866 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002867 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002868 PyErr_SetString(PySSLErrorObject,
2869 "EGD connection failed or EGD did not return "
2870 "enough data to seed the PRNG");
2871 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002872 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002873 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002874}
2875
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002876PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002877"RAND_egd(path) -> bytes\n\
2878\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002879Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2880Returns number of bytes read. Raises SSLError if connection to EGD\n\
2881fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002882
2883#endif
2884
Christian Heimes6d7ad132013-06-09 18:02:55 +02002885PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2886"get_default_verify_paths() -> tuple\n\
2887\n\
2888Return search paths and environment vars that are used by SSLContext's\n\
2889set_default_verify_paths() to load default CAs. The values are\n\
2890'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2891
2892static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002893PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002894{
2895 PyObject *ofile_env = NULL;
2896 PyObject *ofile = NULL;
2897 PyObject *odir_env = NULL;
2898 PyObject *odir = NULL;
2899
2900#define convert(info, target) { \
2901 const char *tmp = (info); \
2902 target = NULL; \
2903 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2904 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2905 target = PyBytes_FromString(tmp); } \
2906 if (!target) goto error; \
2907 } while(0)
2908
2909 convert(X509_get_default_cert_file_env(), ofile_env);
2910 convert(X509_get_default_cert_file(), ofile);
2911 convert(X509_get_default_cert_dir_env(), odir_env);
2912 convert(X509_get_default_cert_dir(), odir);
2913#undef convert
2914
Christian Heimes200bb1b2013-06-14 15:14:29 +02002915 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002916
2917 error:
2918 Py_XDECREF(ofile_env);
2919 Py_XDECREF(ofile);
2920 Py_XDECREF(odir_env);
2921 Py_XDECREF(odir);
2922 return NULL;
2923}
2924
Christian Heimes46bebee2013-06-09 19:03:31 +02002925#ifdef _MSC_VER
2926PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2927"enum_cert_store(store_name, cert_type='certificate') -> []\n\
2928\n\
2929Retrieve certificates from Windows' cert store. store_name may be one of\n\
2930'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
2931cert_type must be either 'certificate' or 'crl'.\n\
2932The function returns a list of (bytes, encoding_type) tuples. The\n\
2933encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
2934PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00002935
Christian Heimes46bebee2013-06-09 19:03:31 +02002936static PyObject *
2937PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
2938{
2939 char *kwlist[] = {"store_name", "cert_type", NULL};
2940 char *store_name;
2941 char *cert_type = "certificate";
2942 HCERTSTORE hStore = NULL;
2943 PyObject *result = NULL;
2944 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
2945 int ok = 1;
2946
2947 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
2948 kwlist, &store_name, &cert_type)) {
2949 return NULL;
2950 }
2951
2952 if ((strcmp(cert_type, "certificate") != 0) &&
2953 (strcmp(cert_type, "crl") != 0)) {
2954 return PyErr_Format(PyExc_ValueError,
2955 "cert_type must be 'certificate' or 'crl', "
2956 "not %.100s", cert_type);
2957 }
2958
2959 if ((result = PyList_New(0)) == NULL) {
2960 return NULL;
2961 }
2962
2963 if ((hStore = CertOpenSystemStore(NULL, store_name)) == NULL) {
2964 Py_DECREF(result);
2965 return PyErr_SetFromWindowsErr(GetLastError());
2966 }
2967
2968 if (strcmp(cert_type, "certificate") == 0) {
2969 PCCERT_CONTEXT pCertCtx = NULL;
2970 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
2971 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
2972 pCertCtx->cbCertEncoded);
2973 if (!cert) {
2974 ok = 0;
2975 break;
2976 }
2977 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
2978 ok = 0;
2979 break;
2980 }
2981 if ((tup = PyTuple_New(2)) == NULL) {
2982 ok = 0;
2983 break;
2984 }
2985 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
2986 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
2987
2988 if (PyList_Append(result, tup) < 0) {
2989 ok = 0;
2990 break;
2991 }
2992 Py_CLEAR(tup);
2993 }
2994 if (pCertCtx) {
2995 /* loop ended with an error, need to clean up context manually */
2996 CertFreeCertificateContext(pCertCtx);
2997 }
2998 } else {
2999 PCCRL_CONTEXT pCrlCtx = NULL;
3000 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3001 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3002 pCrlCtx->cbCrlEncoded);
3003 if (!cert) {
3004 ok = 0;
3005 break;
3006 }
3007 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3008 ok = 0;
3009 break;
3010 }
3011 if ((tup = PyTuple_New(2)) == NULL) {
3012 ok = 0;
3013 break;
3014 }
3015 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3016 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3017
3018 if (PyList_Append(result, tup) < 0) {
3019 ok = 0;
3020 break;
3021 }
3022 Py_CLEAR(tup);
3023 }
3024 if (pCrlCtx) {
3025 /* loop ended with an error, need to clean up context manually */
3026 CertFreeCRLContext(pCrlCtx);
3027 }
3028 }
3029
3030 /* In error cases cert, enc and tup may not be NULL */
3031 Py_XDECREF(cert);
3032 Py_XDECREF(enc);
3033 Py_XDECREF(tup);
3034
3035 if (!CertCloseStore(hStore, 0)) {
3036 /* This error case might shadow another exception.*/
3037 Py_DECREF(result);
3038 return PyErr_SetFromWindowsErr(GetLastError());
3039 }
3040 if (ok) {
3041 return result;
3042 } else {
3043 Py_DECREF(result);
3044 return NULL;
3045 }
3046}
3047#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003048
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003049/* List of functions exported by this module. */
3050
3051static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003052 {"_test_decode_cert", PySSL_test_decode_certificate,
3053 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003054#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003055 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3056 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003057 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3058 PySSL_RAND_bytes_doc},
3059 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3060 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003061 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003062 PySSL_RAND_egd_doc},
3063 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3064 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003065#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003066 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003067 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003068#ifdef _MSC_VER
3069 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3070 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3071#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003072 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003073};
3074
3075
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003076#ifdef WITH_THREAD
3077
3078/* an implementation of OpenSSL threading operations in terms
3079 of the Python C thread library */
3080
3081static PyThread_type_lock *_ssl_locks = NULL;
3082
3083static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003084 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003085}
3086
Bill Janssen6e027db2007-11-15 22:23:56 +00003087static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003088 (int mode, int n, const char *file, int line) {
3089 /* this function is needed to perform locking on shared data
3090 structures. (Note that OpenSSL uses a number of global data
3091 structures that will be implicitly shared whenever multiple
3092 threads use OpenSSL.) Multi-threaded applications will
3093 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003095 locking_function() must be able to handle up to
3096 CRYPTO_num_locks() different mutex locks. It sets the n-th
3097 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003098
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003099 file and line are the file number of the function setting the
3100 lock. They can be useful for debugging.
3101 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003103 if ((_ssl_locks == NULL) ||
3104 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3105 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003107 if (mode & CRYPTO_LOCK) {
3108 PyThread_acquire_lock(_ssl_locks[n], 1);
3109 } else {
3110 PyThread_release_lock(_ssl_locks[n]);
3111 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003112}
3113
3114static int _setup_ssl_threads(void) {
3115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003116 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003118 if (_ssl_locks == NULL) {
3119 _ssl_locks_count = CRYPTO_num_locks();
3120 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003121 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003122 if (_ssl_locks == NULL)
3123 return 0;
3124 memset(_ssl_locks, 0,
3125 sizeof(PyThread_type_lock) * _ssl_locks_count);
3126 for (i = 0; i < _ssl_locks_count; i++) {
3127 _ssl_locks[i] = PyThread_allocate_lock();
3128 if (_ssl_locks[i] == NULL) {
3129 unsigned int j;
3130 for (j = 0; j < i; j++) {
3131 PyThread_free_lock(_ssl_locks[j]);
3132 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003133 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003134 return 0;
3135 }
3136 }
3137 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
3138 CRYPTO_set_id_callback(_ssl_thread_id_function);
3139 }
3140 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003141}
3142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003143#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003145PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003146"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003147for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003148
Martin v. Löwis1a214512008-06-11 05:26:20 +00003149
3150static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003151 PyModuleDef_HEAD_INIT,
3152 "_ssl",
3153 module_doc,
3154 -1,
3155 PySSL_methods,
3156 NULL,
3157 NULL,
3158 NULL,
3159 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003160};
3161
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003162
3163static void
3164parse_openssl_version(unsigned long libver,
3165 unsigned int *major, unsigned int *minor,
3166 unsigned int *fix, unsigned int *patch,
3167 unsigned int *status)
3168{
3169 *status = libver & 0xF;
3170 libver >>= 4;
3171 *patch = libver & 0xFF;
3172 libver >>= 8;
3173 *fix = libver & 0xFF;
3174 libver >>= 8;
3175 *minor = libver & 0xFF;
3176 libver >>= 8;
3177 *major = libver & 0xFF;
3178}
3179
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003180PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003181PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003182{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003183 PyObject *m, *d, *r;
3184 unsigned long libver;
3185 unsigned int major, minor, fix, patch, status;
3186 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003187 struct py_ssl_error_code *errcode;
3188 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003189
Antoine Pitrou152efa22010-05-16 18:19:27 +00003190 if (PyType_Ready(&PySSLContext_Type) < 0)
3191 return NULL;
3192 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003193 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003195 m = PyModule_Create(&_sslmodule);
3196 if (m == NULL)
3197 return NULL;
3198 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003200 /* Load _socket module and its C API */
3201 socket_api = PySocketModule_ImportModuleAndAPI();
3202 if (!socket_api)
3203 return NULL;
3204 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003206 /* Init OpenSSL */
3207 SSL_load_error_strings();
3208 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003209#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003210 /* note that this will start threading if not already started */
3211 if (!_setup_ssl_threads()) {
3212 return NULL;
3213 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003214#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003215 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003217 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003218 sslerror_type_slots[0].pfunc = PyExc_OSError;
3219 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003220 if (PySSLErrorObject == NULL)
3221 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003222
Antoine Pitrou41032a62011-10-27 23:56:55 +02003223 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3224 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3225 PySSLErrorObject, NULL);
3226 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3227 "ssl.SSLWantReadError", SSLWantReadError_doc,
3228 PySSLErrorObject, NULL);
3229 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3230 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3231 PySSLErrorObject, NULL);
3232 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3233 "ssl.SSLSyscallError", SSLSyscallError_doc,
3234 PySSLErrorObject, NULL);
3235 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3236 "ssl.SSLEOFError", SSLEOFError_doc,
3237 PySSLErrorObject, NULL);
3238 if (PySSLZeroReturnErrorObject == NULL
3239 || PySSLWantReadErrorObject == NULL
3240 || PySSLWantWriteErrorObject == NULL
3241 || PySSLSyscallErrorObject == NULL
3242 || PySSLEOFErrorObject == NULL)
3243 return NULL;
3244 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3245 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3246 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3247 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3248 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3249 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003250 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003251 if (PyDict_SetItemString(d, "_SSLContext",
3252 (PyObject *)&PySSLContext_Type) != 0)
3253 return NULL;
3254 if (PyDict_SetItemString(d, "_SSLSocket",
3255 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003256 return NULL;
3257 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3258 PY_SSL_ERROR_ZERO_RETURN);
3259 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3260 PY_SSL_ERROR_WANT_READ);
3261 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3262 PY_SSL_ERROR_WANT_WRITE);
3263 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3264 PY_SSL_ERROR_WANT_X509_LOOKUP);
3265 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3266 PY_SSL_ERROR_SYSCALL);
3267 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3268 PY_SSL_ERROR_SSL);
3269 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3270 PY_SSL_ERROR_WANT_CONNECT);
3271 /* non ssl.h errorcodes */
3272 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3273 PY_SSL_ERROR_EOF);
3274 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3275 PY_SSL_ERROR_INVALID_ERROR_CODE);
3276 /* cert requirements */
3277 PyModule_AddIntConstant(m, "CERT_NONE",
3278 PY_SSL_CERT_NONE);
3279 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3280 PY_SSL_CERT_OPTIONAL);
3281 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3282 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003283
Christian Heimes46bebee2013-06-09 19:03:31 +02003284#ifdef _MSC_VER
3285 /* Windows dwCertEncodingType */
3286 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3287 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3288#endif
3289
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003290 /* Alert Descriptions from ssl.h */
3291 /* note RESERVED constants no longer intended for use have been removed */
3292 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3293
3294#define ADD_AD_CONSTANT(s) \
3295 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3296 SSL_AD_##s)
3297
3298 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3299 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3300 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3301 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3302 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3303 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3304 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3305 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3306 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3307 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3308 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3309 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3310 ADD_AD_CONSTANT(UNKNOWN_CA);
3311 ADD_AD_CONSTANT(ACCESS_DENIED);
3312 ADD_AD_CONSTANT(DECODE_ERROR);
3313 ADD_AD_CONSTANT(DECRYPT_ERROR);
3314 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3315 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3316 ADD_AD_CONSTANT(INTERNAL_ERROR);
3317 ADD_AD_CONSTANT(USER_CANCELLED);
3318 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003319 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003320#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3321 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3322#endif
3323#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3324 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3325#endif
3326#ifdef SSL_AD_UNRECOGNIZED_NAME
3327 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3328#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003329#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3330 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3331#endif
3332#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3333 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3334#endif
3335#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3336 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3337#endif
3338
3339#undef ADD_AD_CONSTANT
3340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003341 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003342#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003343 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3344 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003345#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003346 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3347 PY_SSL_VERSION_SSL3);
3348 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3349 PY_SSL_VERSION_SSL23);
3350 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3351 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003352#if HAVE_TLSv1_2
3353 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3354 PY_SSL_VERSION_TLS1_1);
3355 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3356 PY_SSL_VERSION_TLS1_2);
3357#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003358
Antoine Pitroub5218772010-05-21 09:56:06 +00003359 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003360 PyModule_AddIntConstant(m, "OP_ALL",
3361 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003362 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3363 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3364 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003365#if HAVE_TLSv1_2
3366 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3367 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3368#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003369 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3370 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003371 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003372#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003373 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003374#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003375#ifdef SSL_OP_NO_COMPRESSION
3376 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3377 SSL_OP_NO_COMPRESSION);
3378#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003379
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003380#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003381 r = Py_True;
3382#else
3383 r = Py_False;
3384#endif
3385 Py_INCREF(r);
3386 PyModule_AddObject(m, "HAS_SNI", r);
3387
Antoine Pitroud6494802011-07-21 01:11:30 +02003388#if HAVE_OPENSSL_FINISHED
3389 r = Py_True;
3390#else
3391 r = Py_False;
3392#endif
3393 Py_INCREF(r);
3394 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3395
Antoine Pitrou501da612011-12-21 09:27:41 +01003396#ifdef OPENSSL_NO_ECDH
3397 r = Py_False;
3398#else
3399 r = Py_True;
3400#endif
3401 Py_INCREF(r);
3402 PyModule_AddObject(m, "HAS_ECDH", r);
3403
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003404#ifdef OPENSSL_NPN_NEGOTIATED
3405 r = Py_True;
3406#else
3407 r = Py_False;
3408#endif
3409 Py_INCREF(r);
3410 PyModule_AddObject(m, "HAS_NPN", r);
3411
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003412 /* Mappings for error codes */
3413 err_codes_to_names = PyDict_New();
3414 err_names_to_codes = PyDict_New();
3415 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3416 return NULL;
3417 errcode = error_codes;
3418 while (errcode->mnemonic != NULL) {
3419 PyObject *mnemo, *key;
3420 mnemo = PyUnicode_FromString(errcode->mnemonic);
3421 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3422 if (mnemo == NULL || key == NULL)
3423 return NULL;
3424 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3425 return NULL;
3426 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3427 return NULL;
3428 Py_DECREF(key);
3429 Py_DECREF(mnemo);
3430 errcode++;
3431 }
3432 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3433 return NULL;
3434 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3435 return NULL;
3436
3437 lib_codes_to_names = PyDict_New();
3438 if (lib_codes_to_names == NULL)
3439 return NULL;
3440 libcode = library_codes;
3441 while (libcode->library != NULL) {
3442 PyObject *mnemo, *key;
3443 key = PyLong_FromLong(libcode->code);
3444 mnemo = PyUnicode_FromString(libcode->library);
3445 if (key == NULL || mnemo == NULL)
3446 return NULL;
3447 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3448 return NULL;
3449 Py_DECREF(key);
3450 Py_DECREF(mnemo);
3451 libcode++;
3452 }
3453 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3454 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003456 /* OpenSSL version */
3457 /* SSLeay() gives us the version of the library linked against,
3458 which could be different from the headers version.
3459 */
3460 libver = SSLeay();
3461 r = PyLong_FromUnsignedLong(libver);
3462 if (r == NULL)
3463 return NULL;
3464 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3465 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003466 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003467 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3468 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3469 return NULL;
3470 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3471 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3472 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003473
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003474 libver = OPENSSL_VERSION_NUMBER;
3475 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3476 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3477 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3478 return NULL;
3479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003480 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003481}