blob: 116311cd989bd309605adc86f8396c9b3414eafa [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);
Christian Heimes5962bef2013-07-26 15:51:18 +0200940 if (version == NULL)
941 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000942 if (PyDict_SetItemString(retval, "version", version) < 0) {
943 Py_DECREF(version);
944 goto fail0;
945 }
946 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 /* get a memory buffer */
949 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000950
Antoine Pitroufb046912010-11-09 20:21:19 +0000951 (void) BIO_reset(biobuf);
952 serialNumber = X509_get_serialNumber(certificate);
953 /* should not exceed 20 octets, 160 bits, so buf is big enough */
954 i2a_ASN1_INTEGER(biobuf, serialNumber);
955 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
956 if (len < 0) {
957 _setSSLError(NULL, 0, __FILE__, __LINE__);
958 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000960 sn_obj = PyUnicode_FromStringAndSize(buf, len);
961 if (sn_obj == NULL)
962 goto fail1;
963 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
964 Py_DECREF(sn_obj);
965 goto fail1;
966 }
967 Py_DECREF(sn_obj);
968
969 (void) BIO_reset(biobuf);
970 notBefore = X509_get_notBefore(certificate);
971 ASN1_TIME_print(biobuf, notBefore);
972 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
973 if (len < 0) {
974 _setSSLError(NULL, 0, __FILE__, __LINE__);
975 goto fail1;
976 }
977 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
978 if (pnotBefore == NULL)
979 goto fail1;
980 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
981 Py_DECREF(pnotBefore);
982 goto fail1;
983 }
984 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 (void) BIO_reset(biobuf);
987 notAfter = X509_get_notAfter(certificate);
988 ASN1_TIME_print(biobuf, notAfter);
989 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
990 if (len < 0) {
991 _setSSLError(NULL, 0, __FILE__, __LINE__);
992 goto fail1;
993 }
994 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
995 if (pnotAfter == NULL)
996 goto fail1;
997 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
998 Py_DECREF(pnotAfter);
999 goto fail1;
1000 }
1001 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 peer_alt_names = _get_peer_alt_names(certificate);
1006 if (peer_alt_names == NULL)
1007 goto fail1;
1008 else if (peer_alt_names != Py_None) {
1009 if (PyDict_SetItemString(retval, "subjectAltName",
1010 peer_alt_names) < 0) {
1011 Py_DECREF(peer_alt_names);
1012 goto fail1;
1013 }
1014 Py_DECREF(peer_alt_names);
1015 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 BIO_free(biobuf);
1018 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001019
1020 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 if (biobuf != NULL)
1022 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001023 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 Py_XDECREF(retval);
1025 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001026}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001027
Christian Heimes9a5395a2013-06-17 15:44:12 +02001028static PyObject *
1029_certificate_to_der(X509 *certificate)
1030{
1031 unsigned char *bytes_buf = NULL;
1032 int len;
1033 PyObject *retval;
1034
1035 bytes_buf = NULL;
1036 len = i2d_X509(certificate, &bytes_buf);
1037 if (len < 0) {
1038 _setSSLError(NULL, 0, __FILE__, __LINE__);
1039 return NULL;
1040 }
1041 /* this is actually an immutable bytes sequence */
1042 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1043 OPENSSL_free(bytes_buf);
1044 return retval;
1045}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001046
1047static PyObject *
1048PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001051 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 X509 *x=NULL;
1053 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054
Antoine Pitroufb046912010-11-09 20:21:19 +00001055 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1056 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1060 PyErr_SetString(PySSLErrorObject,
1061 "Can't malloc memory to read file");
1062 goto fail0;
1063 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064
Victor Stinner3800e1e2010-05-16 21:23:48 +00001065 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 PyErr_SetString(PySSLErrorObject,
1067 "Can't open file");
1068 goto fail0;
1069 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1072 if (x == NULL) {
1073 PyErr_SetString(PySSLErrorObject,
1074 "Error decoding PEM-encoded file");
1075 goto fail0;
1076 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001077
Antoine Pitroufb046912010-11-09 20:21:19 +00001078 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001079 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080
1081 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001082 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 if (cert != NULL) BIO_free(cert);
1084 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085}
1086
1087
1088static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001089PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001092 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093
Antoine Pitrou721738f2012-08-15 23:20:39 +02001094 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 if (!self->peer_cert)
1098 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099
Antoine Pitrou721738f2012-08-15 23:20:39 +02001100 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001102 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001104 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 if ((verification & SSL_VERIFY_PEER) == 0)
1106 return PyDict_New();
1107 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001108 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110}
1111
1112PyDoc_STRVAR(PySSL_peercert_doc,
1113"peer_certificate([der=False]) -> certificate\n\
1114\n\
1115Returns the certificate for the peer. If no certificate was provided,\n\
1116returns None. If a certificate was provided, but not validated, returns\n\
1117an empty dictionary. Otherwise returns a dict containing information\n\
1118about the peer certificate.\n\
1119\n\
1120If the optional argument is True, returns a DER-encoded copy of the\n\
1121peer certificate, or None if no certificate was provided. This will\n\
1122return the certificate even if it wasn't validated.");
1123
Antoine Pitrou152efa22010-05-16 18:19:27 +00001124static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001127 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 char *cipher_name;
1129 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001132 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 current = SSL_get_current_cipher(self->ssl);
1134 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001135 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 retval = PyTuple_New(3);
1138 if (retval == NULL)
1139 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 cipher_name = (char *) SSL_CIPHER_get_name(current);
1142 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001143 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 PyTuple_SET_ITEM(retval, 0, Py_None);
1145 } else {
1146 v = PyUnicode_FromString(cipher_name);
1147 if (v == NULL)
1148 goto fail0;
1149 PyTuple_SET_ITEM(retval, 0, v);
1150 }
1151 cipher_protocol = SSL_CIPHER_get_version(current);
1152 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001153 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 PyTuple_SET_ITEM(retval, 1, Py_None);
1155 } else {
1156 v = PyUnicode_FromString(cipher_protocol);
1157 if (v == NULL)
1158 goto fail0;
1159 PyTuple_SET_ITEM(retval, 1, v);
1160 }
1161 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1162 if (v == NULL)
1163 goto fail0;
1164 PyTuple_SET_ITEM(retval, 2, v);
1165 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001166
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 Py_DECREF(retval);
1169 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170}
1171
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001172#ifdef OPENSSL_NPN_NEGOTIATED
1173static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1174 const unsigned char *out;
1175 unsigned int outlen;
1176
Victor Stinner4569cd52013-06-23 14:58:43 +02001177 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001178 &out, &outlen);
1179
1180 if (out == NULL)
1181 Py_RETURN_NONE;
1182 return PyUnicode_FromStringAndSize((char *) out, outlen);
1183}
1184#endif
1185
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001186static PyObject *PySSL_compression(PySSLSocket *self) {
1187#ifdef OPENSSL_NO_COMP
1188 Py_RETURN_NONE;
1189#else
1190 const COMP_METHOD *comp_method;
1191 const char *short_name;
1192
1193 if (self->ssl == NULL)
1194 Py_RETURN_NONE;
1195 comp_method = SSL_get_current_compression(self->ssl);
1196 if (comp_method == NULL || comp_method->type == NID_undef)
1197 Py_RETURN_NONE;
1198 short_name = OBJ_nid2sn(comp_method->type);
1199 if (short_name == NULL)
1200 Py_RETURN_NONE;
1201 return PyUnicode_DecodeFSDefault(short_name);
1202#endif
1203}
1204
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001205static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1206 Py_INCREF(self->ctx);
1207 return self->ctx;
1208}
1209
1210static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1211 void *closure) {
1212
1213 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001214#if !HAVE_SNI
1215 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1216 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001217 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001218#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001219 Py_INCREF(value);
1220 Py_DECREF(self->ctx);
1221 self->ctx = (PySSLContext *) value;
1222 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001223#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001224 } else {
1225 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1226 return -1;
1227 }
1228
1229 return 0;
1230}
1231
1232PyDoc_STRVAR(PySSL_set_context_doc,
1233"_setter_context(ctx)\n\
1234\
1235This changes the context associated with the SSLSocket. This is typically\n\
1236used from within a callback function set by the set_servername_callback\n\
1237on the SSLContext to change the certificate information associated with the\n\
1238SSLSocket before the cryptographic exchange handshake messages\n");
1239
1240
1241
Antoine Pitrou152efa22010-05-16 18:19:27 +00001242static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001243{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 if (self->peer_cert) /* Possible not to have one? */
1245 X509_free (self->peer_cert);
1246 if (self->ssl)
1247 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001249 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001251}
1252
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001253/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001254 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001255 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001256 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001257
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001258static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001259check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001260{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 fd_set fds;
1262 struct timeval tv;
1263 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1266 if (s->sock_timeout < 0.0)
1267 return SOCKET_IS_BLOCKING;
1268 else if (s->sock_timeout == 0.0)
1269 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 /* Guard against closed socket */
1272 if (s->sock_fd < 0)
1273 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 /* Prefer poll, if available, since you can poll() any fd
1276 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001277#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 {
1279 struct pollfd pollfd;
1280 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 pollfd.fd = s->sock_fd;
1283 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 /* s->sock_timeout is in seconds, timeout in ms */
1286 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1287 PySSL_BEGIN_ALLOW_THREADS
1288 rc = poll(&pollfd, 1, timeout);
1289 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 goto normal_return;
1292 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293#endif
1294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001296 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 /* Construct the arguments to select */
1300 tv.tv_sec = (int)s->sock_timeout;
1301 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1302 FD_ZERO(&fds);
1303 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 /* See if the socket is ready */
1306 PySSL_BEGIN_ALLOW_THREADS
1307 if (writing)
1308 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1309 else
1310 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1311 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001312
Bill Janssen6e027db2007-11-15 22:23:56 +00001313#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001314normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001315#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1317 (when we are able to write or when there's something to read) */
1318 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001319}
1320
Antoine Pitrou152efa22010-05-16 18:19:27 +00001321static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001322{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 Py_buffer buf;
1324 int len;
1325 int sockstate;
1326 int err;
1327 int nonblocking;
1328 PySocketSockObject *sock
1329 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 if (((PyObject*)sock) == Py_None) {
1332 _setSSLError("Underlying socket connection gone",
1333 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1334 return NULL;
1335 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001336 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001338 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1339 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001341 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342
Victor Stinner6efa9652013-06-25 00:42:31 +02001343 if (buf.len > INT_MAX) {
1344 PyErr_Format(PyExc_OverflowError,
1345 "string longer than %d bytes", INT_MAX);
1346 goto error;
1347 }
1348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 /* just in case the blocking state of the socket has been changed */
1350 nonblocking = (sock->sock_timeout >= 0.0);
1351 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1352 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1353
1354 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1355 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001356 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 "The write operation timed out");
1358 goto error;
1359 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1360 PyErr_SetString(PySSLErrorObject,
1361 "Underlying socket has been closed.");
1362 goto error;
1363 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1364 PyErr_SetString(PySSLErrorObject,
1365 "Underlying socket too large for select().");
1366 goto error;
1367 }
1368 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001370 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 err = SSL_get_error(self->ssl, len);
1372 PySSL_END_ALLOW_THREADS
1373 if (PyErr_CheckSignals()) {
1374 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001375 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001377 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001379 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 } else {
1381 sockstate = SOCKET_OPERATION_OK;
1382 }
1383 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001384 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 "The write operation timed out");
1386 goto error;
1387 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1388 PyErr_SetString(PySSLErrorObject,
1389 "Underlying socket has been closed.");
1390 goto error;
1391 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1392 break;
1393 }
1394 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001396 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 PyBuffer_Release(&buf);
1398 if (len > 0)
1399 return PyLong_FromLong(len);
1400 else
1401 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001402
1403error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001404 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 PyBuffer_Release(&buf);
1406 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001407}
1408
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001409PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001410"write(s) -> len\n\
1411\n\
1412Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001413of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001414
Antoine Pitrou152efa22010-05-16 18:19:27 +00001415static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001416{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 PySSL_BEGIN_ALLOW_THREADS
1420 count = SSL_pending(self->ssl);
1421 PySSL_END_ALLOW_THREADS
1422 if (count < 0)
1423 return PySSL_SetError(self, count, __FILE__, __LINE__);
1424 else
1425 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001426}
1427
1428PyDoc_STRVAR(PySSL_SSLpending_doc,
1429"pending() -> count\n\
1430\n\
1431Returns the number of already decrypted bytes available for read,\n\
1432pending on the connection.\n");
1433
Antoine Pitrou152efa22010-05-16 18:19:27 +00001434static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001435{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 PyObject *dest = NULL;
1437 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001439 int len, count;
1440 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 int sockstate;
1442 int err;
1443 int nonblocking;
1444 PySocketSockObject *sock
1445 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001446
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001447 if (((PyObject*)sock) == Py_None) {
1448 _setSSLError("Underlying socket connection gone",
1449 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1450 return NULL;
1451 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001452 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001454 buf.obj = NULL;
1455 buf.buf = NULL;
1456 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001457 goto error;
1458
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001459 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1460 dest = PyBytes_FromStringAndSize(NULL, len);
1461 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001462 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001463 mem = PyBytes_AS_STRING(dest);
1464 }
1465 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001467 mem = buf.buf;
1468 if (len <= 0 || len > buf.len) {
1469 len = (int) buf.len;
1470 if (buf.len != len) {
1471 PyErr_SetString(PyExc_OverflowError,
1472 "maximum length can't fit in a C 'int'");
1473 goto error;
1474 }
1475 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 }
1477
1478 /* just in case the blocking state of the socket has been changed */
1479 nonblocking = (sock->sock_timeout >= 0.0);
1480 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1481 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1482
1483 /* first check if there are bytes ready to be read */
1484 PySSL_BEGIN_ALLOW_THREADS
1485 count = SSL_pending(self->ssl);
1486 PySSL_END_ALLOW_THREADS
1487
1488 if (!count) {
1489 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1490 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001491 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 "The read operation timed out");
1493 goto error;
1494 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1495 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001496 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 goto error;
1498 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1499 count = 0;
1500 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001501 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 }
1503 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 PySSL_BEGIN_ALLOW_THREADS
1505 count = SSL_read(self->ssl, mem, len);
1506 err = SSL_get_error(self->ssl, count);
1507 PySSL_END_ALLOW_THREADS
1508 if (PyErr_CheckSignals())
1509 goto error;
1510 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001511 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001513 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1515 (SSL_get_shutdown(self->ssl) ==
1516 SSL_RECEIVED_SHUTDOWN))
1517 {
1518 count = 0;
1519 goto done;
1520 } else {
1521 sockstate = SOCKET_OPERATION_OK;
1522 }
1523 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001524 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 "The read operation timed out");
1526 goto error;
1527 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1528 break;
1529 }
1530 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1531 if (count <= 0) {
1532 PySSL_SetError(self, count, __FILE__, __LINE__);
1533 goto error;
1534 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001535
1536done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001537 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001539 _PyBytes_Resize(&dest, count);
1540 return dest;
1541 }
1542 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 PyBuffer_Release(&buf);
1544 return PyLong_FromLong(count);
1545 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001546
1547error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001548 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001549 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001550 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001551 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001554}
1555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001557"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001558\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001559Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001560
Antoine Pitrou152efa22010-05-16 18:19:27 +00001561static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001562{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 int err, ssl_err, sockstate, nonblocking;
1564 int zeros = 0;
1565 PySocketSockObject *sock
1566 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 /* Guard against closed socket */
1569 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1570 _setSSLError("Underlying socket connection gone",
1571 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1572 return NULL;
1573 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001574 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575
1576 /* Just in case the blocking state of the socket has been changed */
1577 nonblocking = (sock->sock_timeout >= 0.0);
1578 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1579 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1580
1581 while (1) {
1582 PySSL_BEGIN_ALLOW_THREADS
1583 /* Disable read-ahead so that unwrap can work correctly.
1584 * Otherwise OpenSSL might read in too much data,
1585 * eating clear text data that happens to be
1586 * transmitted after the SSL shutdown.
1587 * Should be safe to call repeatedly everytime this
1588 * function is used and the shutdown_seen_zero != 0
1589 * condition is met.
1590 */
1591 if (self->shutdown_seen_zero)
1592 SSL_set_read_ahead(self->ssl, 0);
1593 err = SSL_shutdown(self->ssl);
1594 PySSL_END_ALLOW_THREADS
1595 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1596 if (err > 0)
1597 break;
1598 if (err == 0) {
1599 /* Don't loop endlessly; instead preserve legacy
1600 behaviour of trying SSL_shutdown() only twice.
1601 This looks necessary for OpenSSL < 0.9.8m */
1602 if (++zeros > 1)
1603 break;
1604 /* Shutdown was sent, now try receiving */
1605 self->shutdown_seen_zero = 1;
1606 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001607 }
1608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 /* Possibly retry shutdown until timeout or failure */
1610 ssl_err = SSL_get_error(self->ssl, err);
1611 if (ssl_err == SSL_ERROR_WANT_READ)
1612 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1613 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1614 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1615 else
1616 break;
1617 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1618 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001619 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 "The read operation timed out");
1621 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001622 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001624 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 }
1626 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1627 PyErr_SetString(PySSLErrorObject,
1628 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001629 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 }
1631 else if (sockstate != SOCKET_OPERATION_OK)
1632 /* Retain the SSL error code */
1633 break;
1634 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001635
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001636 if (err < 0) {
1637 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001639 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001640 else
1641 /* It's already INCREF'ed */
1642 return (PyObject *) sock;
1643
1644error:
1645 Py_DECREF(sock);
1646 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001647}
1648
1649PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1650"shutdown(s) -> socket\n\
1651\n\
1652Does the SSL shutdown handshake with the remote end, and returns\n\
1653the underlying socket object.");
1654
Antoine Pitroud6494802011-07-21 01:11:30 +02001655#if HAVE_OPENSSL_FINISHED
1656static PyObject *
1657PySSL_tls_unique_cb(PySSLSocket *self)
1658{
1659 PyObject *retval = NULL;
1660 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001661 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001662
1663 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1664 /* if session is resumed XOR we are the client */
1665 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1666 }
1667 else {
1668 /* if a new session XOR we are the server */
1669 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1670 }
1671
1672 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001673 if (len == 0)
1674 Py_RETURN_NONE;
1675
1676 retval = PyBytes_FromStringAndSize(buf, len);
1677
1678 return retval;
1679}
1680
1681PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1682"tls_unique_cb() -> bytes\n\
1683\n\
1684Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1685\n\
1686If the TLS handshake is not yet complete, None is returned");
1687
1688#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001689
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001690static PyGetSetDef ssl_getsetlist[] = {
1691 {"context", (getter) PySSL_get_context,
1692 (setter) PySSL_set_context, PySSL_set_context_doc},
1693 {NULL}, /* sentinel */
1694};
1695
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001696static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1698 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1699 PySSL_SSLwrite_doc},
1700 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1701 PySSL_SSLread_doc},
1702 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1703 PySSL_SSLpending_doc},
1704 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1705 PySSL_peercert_doc},
1706 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001707#ifdef OPENSSL_NPN_NEGOTIATED
1708 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1709#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001710 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1712 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001713#if HAVE_OPENSSL_FINISHED
1714 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1715 PySSL_tls_unique_cb_doc},
1716#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001718};
1719
Antoine Pitrou152efa22010-05-16 18:19:27 +00001720static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001722 "_ssl._SSLSocket", /*tp_name*/
1723 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 0, /*tp_itemsize*/
1725 /* methods */
1726 (destructor)PySSL_dealloc, /*tp_dealloc*/
1727 0, /*tp_print*/
1728 0, /*tp_getattr*/
1729 0, /*tp_setattr*/
1730 0, /*tp_reserved*/
1731 0, /*tp_repr*/
1732 0, /*tp_as_number*/
1733 0, /*tp_as_sequence*/
1734 0, /*tp_as_mapping*/
1735 0, /*tp_hash*/
1736 0, /*tp_call*/
1737 0, /*tp_str*/
1738 0, /*tp_getattro*/
1739 0, /*tp_setattro*/
1740 0, /*tp_as_buffer*/
1741 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1742 0, /*tp_doc*/
1743 0, /*tp_traverse*/
1744 0, /*tp_clear*/
1745 0, /*tp_richcompare*/
1746 0, /*tp_weaklistoffset*/
1747 0, /*tp_iter*/
1748 0, /*tp_iternext*/
1749 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001750 0, /*tp_members*/
1751 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001752};
1753
Antoine Pitrou152efa22010-05-16 18:19:27 +00001754
1755/*
1756 * _SSLContext objects
1757 */
1758
1759static PyObject *
1760context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1761{
1762 char *kwlist[] = {"protocol", NULL};
1763 PySSLContext *self;
1764 int proto_version = PY_SSL_VERSION_SSL23;
1765 SSL_CTX *ctx = NULL;
1766
1767 if (!PyArg_ParseTupleAndKeywords(
1768 args, kwds, "i:_SSLContext", kwlist,
1769 &proto_version))
1770 return NULL;
1771
1772 PySSL_BEGIN_ALLOW_THREADS
1773 if (proto_version == PY_SSL_VERSION_TLS1)
1774 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001775#if HAVE_TLSv1_2
1776 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1777 ctx = SSL_CTX_new(TLSv1_1_method());
1778 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1779 ctx = SSL_CTX_new(TLSv1_2_method());
1780#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001781 else if (proto_version == PY_SSL_VERSION_SSL3)
1782 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001783#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001784 else if (proto_version == PY_SSL_VERSION_SSL2)
1785 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001786#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001787 else if (proto_version == PY_SSL_VERSION_SSL23)
1788 ctx = SSL_CTX_new(SSLv23_method());
1789 else
1790 proto_version = -1;
1791 PySSL_END_ALLOW_THREADS
1792
1793 if (proto_version == -1) {
1794 PyErr_SetString(PyExc_ValueError,
1795 "invalid protocol version");
1796 return NULL;
1797 }
1798 if (ctx == NULL) {
1799 PyErr_SetString(PySSLErrorObject,
1800 "failed to allocate SSL context");
1801 return NULL;
1802 }
1803
1804 assert(type != NULL && type->tp_alloc != NULL);
1805 self = (PySSLContext *) type->tp_alloc(type, 0);
1806 if (self == NULL) {
1807 SSL_CTX_free(ctx);
1808 return NULL;
1809 }
1810 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001811#ifdef OPENSSL_NPN_NEGOTIATED
1812 self->npn_protocols = NULL;
1813#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001814#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001815 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001816#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001817 /* Defaults */
1818 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001819 SSL_CTX_set_options(self->ctx,
1820 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001822#define SID_CTX "Python"
1823 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1824 sizeof(SID_CTX));
1825#undef SID_CTX
1826
Antoine Pitrou152efa22010-05-16 18:19:27 +00001827 return (PyObject *)self;
1828}
1829
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001830static int
1831context_traverse(PySSLContext *self, visitproc visit, void *arg)
1832{
1833#ifndef OPENSSL_NO_TLSEXT
1834 Py_VISIT(self->set_hostname);
1835#endif
1836 return 0;
1837}
1838
1839static int
1840context_clear(PySSLContext *self)
1841{
1842#ifndef OPENSSL_NO_TLSEXT
1843 Py_CLEAR(self->set_hostname);
1844#endif
1845 return 0;
1846}
1847
Antoine Pitrou152efa22010-05-16 18:19:27 +00001848static void
1849context_dealloc(PySSLContext *self)
1850{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001851 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001852 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001853#ifdef OPENSSL_NPN_NEGOTIATED
1854 PyMem_Free(self->npn_protocols);
1855#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001856 Py_TYPE(self)->tp_free(self);
1857}
1858
1859static PyObject *
1860set_ciphers(PySSLContext *self, PyObject *args)
1861{
1862 int ret;
1863 const char *cipherlist;
1864
1865 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1866 return NULL;
1867 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1868 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001869 /* Clearing the error queue is necessary on some OpenSSL versions,
1870 otherwise the error will be reported again when another SSL call
1871 is done. */
1872 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001873 PyErr_SetString(PySSLErrorObject,
1874 "No cipher can be selected.");
1875 return NULL;
1876 }
1877 Py_RETURN_NONE;
1878}
1879
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001880#ifdef OPENSSL_NPN_NEGOTIATED
1881/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1882static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001883_advertiseNPN_cb(SSL *s,
1884 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001885 void *args)
1886{
1887 PySSLContext *ssl_ctx = (PySSLContext *) args;
1888
1889 if (ssl_ctx->npn_protocols == NULL) {
1890 *data = (unsigned char *) "";
1891 *len = 0;
1892 } else {
1893 *data = (unsigned char *) ssl_ctx->npn_protocols;
1894 *len = ssl_ctx->npn_protocols_len;
1895 }
1896
1897 return SSL_TLSEXT_ERR_OK;
1898}
1899/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1900static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001901_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001902 unsigned char **out, unsigned char *outlen,
1903 const unsigned char *server, unsigned int server_len,
1904 void *args)
1905{
1906 PySSLContext *ssl_ctx = (PySSLContext *) args;
1907
1908 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1909 int client_len;
1910
1911 if (client == NULL) {
1912 client = (unsigned char *) "";
1913 client_len = 0;
1914 } else {
1915 client_len = ssl_ctx->npn_protocols_len;
1916 }
1917
1918 SSL_select_next_proto(out, outlen,
1919 server, server_len,
1920 client, client_len);
1921
1922 return SSL_TLSEXT_ERR_OK;
1923}
1924#endif
1925
1926static PyObject *
1927_set_npn_protocols(PySSLContext *self, PyObject *args)
1928{
1929#ifdef OPENSSL_NPN_NEGOTIATED
1930 Py_buffer protos;
1931
1932 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1933 return NULL;
1934
Christian Heimes5cb31c92012-09-20 12:42:54 +02001935 if (self->npn_protocols != NULL) {
1936 PyMem_Free(self->npn_protocols);
1937 }
1938
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001939 self->npn_protocols = PyMem_Malloc(protos.len);
1940 if (self->npn_protocols == NULL) {
1941 PyBuffer_Release(&protos);
1942 return PyErr_NoMemory();
1943 }
1944 memcpy(self->npn_protocols, protos.buf, protos.len);
1945 self->npn_protocols_len = (int) protos.len;
1946
1947 /* set both server and client callbacks, because the context can
1948 * be used to create both types of sockets */
1949 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1950 _advertiseNPN_cb,
1951 self);
1952 SSL_CTX_set_next_proto_select_cb(self->ctx,
1953 _selectNPN_cb,
1954 self);
1955
1956 PyBuffer_Release(&protos);
1957 Py_RETURN_NONE;
1958#else
1959 PyErr_SetString(PyExc_NotImplementedError,
1960 "The NPN extension requires OpenSSL 1.0.1 or later.");
1961 return NULL;
1962#endif
1963}
1964
Antoine Pitrou152efa22010-05-16 18:19:27 +00001965static PyObject *
1966get_verify_mode(PySSLContext *self, void *c)
1967{
1968 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1969 case SSL_VERIFY_NONE:
1970 return PyLong_FromLong(PY_SSL_CERT_NONE);
1971 case SSL_VERIFY_PEER:
1972 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1973 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1974 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1975 }
1976 PyErr_SetString(PySSLErrorObject,
1977 "invalid return value from SSL_CTX_get_verify_mode");
1978 return NULL;
1979}
1980
1981static int
1982set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1983{
1984 int n, mode;
1985 if (!PyArg_Parse(arg, "i", &n))
1986 return -1;
1987 if (n == PY_SSL_CERT_NONE)
1988 mode = SSL_VERIFY_NONE;
1989 else if (n == PY_SSL_CERT_OPTIONAL)
1990 mode = SSL_VERIFY_PEER;
1991 else if (n == PY_SSL_CERT_REQUIRED)
1992 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1993 else {
1994 PyErr_SetString(PyExc_ValueError,
1995 "invalid value for verify_mode");
1996 return -1;
1997 }
1998 SSL_CTX_set_verify(self->ctx, mode, NULL);
1999 return 0;
2000}
2001
2002static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002003get_options(PySSLContext *self, void *c)
2004{
2005 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2006}
2007
2008static int
2009set_options(PySSLContext *self, PyObject *arg, void *c)
2010{
2011 long new_opts, opts, set, clear;
2012 if (!PyArg_Parse(arg, "l", &new_opts))
2013 return -1;
2014 opts = SSL_CTX_get_options(self->ctx);
2015 clear = opts & ~new_opts;
2016 set = ~opts & new_opts;
2017 if (clear) {
2018#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2019 SSL_CTX_clear_options(self->ctx, clear);
2020#else
2021 PyErr_SetString(PyExc_ValueError,
2022 "can't clear options before OpenSSL 0.9.8m");
2023 return -1;
2024#endif
2025 }
2026 if (set)
2027 SSL_CTX_set_options(self->ctx, set);
2028 return 0;
2029}
2030
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002031typedef struct {
2032 PyThreadState *thread_state;
2033 PyObject *callable;
2034 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002035 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002036 int error;
2037} _PySSLPasswordInfo;
2038
2039static int
2040_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2041 const char *bad_type_error)
2042{
2043 /* Set the password and size fields of a _PySSLPasswordInfo struct
2044 from a unicode, bytes, or byte array object.
2045 The password field will be dynamically allocated and must be freed
2046 by the caller */
2047 PyObject *password_bytes = NULL;
2048 const char *data = NULL;
2049 Py_ssize_t size;
2050
2051 if (PyUnicode_Check(password)) {
2052 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2053 if (!password_bytes) {
2054 goto error;
2055 }
2056 data = PyBytes_AS_STRING(password_bytes);
2057 size = PyBytes_GET_SIZE(password_bytes);
2058 } else if (PyBytes_Check(password)) {
2059 data = PyBytes_AS_STRING(password);
2060 size = PyBytes_GET_SIZE(password);
2061 } else if (PyByteArray_Check(password)) {
2062 data = PyByteArray_AS_STRING(password);
2063 size = PyByteArray_GET_SIZE(password);
2064 } else {
2065 PyErr_SetString(PyExc_TypeError, bad_type_error);
2066 goto error;
2067 }
2068
Victor Stinner9ee02032013-06-23 15:08:23 +02002069 if (size > (Py_ssize_t)INT_MAX) {
2070 PyErr_Format(PyExc_ValueError,
2071 "password cannot be longer than %d bytes", INT_MAX);
2072 goto error;
2073 }
2074
Victor Stinner11ebff22013-07-07 17:07:52 +02002075 PyMem_Free(pw_info->password);
2076 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002077 if (!pw_info->password) {
2078 PyErr_SetString(PyExc_MemoryError,
2079 "unable to allocate password buffer");
2080 goto error;
2081 }
2082 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002083 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002084
2085 Py_XDECREF(password_bytes);
2086 return 1;
2087
2088error:
2089 Py_XDECREF(password_bytes);
2090 return 0;
2091}
2092
2093static int
2094_password_callback(char *buf, int size, int rwflag, void *userdata)
2095{
2096 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2097 PyObject *fn_ret = NULL;
2098
2099 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2100
2101 if (pw_info->callable) {
2102 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2103 if (!fn_ret) {
2104 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2105 core python API, so we could use it to add a frame here */
2106 goto error;
2107 }
2108
2109 if (!_pwinfo_set(pw_info, fn_ret,
2110 "password callback must return a string")) {
2111 goto error;
2112 }
2113 Py_CLEAR(fn_ret);
2114 }
2115
2116 if (pw_info->size > size) {
2117 PyErr_Format(PyExc_ValueError,
2118 "password cannot be longer than %d bytes", size);
2119 goto error;
2120 }
2121
2122 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2123 memcpy(buf, pw_info->password, pw_info->size);
2124 return pw_info->size;
2125
2126error:
2127 Py_XDECREF(fn_ret);
2128 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2129 pw_info->error = 1;
2130 return -1;
2131}
2132
Antoine Pitroub5218772010-05-21 09:56:06 +00002133static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002134load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2135{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002136 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2137 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002139 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2140 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2141 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002142 int r;
2143
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002144 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002145 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002146 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002147 "O|OO:load_cert_chain", kwlist,
2148 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002149 return NULL;
2150 if (keyfile == Py_None)
2151 keyfile = NULL;
2152 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2153 PyErr_SetString(PyExc_TypeError,
2154 "certfile should be a valid filesystem path");
2155 return NULL;
2156 }
2157 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2158 PyErr_SetString(PyExc_TypeError,
2159 "keyfile should be a valid filesystem path");
2160 goto error;
2161 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002162 if (password && password != Py_None) {
2163 if (PyCallable_Check(password)) {
2164 pw_info.callable = password;
2165 } else if (!_pwinfo_set(&pw_info, password,
2166 "password should be a string or callable")) {
2167 goto error;
2168 }
2169 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2170 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2171 }
2172 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2174 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002175 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002176 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002177 if (pw_info.error) {
2178 ERR_clear_error();
2179 /* the password callback has already set the error information */
2180 }
2181 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002182 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002183 PyErr_SetFromErrno(PyExc_IOError);
2184 }
2185 else {
2186 _setSSLError(NULL, 0, __FILE__, __LINE__);
2187 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002188 goto error;
2189 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002190 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002191 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2193 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002194 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2195 Py_CLEAR(keyfile_bytes);
2196 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002197 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002198 if (pw_info.error) {
2199 ERR_clear_error();
2200 /* the password callback has already set the error information */
2201 }
2202 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002203 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002204 PyErr_SetFromErrno(PyExc_IOError);
2205 }
2206 else {
2207 _setSSLError(NULL, 0, __FILE__, __LINE__);
2208 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002209 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002211 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002213 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002214 if (r != 1) {
2215 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002216 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002218 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2219 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002220 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221 Py_RETURN_NONE;
2222
2223error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002224 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2225 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002226 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002227 Py_XDECREF(keyfile_bytes);
2228 Py_XDECREF(certfile_bytes);
2229 return NULL;
2230}
2231
2232static PyObject *
2233load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2234{
2235 char *kwlist[] = {"cafile", "capath", NULL};
2236 PyObject *cafile = NULL, *capath = NULL;
2237 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2238 const char *cafile_buf = NULL, *capath_buf = NULL;
2239 int r;
2240
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002241 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002242 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2243 "|OO:load_verify_locations", kwlist,
2244 &cafile, &capath))
2245 return NULL;
2246 if (cafile == Py_None)
2247 cafile = NULL;
2248 if (capath == Py_None)
2249 capath = NULL;
2250 if (cafile == NULL && capath == NULL) {
2251 PyErr_SetString(PyExc_TypeError,
2252 "cafile and capath cannot be both omitted");
2253 return NULL;
2254 }
2255 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2256 PyErr_SetString(PyExc_TypeError,
2257 "cafile should be a valid filesystem path");
2258 return NULL;
2259 }
2260 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002261 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002262 PyErr_SetString(PyExc_TypeError,
2263 "capath should be a valid filesystem path");
2264 return NULL;
2265 }
2266 if (cafile)
2267 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2268 if (capath)
2269 capath_buf = PyBytes_AS_STRING(capath_bytes);
2270 PySSL_BEGIN_ALLOW_THREADS
2271 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2272 PySSL_END_ALLOW_THREADS
2273 Py_XDECREF(cafile_bytes);
2274 Py_XDECREF(capath_bytes);
2275 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002276 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002277 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002278 PyErr_SetFromErrno(PyExc_IOError);
2279 }
2280 else {
2281 _setSSLError(NULL, 0, __FILE__, __LINE__);
2282 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002283 return NULL;
2284 }
2285 Py_RETURN_NONE;
2286}
2287
2288static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002289load_dh_params(PySSLContext *self, PyObject *filepath)
2290{
2291 FILE *f;
2292 DH *dh;
2293
2294 f = _Py_fopen(filepath, "rb");
2295 if (f == NULL) {
2296 if (!PyErr_Occurred())
2297 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2298 return NULL;
2299 }
2300 errno = 0;
2301 PySSL_BEGIN_ALLOW_THREADS
2302 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002303 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002304 PySSL_END_ALLOW_THREADS
2305 if (dh == NULL) {
2306 if (errno != 0) {
2307 ERR_clear_error();
2308 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2309 }
2310 else {
2311 _setSSLError(NULL, 0, __FILE__, __LINE__);
2312 }
2313 return NULL;
2314 }
2315 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2316 _setSSLError(NULL, 0, __FILE__, __LINE__);
2317 DH_free(dh);
2318 Py_RETURN_NONE;
2319}
2320
2321static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002322context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2323{
Antoine Pitroud5323212010-10-22 18:19:07 +00002324 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002325 PySocketSockObject *sock;
2326 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002327 char *hostname = NULL;
2328 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002329
Antoine Pitroud5323212010-10-22 18:19:07 +00002330 /* server_hostname is either None (or absent), or to be encoded
2331 using the idna encoding. */
2332 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002333 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002334 &sock, &server_side,
2335 Py_TYPE(Py_None), &hostname_obj)) {
2336 PyErr_Clear();
2337 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2338 PySocketModule.Sock_Type,
2339 &sock, &server_side,
2340 "idna", &hostname))
2341 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002342#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002343 PyMem_Free(hostname);
2344 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2345 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002346 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002347#endif
2348 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002349
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002350 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002351 hostname);
2352 if (hostname != NULL)
2353 PyMem_Free(hostname);
2354 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002355}
2356
Antoine Pitroub0182c82010-10-12 20:09:02 +00002357static PyObject *
2358session_stats(PySSLContext *self, PyObject *unused)
2359{
2360 int r;
2361 PyObject *value, *stats = PyDict_New();
2362 if (!stats)
2363 return NULL;
2364
2365#define ADD_STATS(SSL_NAME, KEY_NAME) \
2366 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2367 if (value == NULL) \
2368 goto error; \
2369 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2370 Py_DECREF(value); \
2371 if (r < 0) \
2372 goto error;
2373
2374 ADD_STATS(number, "number");
2375 ADD_STATS(connect, "connect");
2376 ADD_STATS(connect_good, "connect_good");
2377 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2378 ADD_STATS(accept, "accept");
2379 ADD_STATS(accept_good, "accept_good");
2380 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2381 ADD_STATS(accept, "accept");
2382 ADD_STATS(hits, "hits");
2383 ADD_STATS(misses, "misses");
2384 ADD_STATS(timeouts, "timeouts");
2385 ADD_STATS(cache_full, "cache_full");
2386
2387#undef ADD_STATS
2388
2389 return stats;
2390
2391error:
2392 Py_DECREF(stats);
2393 return NULL;
2394}
2395
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002396static PyObject *
2397set_default_verify_paths(PySSLContext *self, PyObject *unused)
2398{
2399 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2400 _setSSLError(NULL, 0, __FILE__, __LINE__);
2401 return NULL;
2402 }
2403 Py_RETURN_NONE;
2404}
2405
Antoine Pitrou501da612011-12-21 09:27:41 +01002406#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002407static PyObject *
2408set_ecdh_curve(PySSLContext *self, PyObject *name)
2409{
2410 PyObject *name_bytes;
2411 int nid;
2412 EC_KEY *key;
2413
2414 if (!PyUnicode_FSConverter(name, &name_bytes))
2415 return NULL;
2416 assert(PyBytes_Check(name_bytes));
2417 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2418 Py_DECREF(name_bytes);
2419 if (nid == 0) {
2420 PyErr_Format(PyExc_ValueError,
2421 "unknown elliptic curve name %R", name);
2422 return NULL;
2423 }
2424 key = EC_KEY_new_by_curve_name(nid);
2425 if (key == NULL) {
2426 _setSSLError(NULL, 0, __FILE__, __LINE__);
2427 return NULL;
2428 }
2429 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2430 EC_KEY_free(key);
2431 Py_RETURN_NONE;
2432}
Antoine Pitrou501da612011-12-21 09:27:41 +01002433#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002434
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002435#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002436static int
2437_servername_callback(SSL *s, int *al, void *args)
2438{
2439 int ret;
2440 PySSLContext *ssl_ctx = (PySSLContext *) args;
2441 PySSLSocket *ssl;
2442 PyObject *servername_o;
2443 PyObject *servername_idna;
2444 PyObject *result;
2445 /* The high-level ssl.SSLSocket object */
2446 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002447 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002448#ifdef WITH_THREAD
2449 PyGILState_STATE gstate = PyGILState_Ensure();
2450#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002451
2452 if (ssl_ctx->set_hostname == NULL) {
2453 /* remove race condition in this the call back while if removing the
2454 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002455#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002456 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002457#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002458 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002459 }
2460
2461 ssl = SSL_get_app_data(s);
2462 assert(PySSLSocket_Check(ssl));
2463 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2464 Py_INCREF(ssl_socket);
2465 if (ssl_socket == Py_None) {
2466 goto error;
2467 }
Victor Stinner7e001512013-06-25 00:44:31 +02002468
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002469 if (servername == NULL) {
2470 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2471 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002472 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002473 else {
2474 servername_o = PyBytes_FromString(servername);
2475 if (servername_o == NULL) {
2476 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2477 goto error;
2478 }
2479 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2480 if (servername_idna == NULL) {
2481 PyErr_WriteUnraisable(servername_o);
2482 Py_DECREF(servername_o);
2483 goto error;
2484 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002485 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002486 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2487 servername_idna, ssl_ctx, NULL);
2488 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002489 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002490 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002491
2492 if (result == NULL) {
2493 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2494 *al = SSL_AD_HANDSHAKE_FAILURE;
2495 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2496 }
2497 else {
2498 if (result != Py_None) {
2499 *al = (int) PyLong_AsLong(result);
2500 if (PyErr_Occurred()) {
2501 PyErr_WriteUnraisable(result);
2502 *al = SSL_AD_INTERNAL_ERROR;
2503 }
2504 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2505 }
2506 else {
2507 ret = SSL_TLSEXT_ERR_OK;
2508 }
2509 Py_DECREF(result);
2510 }
2511
Stefan Krah20d60802013-01-17 17:07:17 +01002512#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002513 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002514#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002515 return ret;
2516
2517error:
2518 Py_DECREF(ssl_socket);
2519 *al = SSL_AD_INTERNAL_ERROR;
2520 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002521#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002522 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002523#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524 return ret;
2525}
Antoine Pitroua5963382013-03-30 16:39:00 +01002526#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002527
2528PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2529"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002530\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002531This sets a callback that will be called when a server name is provided by\n\
2532the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002533\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002534If the argument is None then the callback is disabled. The method is called\n\
2535with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002536See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002537
2538static PyObject *
2539set_servername_callback(PySSLContext *self, PyObject *args)
2540{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002541#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002542 PyObject *cb;
2543
2544 if (!PyArg_ParseTuple(args, "O", &cb))
2545 return NULL;
2546
2547 Py_CLEAR(self->set_hostname);
2548 if (cb == Py_None) {
2549 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2550 }
2551 else {
2552 if (!PyCallable_Check(cb)) {
2553 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2554 PyErr_SetString(PyExc_TypeError,
2555 "not a callable object");
2556 return NULL;
2557 }
2558 Py_INCREF(cb);
2559 self->set_hostname = cb;
2560 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2561 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2562 }
2563 Py_RETURN_NONE;
2564#else
2565 PyErr_SetString(PyExc_NotImplementedError,
2566 "The TLS extension servername callback, "
2567 "SSL_CTX_set_tlsext_servername_callback, "
2568 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002569 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002570#endif
2571}
2572
Christian Heimes9a5395a2013-06-17 15:44:12 +02002573PyDoc_STRVAR(PySSL_get_stats_doc,
2574"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2575\n\
2576Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2577CA extension and certificate revocation lists inside the context's cert\n\
2578store.\n\
2579NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2580been used at least once.");
2581
2582static PyObject *
2583cert_store_stats(PySSLContext *self)
2584{
2585 X509_STORE *store;
2586 X509_OBJECT *obj;
2587 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2588
2589 store = SSL_CTX_get_cert_store(self->ctx);
2590 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2591 obj = sk_X509_OBJECT_value(store->objs, i);
2592 switch (obj->type) {
2593 case X509_LU_X509:
2594 x509++;
2595 if (X509_check_ca(obj->data.x509)) {
2596 ca++;
2597 }
2598 break;
2599 case X509_LU_CRL:
2600 crl++;
2601 break;
2602 case X509_LU_PKEY:
2603 pkey++;
2604 break;
2605 default:
2606 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2607 * As far as I can tell they are internal states and never
2608 * stored in a cert store */
2609 break;
2610 }
2611 }
2612 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2613 "x509_ca", ca);
2614}
2615
2616PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2617"get_ca_certs([der=False]) -> list of loaded certificate\n\
2618\n\
2619Returns a list of dicts with information of loaded CA certs. If the\n\
2620optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2621NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2622been used at least once.");
2623
2624static PyObject *
2625get_ca_certs(PySSLContext *self, PyObject *args)
2626{
2627 X509_STORE *store;
2628 PyObject *ci = NULL, *rlist = NULL;
2629 int i;
2630 int binary_mode = 0;
2631
2632 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2633 return NULL;
2634 }
2635
2636 if ((rlist = PyList_New(0)) == NULL) {
2637 return NULL;
2638 }
2639
2640 store = SSL_CTX_get_cert_store(self->ctx);
2641 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2642 X509_OBJECT *obj;
2643 X509 *cert;
2644
2645 obj = sk_X509_OBJECT_value(store->objs, i);
2646 if (obj->type != X509_LU_X509) {
2647 /* not a x509 cert */
2648 continue;
2649 }
2650 /* CA for any purpose */
2651 cert = obj->data.x509;
2652 if (!X509_check_ca(cert)) {
2653 continue;
2654 }
2655 if (binary_mode) {
2656 ci = _certificate_to_der(cert);
2657 } else {
2658 ci = _decode_certificate(cert);
2659 }
2660 if (ci == NULL) {
2661 goto error;
2662 }
2663 if (PyList_Append(rlist, ci) == -1) {
2664 goto error;
2665 }
2666 Py_CLEAR(ci);
2667 }
2668 return rlist;
2669
2670 error:
2671 Py_XDECREF(ci);
2672 Py_XDECREF(rlist);
2673 return NULL;
2674}
2675
2676
Antoine Pitrou152efa22010-05-16 18:19:27 +00002677static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002678 {"options", (getter) get_options,
2679 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002680 {"verify_mode", (getter) get_verify_mode,
2681 (setter) set_verify_mode, NULL},
2682 {NULL}, /* sentinel */
2683};
2684
2685static struct PyMethodDef context_methods[] = {
2686 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2687 METH_VARARGS | METH_KEYWORDS, NULL},
2688 {"set_ciphers", (PyCFunction) set_ciphers,
2689 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002690 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2691 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002692 {"load_cert_chain", (PyCFunction) load_cert_chain,
2693 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002694 {"load_dh_params", (PyCFunction) load_dh_params,
2695 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002696 {"load_verify_locations", (PyCFunction) load_verify_locations,
2697 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002698 {"session_stats", (PyCFunction) session_stats,
2699 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002700 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2701 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002702#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002703 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2704 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002705#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002706 {"set_servername_callback", (PyCFunction) set_servername_callback,
2707 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002708 {"cert_store_stats", (PyCFunction) cert_store_stats,
2709 METH_NOARGS, PySSL_get_stats_doc},
2710 {"get_ca_certs", (PyCFunction) get_ca_certs,
2711 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002712 {NULL, NULL} /* sentinel */
2713};
2714
2715static PyTypeObject PySSLContext_Type = {
2716 PyVarObject_HEAD_INIT(NULL, 0)
2717 "_ssl._SSLContext", /*tp_name*/
2718 sizeof(PySSLContext), /*tp_basicsize*/
2719 0, /*tp_itemsize*/
2720 (destructor)context_dealloc, /*tp_dealloc*/
2721 0, /*tp_print*/
2722 0, /*tp_getattr*/
2723 0, /*tp_setattr*/
2724 0, /*tp_reserved*/
2725 0, /*tp_repr*/
2726 0, /*tp_as_number*/
2727 0, /*tp_as_sequence*/
2728 0, /*tp_as_mapping*/
2729 0, /*tp_hash*/
2730 0, /*tp_call*/
2731 0, /*tp_str*/
2732 0, /*tp_getattro*/
2733 0, /*tp_setattro*/
2734 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002737 (traverseproc) context_traverse, /*tp_traverse*/
2738 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002739 0, /*tp_richcompare*/
2740 0, /*tp_weaklistoffset*/
2741 0, /*tp_iter*/
2742 0, /*tp_iternext*/
2743 context_methods, /*tp_methods*/
2744 0, /*tp_members*/
2745 context_getsetlist, /*tp_getset*/
2746 0, /*tp_base*/
2747 0, /*tp_dict*/
2748 0, /*tp_descr_get*/
2749 0, /*tp_descr_set*/
2750 0, /*tp_dictoffset*/
2751 0, /*tp_init*/
2752 0, /*tp_alloc*/
2753 context_new, /*tp_new*/
2754};
2755
2756
2757
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002758#ifdef HAVE_OPENSSL_RAND
2759
2760/* helper routines for seeding the SSL PRNG */
2761static PyObject *
2762PySSL_RAND_add(PyObject *self, PyObject *args)
2763{
2764 char *buf;
2765 int len;
2766 double entropy;
2767
2768 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002769 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002770 RAND_add(buf, len, entropy);
2771 Py_INCREF(Py_None);
2772 return Py_None;
2773}
2774
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002775PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002776"RAND_add(string, entropy)\n\
2777\n\
2778Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002779bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002780
2781static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002782PySSL_RAND(int len, int pseudo)
2783{
2784 int ok;
2785 PyObject *bytes;
2786 unsigned long err;
2787 const char *errstr;
2788 PyObject *v;
2789
2790 bytes = PyBytes_FromStringAndSize(NULL, len);
2791 if (bytes == NULL)
2792 return NULL;
2793 if (pseudo) {
2794 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2795 if (ok == 0 || ok == 1)
2796 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2797 }
2798 else {
2799 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2800 if (ok == 1)
2801 return bytes;
2802 }
2803 Py_DECREF(bytes);
2804
2805 err = ERR_get_error();
2806 errstr = ERR_reason_error_string(err);
2807 v = Py_BuildValue("(ks)", err, errstr);
2808 if (v != NULL) {
2809 PyErr_SetObject(PySSLErrorObject, v);
2810 Py_DECREF(v);
2811 }
2812 return NULL;
2813}
2814
2815static PyObject *
2816PySSL_RAND_bytes(PyObject *self, PyObject *args)
2817{
2818 int len;
2819 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2820 return NULL;
2821 return PySSL_RAND(len, 0);
2822}
2823
2824PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2825"RAND_bytes(n) -> bytes\n\
2826\n\
2827Generate n cryptographically strong pseudo-random bytes.");
2828
2829static PyObject *
2830PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2831{
2832 int len;
2833 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2834 return NULL;
2835 return PySSL_RAND(len, 1);
2836}
2837
2838PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2839"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2840\n\
2841Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2842generated are cryptographically strong.");
2843
2844static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002845PySSL_RAND_status(PyObject *self)
2846{
Christian Heimes217cfd12007-12-02 14:31:20 +00002847 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002848}
2849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002850PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002851"RAND_status() -> 0 or 1\n\
2852\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002853Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2854It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2855using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002856
2857static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002858PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002859{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002860 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002861 int bytes;
2862
Jesus Ceac8754a12012-09-11 02:00:58 +02002863 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002864 PyUnicode_FSConverter, &path))
2865 return NULL;
2866
2867 bytes = RAND_egd(PyBytes_AsString(path));
2868 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002869 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002870 PyErr_SetString(PySSLErrorObject,
2871 "EGD connection failed or EGD did not return "
2872 "enough data to seed the PRNG");
2873 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002874 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002875 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002876}
2877
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002878PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002879"RAND_egd(path) -> bytes\n\
2880\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002881Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2882Returns number of bytes read. Raises SSLError if connection to EGD\n\
2883fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002884
2885#endif
2886
Christian Heimes6d7ad132013-06-09 18:02:55 +02002887PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2888"get_default_verify_paths() -> tuple\n\
2889\n\
2890Return search paths and environment vars that are used by SSLContext's\n\
2891set_default_verify_paths() to load default CAs. The values are\n\
2892'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2893
2894static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002895PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002896{
2897 PyObject *ofile_env = NULL;
2898 PyObject *ofile = NULL;
2899 PyObject *odir_env = NULL;
2900 PyObject *odir = NULL;
2901
2902#define convert(info, target) { \
2903 const char *tmp = (info); \
2904 target = NULL; \
2905 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2906 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2907 target = PyBytes_FromString(tmp); } \
2908 if (!target) goto error; \
2909 } while(0)
2910
2911 convert(X509_get_default_cert_file_env(), ofile_env);
2912 convert(X509_get_default_cert_file(), ofile);
2913 convert(X509_get_default_cert_dir_env(), odir_env);
2914 convert(X509_get_default_cert_dir(), odir);
2915#undef convert
2916
Christian Heimes200bb1b2013-06-14 15:14:29 +02002917 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002918
2919 error:
2920 Py_XDECREF(ofile_env);
2921 Py_XDECREF(ofile);
2922 Py_XDECREF(odir_env);
2923 Py_XDECREF(odir);
2924 return NULL;
2925}
2926
Christian Heimes46bebee2013-06-09 19:03:31 +02002927#ifdef _MSC_VER
2928PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2929"enum_cert_store(store_name, cert_type='certificate') -> []\n\
2930\n\
2931Retrieve certificates from Windows' cert store. store_name may be one of\n\
2932'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
2933cert_type must be either 'certificate' or 'crl'.\n\
2934The function returns a list of (bytes, encoding_type) tuples. The\n\
2935encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
2936PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00002937
Christian Heimes46bebee2013-06-09 19:03:31 +02002938static PyObject *
2939PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
2940{
2941 char *kwlist[] = {"store_name", "cert_type", NULL};
2942 char *store_name;
2943 char *cert_type = "certificate";
2944 HCERTSTORE hStore = NULL;
2945 PyObject *result = NULL;
2946 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
2947 int ok = 1;
2948
2949 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
2950 kwlist, &store_name, &cert_type)) {
2951 return NULL;
2952 }
2953
2954 if ((strcmp(cert_type, "certificate") != 0) &&
2955 (strcmp(cert_type, "crl") != 0)) {
2956 return PyErr_Format(PyExc_ValueError,
2957 "cert_type must be 'certificate' or 'crl', "
2958 "not %.100s", cert_type);
2959 }
2960
2961 if ((result = PyList_New(0)) == NULL) {
2962 return NULL;
2963 }
2964
2965 if ((hStore = CertOpenSystemStore(NULL, store_name)) == NULL) {
2966 Py_DECREF(result);
2967 return PyErr_SetFromWindowsErr(GetLastError());
2968 }
2969
2970 if (strcmp(cert_type, "certificate") == 0) {
2971 PCCERT_CONTEXT pCertCtx = NULL;
2972 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
2973 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
2974 pCertCtx->cbCertEncoded);
2975 if (!cert) {
2976 ok = 0;
2977 break;
2978 }
2979 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
2980 ok = 0;
2981 break;
2982 }
2983 if ((tup = PyTuple_New(2)) == NULL) {
2984 ok = 0;
2985 break;
2986 }
2987 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
2988 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
2989
2990 if (PyList_Append(result, tup) < 0) {
2991 ok = 0;
2992 break;
2993 }
2994 Py_CLEAR(tup);
2995 }
2996 if (pCertCtx) {
2997 /* loop ended with an error, need to clean up context manually */
2998 CertFreeCertificateContext(pCertCtx);
2999 }
3000 } else {
3001 PCCRL_CONTEXT pCrlCtx = NULL;
3002 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3003 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3004 pCrlCtx->cbCrlEncoded);
3005 if (!cert) {
3006 ok = 0;
3007 break;
3008 }
3009 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3010 ok = 0;
3011 break;
3012 }
3013 if ((tup = PyTuple_New(2)) == NULL) {
3014 ok = 0;
3015 break;
3016 }
3017 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3018 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3019
3020 if (PyList_Append(result, tup) < 0) {
3021 ok = 0;
3022 break;
3023 }
3024 Py_CLEAR(tup);
3025 }
3026 if (pCrlCtx) {
3027 /* loop ended with an error, need to clean up context manually */
3028 CertFreeCRLContext(pCrlCtx);
3029 }
3030 }
3031
3032 /* In error cases cert, enc and tup may not be NULL */
3033 Py_XDECREF(cert);
3034 Py_XDECREF(enc);
3035 Py_XDECREF(tup);
3036
3037 if (!CertCloseStore(hStore, 0)) {
3038 /* This error case might shadow another exception.*/
3039 Py_DECREF(result);
3040 return PyErr_SetFromWindowsErr(GetLastError());
3041 }
3042 if (ok) {
3043 return result;
3044 } else {
3045 Py_DECREF(result);
3046 return NULL;
3047 }
3048}
3049#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003050
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003051/* List of functions exported by this module. */
3052
3053static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003054 {"_test_decode_cert", PySSL_test_decode_certificate,
3055 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003056#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003057 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3058 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003059 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3060 PySSL_RAND_bytes_doc},
3061 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3062 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003063 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003064 PySSL_RAND_egd_doc},
3065 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3066 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003067#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003068 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003069 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003070#ifdef _MSC_VER
3071 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3072 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3073#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003074 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003075};
3076
3077
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003078#ifdef WITH_THREAD
3079
3080/* an implementation of OpenSSL threading operations in terms
3081 of the Python C thread library */
3082
3083static PyThread_type_lock *_ssl_locks = NULL;
3084
3085static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003086 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003087}
3088
Bill Janssen6e027db2007-11-15 22:23:56 +00003089static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003090 (int mode, int n, const char *file, int line) {
3091 /* this function is needed to perform locking on shared data
3092 structures. (Note that OpenSSL uses a number of global data
3093 structures that will be implicitly shared whenever multiple
3094 threads use OpenSSL.) Multi-threaded applications will
3095 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003097 locking_function() must be able to handle up to
3098 CRYPTO_num_locks() different mutex locks. It sets the n-th
3099 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003100
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003101 file and line are the file number of the function setting the
3102 lock. They can be useful for debugging.
3103 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003105 if ((_ssl_locks == NULL) ||
3106 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3107 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003109 if (mode & CRYPTO_LOCK) {
3110 PyThread_acquire_lock(_ssl_locks[n], 1);
3111 } else {
3112 PyThread_release_lock(_ssl_locks[n]);
3113 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003114}
3115
3116static int _setup_ssl_threads(void) {
3117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003118 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003120 if (_ssl_locks == NULL) {
3121 _ssl_locks_count = CRYPTO_num_locks();
3122 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003123 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003124 if (_ssl_locks == NULL)
3125 return 0;
3126 memset(_ssl_locks, 0,
3127 sizeof(PyThread_type_lock) * _ssl_locks_count);
3128 for (i = 0; i < _ssl_locks_count; i++) {
3129 _ssl_locks[i] = PyThread_allocate_lock();
3130 if (_ssl_locks[i] == NULL) {
3131 unsigned int j;
3132 for (j = 0; j < i; j++) {
3133 PyThread_free_lock(_ssl_locks[j]);
3134 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003135 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003136 return 0;
3137 }
3138 }
3139 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
3140 CRYPTO_set_id_callback(_ssl_thread_id_function);
3141 }
3142 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003143}
3144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003145#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003147PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003148"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003149for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003150
Martin v. Löwis1a214512008-06-11 05:26:20 +00003151
3152static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003153 PyModuleDef_HEAD_INIT,
3154 "_ssl",
3155 module_doc,
3156 -1,
3157 PySSL_methods,
3158 NULL,
3159 NULL,
3160 NULL,
3161 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003162};
3163
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003164
3165static void
3166parse_openssl_version(unsigned long libver,
3167 unsigned int *major, unsigned int *minor,
3168 unsigned int *fix, unsigned int *patch,
3169 unsigned int *status)
3170{
3171 *status = libver & 0xF;
3172 libver >>= 4;
3173 *patch = libver & 0xFF;
3174 libver >>= 8;
3175 *fix = libver & 0xFF;
3176 libver >>= 8;
3177 *minor = libver & 0xFF;
3178 libver >>= 8;
3179 *major = libver & 0xFF;
3180}
3181
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003182PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003183PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003184{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003185 PyObject *m, *d, *r;
3186 unsigned long libver;
3187 unsigned int major, minor, fix, patch, status;
3188 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003189 struct py_ssl_error_code *errcode;
3190 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003191
Antoine Pitrou152efa22010-05-16 18:19:27 +00003192 if (PyType_Ready(&PySSLContext_Type) < 0)
3193 return NULL;
3194 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003195 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003197 m = PyModule_Create(&_sslmodule);
3198 if (m == NULL)
3199 return NULL;
3200 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003202 /* Load _socket module and its C API */
3203 socket_api = PySocketModule_ImportModuleAndAPI();
3204 if (!socket_api)
3205 return NULL;
3206 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003208 /* Init OpenSSL */
3209 SSL_load_error_strings();
3210 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003211#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003212 /* note that this will start threading if not already started */
3213 if (!_setup_ssl_threads()) {
3214 return NULL;
3215 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003217 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003219 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003220 sslerror_type_slots[0].pfunc = PyExc_OSError;
3221 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003222 if (PySSLErrorObject == NULL)
3223 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003224
Antoine Pitrou41032a62011-10-27 23:56:55 +02003225 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3226 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3227 PySSLErrorObject, NULL);
3228 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3229 "ssl.SSLWantReadError", SSLWantReadError_doc,
3230 PySSLErrorObject, NULL);
3231 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3232 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3233 PySSLErrorObject, NULL);
3234 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3235 "ssl.SSLSyscallError", SSLSyscallError_doc,
3236 PySSLErrorObject, NULL);
3237 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3238 "ssl.SSLEOFError", SSLEOFError_doc,
3239 PySSLErrorObject, NULL);
3240 if (PySSLZeroReturnErrorObject == NULL
3241 || PySSLWantReadErrorObject == NULL
3242 || PySSLWantWriteErrorObject == NULL
3243 || PySSLSyscallErrorObject == NULL
3244 || PySSLEOFErrorObject == NULL)
3245 return NULL;
3246 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3247 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3248 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3249 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3250 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3251 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003252 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 if (PyDict_SetItemString(d, "_SSLContext",
3254 (PyObject *)&PySSLContext_Type) != 0)
3255 return NULL;
3256 if (PyDict_SetItemString(d, "_SSLSocket",
3257 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003258 return NULL;
3259 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3260 PY_SSL_ERROR_ZERO_RETURN);
3261 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3262 PY_SSL_ERROR_WANT_READ);
3263 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3264 PY_SSL_ERROR_WANT_WRITE);
3265 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3266 PY_SSL_ERROR_WANT_X509_LOOKUP);
3267 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3268 PY_SSL_ERROR_SYSCALL);
3269 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3270 PY_SSL_ERROR_SSL);
3271 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3272 PY_SSL_ERROR_WANT_CONNECT);
3273 /* non ssl.h errorcodes */
3274 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3275 PY_SSL_ERROR_EOF);
3276 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3277 PY_SSL_ERROR_INVALID_ERROR_CODE);
3278 /* cert requirements */
3279 PyModule_AddIntConstant(m, "CERT_NONE",
3280 PY_SSL_CERT_NONE);
3281 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3282 PY_SSL_CERT_OPTIONAL);
3283 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3284 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003285
Christian Heimes46bebee2013-06-09 19:03:31 +02003286#ifdef _MSC_VER
3287 /* Windows dwCertEncodingType */
3288 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3289 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3290#endif
3291
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 /* Alert Descriptions from ssl.h */
3293 /* note RESERVED constants no longer intended for use have been removed */
3294 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3295
3296#define ADD_AD_CONSTANT(s) \
3297 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3298 SSL_AD_##s)
3299
3300 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3301 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3302 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3303 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3304 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3305 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3306 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3307 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3308 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3309 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3310 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3311 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3312 ADD_AD_CONSTANT(UNKNOWN_CA);
3313 ADD_AD_CONSTANT(ACCESS_DENIED);
3314 ADD_AD_CONSTANT(DECODE_ERROR);
3315 ADD_AD_CONSTANT(DECRYPT_ERROR);
3316 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3317 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3318 ADD_AD_CONSTANT(INTERNAL_ERROR);
3319 ADD_AD_CONSTANT(USER_CANCELLED);
3320 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003321 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003322#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3323 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3324#endif
3325#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3326 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3327#endif
3328#ifdef SSL_AD_UNRECOGNIZED_NAME
3329 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3330#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003331#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3332 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3333#endif
3334#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3335 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3336#endif
3337#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3338 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3339#endif
3340
3341#undef ADD_AD_CONSTANT
3342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003343 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003344#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003345 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3346 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003347#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003348 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3349 PY_SSL_VERSION_SSL3);
3350 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3351 PY_SSL_VERSION_SSL23);
3352 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3353 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003354#if HAVE_TLSv1_2
3355 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3356 PY_SSL_VERSION_TLS1_1);
3357 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3358 PY_SSL_VERSION_TLS1_2);
3359#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003360
Antoine Pitroub5218772010-05-21 09:56:06 +00003361 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003362 PyModule_AddIntConstant(m, "OP_ALL",
3363 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003364 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3365 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3366 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003367#if HAVE_TLSv1_2
3368 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3369 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3370#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003371 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3372 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003373 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003374#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003375 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003376#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003377#ifdef SSL_OP_NO_COMPRESSION
3378 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3379 SSL_OP_NO_COMPRESSION);
3380#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003381
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003382#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003383 r = Py_True;
3384#else
3385 r = Py_False;
3386#endif
3387 Py_INCREF(r);
3388 PyModule_AddObject(m, "HAS_SNI", r);
3389
Antoine Pitroud6494802011-07-21 01:11:30 +02003390#if HAVE_OPENSSL_FINISHED
3391 r = Py_True;
3392#else
3393 r = Py_False;
3394#endif
3395 Py_INCREF(r);
3396 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3397
Antoine Pitrou501da612011-12-21 09:27:41 +01003398#ifdef OPENSSL_NO_ECDH
3399 r = Py_False;
3400#else
3401 r = Py_True;
3402#endif
3403 Py_INCREF(r);
3404 PyModule_AddObject(m, "HAS_ECDH", r);
3405
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003406#ifdef OPENSSL_NPN_NEGOTIATED
3407 r = Py_True;
3408#else
3409 r = Py_False;
3410#endif
3411 Py_INCREF(r);
3412 PyModule_AddObject(m, "HAS_NPN", r);
3413
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003414 /* Mappings for error codes */
3415 err_codes_to_names = PyDict_New();
3416 err_names_to_codes = PyDict_New();
3417 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3418 return NULL;
3419 errcode = error_codes;
3420 while (errcode->mnemonic != NULL) {
3421 PyObject *mnemo, *key;
3422 mnemo = PyUnicode_FromString(errcode->mnemonic);
3423 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3424 if (mnemo == NULL || key == NULL)
3425 return NULL;
3426 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3427 return NULL;
3428 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3429 return NULL;
3430 Py_DECREF(key);
3431 Py_DECREF(mnemo);
3432 errcode++;
3433 }
3434 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3435 return NULL;
3436 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3437 return NULL;
3438
3439 lib_codes_to_names = PyDict_New();
3440 if (lib_codes_to_names == NULL)
3441 return NULL;
3442 libcode = library_codes;
3443 while (libcode->library != NULL) {
3444 PyObject *mnemo, *key;
3445 key = PyLong_FromLong(libcode->code);
3446 mnemo = PyUnicode_FromString(libcode->library);
3447 if (key == NULL || mnemo == NULL)
3448 return NULL;
3449 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3450 return NULL;
3451 Py_DECREF(key);
3452 Py_DECREF(mnemo);
3453 libcode++;
3454 }
3455 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3456 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003458 /* OpenSSL version */
3459 /* SSLeay() gives us the version of the library linked against,
3460 which could be different from the headers version.
3461 */
3462 libver = SSLeay();
3463 r = PyLong_FromUnsignedLong(libver);
3464 if (r == NULL)
3465 return NULL;
3466 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3467 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003468 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003469 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3470 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3471 return NULL;
3472 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3473 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3474 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003475
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003476 libver = OPENSSL_VERSION_NUMBER;
3477 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3478 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3479 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3480 return NULL;
3481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003482 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003483}