blob: 48804ef920cfebc1e80309c2394d221f262aaa1b [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"
Christian Heimesf77b4b22013-08-21 13:26:05 +020021
22#ifdef HAVE_PTHREAD_ATFORK
23# include <pthread.h>
24#endif
25
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
29 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000037#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020039#define PySSL_BEGIN_ALLOW_THREADS_S(save)
40#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041#define PySSL_BEGIN_ALLOW_THREADS
42#define PySSL_BLOCK_THREADS
43#define PySSL_UNBLOCK_THREADS
44#define PySSL_END_ALLOW_THREADS
45
46#endif
47
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010048/* Include symbols from _socket module */
49#include "socketmodule.h"
50
51static PySocketModule_APIObject PySocketModule;
52
53#if defined(HAVE_POLL_H)
54#include <poll.h>
55#elif defined(HAVE_SYS_POLL_H)
56#include <sys/poll.h>
57#endif
58
59/* Include OpenSSL header files */
60#include "openssl/rsa.h"
61#include "openssl/crypto.h"
62#include "openssl/x509.h"
63#include "openssl/x509v3.h"
64#include "openssl/pem.h"
65#include "openssl/ssl.h"
66#include "openssl/err.h"
67#include "openssl/rand.h"
68
69/* SSL error object */
70static PyObject *PySSLErrorObject;
71static PyObject *PySSLZeroReturnErrorObject;
72static PyObject *PySSLWantReadErrorObject;
73static PyObject *PySSLWantWriteErrorObject;
74static PyObject *PySSLSyscallErrorObject;
75static PyObject *PySSLEOFErrorObject;
76
77/* Error mappings */
78static PyObject *err_codes_to_names;
79static PyObject *err_names_to_codes;
80static PyObject *lib_codes_to_names;
81
82struct py_ssl_error_code {
83 const char *mnemonic;
84 int library, reason;
85};
86struct py_ssl_library_code {
87 const char *library;
88 int code;
89};
90
91/* Include generated data (error codes) */
92#include "_ssl_data.h"
93
94/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
95 http://www.openssl.org/news/changelog.html
96 */
97#if OPENSSL_VERSION_NUMBER >= 0x10001000L
98# define HAVE_TLSv1_2 1
99#else
100# define HAVE_TLSv1_2 0
101#endif
102
Antoine Pitrouce852cb2013-03-30 16:45:04 +0100103/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100104 * This includes the SSL_set_SSL_CTX() function.
105 */
106#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
107# define HAVE_SNI 1
108#else
109# define HAVE_SNI 0
110#endif
111
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000112enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000113 /* these mirror ssl.h */
114 PY_SSL_ERROR_NONE,
115 PY_SSL_ERROR_SSL,
116 PY_SSL_ERROR_WANT_READ,
117 PY_SSL_ERROR_WANT_WRITE,
118 PY_SSL_ERROR_WANT_X509_LOOKUP,
119 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
120 PY_SSL_ERROR_ZERO_RETURN,
121 PY_SSL_ERROR_WANT_CONNECT,
122 /* start of non ssl.h errorcodes */
123 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
124 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
125 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000126};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127
Thomas Woutersed03b412007-08-28 21:37:11 +0000128enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000129 PY_SSL_CLIENT,
130 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000131};
132
133enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000134 PY_SSL_CERT_NONE,
135 PY_SSL_CERT_OPTIONAL,
136 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000137};
138
139enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +0200140#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000141 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200142#endif
143 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100145#if HAVE_TLSv1_2
146 PY_SSL_VERSION_TLS1,
147 PY_SSL_VERSION_TLS1_1,
148 PY_SSL_VERSION_TLS1_2
149#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000150 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000151#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100152};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200153
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154#ifdef WITH_THREAD
155
156/* serves as a flag to see whether we've initialized the SSL thread support. */
157/* 0 means no, greater than 0 means yes */
158
159static unsigned int _ssl_locks_count = 0;
160
161#endif /* def WITH_THREAD */
162
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000163/* SSL socket object */
164
165#define X509_NAME_MAXLEN 256
166
167/* RAND_* APIs got added to OpenSSL in 0.9.5 */
168#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
169# define HAVE_OPENSSL_RAND 1
170#else
171# undef HAVE_OPENSSL_RAND
172#endif
173
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000174/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
175 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
176 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
177#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000178# define HAVE_SSL_CTX_CLEAR_OPTIONS
179#else
180# undef HAVE_SSL_CTX_CLEAR_OPTIONS
181#endif
182
Antoine Pitroud6494802011-07-21 01:11:30 +0200183/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
184 * older SSL, but let's be safe */
185#define PySSL_CB_MAXLEN 128
186
187/* SSL_get_finished got added to OpenSSL in 0.9.5 */
188#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
189# define HAVE_OPENSSL_FINISHED 1
190#else
191# define HAVE_OPENSSL_FINISHED 0
192#endif
193
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100194/* ECDH support got added to OpenSSL in 0.9.8 */
195#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
196# define OPENSSL_NO_ECDH
197#endif
198
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100199/* compression support got added to OpenSSL in 0.9.8 */
200#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
201# define OPENSSL_NO_COMP
202#endif
203
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100204
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000205typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100208#ifdef OPENSSL_NPN_NEGOTIATED
209 char *npn_protocols;
210 int npn_protocols_len;
211#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100212#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200213 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100214#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000215} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000216
Antoine Pitrou152efa22010-05-16 18:19:27 +0000217typedef struct {
218 PyObject_HEAD
219 PyObject *Socket; /* weakref to socket on which we're layered */
220 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100221 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222 X509 *peer_cert;
223 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200224 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000226
Antoine Pitrou152efa22010-05-16 18:19:27 +0000227static PyTypeObject PySSLContext_Type;
228static PyTypeObject PySSLSocket_Type;
229
230static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
231static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000232static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000233 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000234static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
235static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000236
Antoine Pitrou152efa22010-05-16 18:19:27 +0000237#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
238#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000239
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000240typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000241 SOCKET_IS_NONBLOCKING,
242 SOCKET_IS_BLOCKING,
243 SOCKET_HAS_TIMED_OUT,
244 SOCKET_HAS_BEEN_CLOSED,
245 SOCKET_TOO_LARGE_FOR_SELECT,
246 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000247} timeout_state;
248
Thomas Woutersed03b412007-08-28 21:37:11 +0000249/* Wrap error strings with filename and line # */
250#define STRINGIFY1(x) #x
251#define STRINGIFY2(x) STRINGIFY1(x)
252#define ERRSTR1(x,y,z) (x ":" y ": " z)
253#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
254
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200255
256/*
257 * SSL errors.
258 */
259
260PyDoc_STRVAR(SSLError_doc,
261"An error occurred in the SSL implementation.");
262
263PyDoc_STRVAR(SSLZeroReturnError_doc,
264"SSL/TLS session closed cleanly.");
265
266PyDoc_STRVAR(SSLWantReadError_doc,
267"Non-blocking SSL socket needs to read more data\n"
268"before the requested operation can be completed.");
269
270PyDoc_STRVAR(SSLWantWriteError_doc,
271"Non-blocking SSL socket needs to write more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLSyscallError_doc,
275"System error when attempting SSL operation.");
276
277PyDoc_STRVAR(SSLEOFError_doc,
278"SSL/TLS connection terminated abruptly.");
279
280static PyObject *
281SSLError_str(PyOSErrorObject *self)
282{
283 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
284 Py_INCREF(self->strerror);
285 return self->strerror;
286 }
287 else
288 return PyObject_Str(self->args);
289}
290
291static PyType_Slot sslerror_type_slots[] = {
292 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
293 {Py_tp_doc, SSLError_doc},
294 {Py_tp_str, SSLError_str},
295 {0, 0},
296};
297
298static PyType_Spec sslerror_type_spec = {
299 "ssl.SSLError",
300 sizeof(PyOSErrorObject),
301 0,
302 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
303 sslerror_type_slots
304};
305
306static void
307fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
308 int lineno, unsigned long errcode)
309{
310 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
311 PyObject *init_value, *msg, *key;
312 _Py_IDENTIFIER(reason);
313 _Py_IDENTIFIER(library);
314
315 if (errcode != 0) {
316 int lib, reason;
317
318 lib = ERR_GET_LIB(errcode);
319 reason = ERR_GET_REASON(errcode);
320 key = Py_BuildValue("ii", lib, reason);
321 if (key == NULL)
322 goto fail;
323 reason_obj = PyDict_GetItem(err_codes_to_names, key);
324 Py_DECREF(key);
325 if (reason_obj == NULL) {
326 /* XXX if reason < 100, it might reflect a library number (!!) */
327 PyErr_Clear();
328 }
329 key = PyLong_FromLong(lib);
330 if (key == NULL)
331 goto fail;
332 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
333 Py_DECREF(key);
334 if (lib_obj == NULL) {
335 PyErr_Clear();
336 }
337 if (errstr == NULL)
338 errstr = ERR_reason_error_string(errcode);
339 }
340 if (errstr == NULL)
341 errstr = "unknown error";
342
343 if (reason_obj && lib_obj)
344 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
345 lib_obj, reason_obj, errstr, lineno);
346 else if (lib_obj)
347 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
348 lib_obj, errstr, lineno);
349 else
350 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
351
352 if (msg == NULL)
353 goto fail;
354 init_value = Py_BuildValue("iN", ssl_errno, msg);
355 err_value = PyObject_CallObject(type, init_value);
356 Py_DECREF(init_value);
357 if (err_value == NULL)
358 goto fail;
359 if (reason_obj == NULL)
360 reason_obj = Py_None;
361 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
362 goto fail;
363 if (lib_obj == NULL)
364 lib_obj = Py_None;
365 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
366 goto fail;
367 PyErr_SetObject(type, err_value);
368fail:
369 Py_XDECREF(err_value);
370}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371
372static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000373PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200375 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200376 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 int err;
378 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200379 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (obj->ssl != NULL) {
385 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 switch (err) {
388 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200389 errstr = "TLS/SSL connection has been closed (EOF)";
390 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 p = PY_SSL_ERROR_ZERO_RETURN;
392 break;
393 case SSL_ERROR_WANT_READ:
394 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 p = PY_SSL_ERROR_WANT_READ;
397 break;
398 case SSL_ERROR_WANT_WRITE:
399 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200400 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 errstr = "The operation did not complete (write)";
402 break;
403 case SSL_ERROR_WANT_X509_LOOKUP:
404 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000405 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 break;
407 case SSL_ERROR_WANT_CONNECT:
408 p = PY_SSL_ERROR_WANT_CONNECT;
409 errstr = "The operation did not complete (connect)";
410 break;
411 case SSL_ERROR_SYSCALL:
412 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 if (e == 0) {
414 PySocketSockObject *s
415 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
416 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000417 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200418 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000420 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000421 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000422 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000423 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200424 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000425 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200426 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200429 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000430 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000431 }
432 } else {
433 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 }
435 break;
436 }
437 case SSL_ERROR_SSL:
438 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200440 if (e == 0)
441 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000442 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000443 break;
444 }
445 default:
446 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
447 errstr = "Invalid error code";
448 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200450 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000451 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000453}
454
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455static PyObject *
456_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
457
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200460 else
461 errcode = 0;
462 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000463 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000464 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465}
466
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467/*
468 * SSL objects
469 */
470
Antoine Pitrou152efa22010-05-16 18:19:27 +0000471static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100472newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000473 enum py_ssl_server_or_client socket_type,
474 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000475{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000476 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100477 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200478 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000479
Antoine Pitrou152efa22010-05-16 18:19:27 +0000480 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 if (self == NULL)
482 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000484 self->peer_cert = NULL;
485 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100487 self->ctx = sslctx;
488 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 /* Make sure the SSL error state is initialized */
491 (void) ERR_get_state();
492 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000498 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200499 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000500#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200501 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000502#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200503 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000504
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100505#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000506 if (server_hostname != NULL)
507 SSL_set_tlsext_host_name(self->ssl, server_hostname);
508#endif
509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000510 /* If the socket is in non-blocking mode or timeout mode, set the BIO
511 * to non-blocking mode (blocking is the default)
512 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000513 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
515 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
516 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 PySSL_BEGIN_ALLOW_THREADS
519 if (socket_type == PY_SSL_CLIENT)
520 SSL_set_connect_state(self->ssl);
521 else
522 SSL_set_accept_state(self->ssl);
523 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000524
Antoine Pitroud6494802011-07-21 01:11:30 +0200525 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000526 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528}
529
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000530/* SSL object methods */
531
Antoine Pitrou152efa22010-05-16 18:19:27 +0000532static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000533{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 int ret;
535 int err;
536 int sockstate, nonblocking;
537 PySocketSockObject *sock
538 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 if (((PyObject*)sock) == Py_None) {
541 _setSSLError("Underlying socket connection gone",
542 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
543 return NULL;
544 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000545 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 /* just in case the blocking state of the socket has been changed */
548 nonblocking = (sock->sock_timeout >= 0.0);
549 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
550 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 /* Actually negotiate SSL connection */
553 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000555 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 ret = SSL_do_handshake(self->ssl);
557 err = SSL_get_error(self->ssl, ret);
558 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000559 if (PyErr_CheckSignals())
560 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 if (err == SSL_ERROR_WANT_READ) {
562 sockstate = check_socket_and_wait_for_timeout(sock, 0);
563 } else if (err == SSL_ERROR_WANT_WRITE) {
564 sockstate = check_socket_and_wait_for_timeout(sock, 1);
565 } else {
566 sockstate = SOCKET_OPERATION_OK;
567 }
568 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000569 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000570 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
573 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000574 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000575 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
577 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000578 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
581 break;
582 }
583 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000584 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 if (ret < 1)
586 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 if (self->peer_cert)
589 X509_free (self->peer_cert);
590 PySSL_BEGIN_ALLOW_THREADS
591 self->peer_cert = SSL_get_peer_certificate(self->ssl);
592 PySSL_END_ALLOW_THREADS
593
594 Py_INCREF(Py_None);
595 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000596
597error:
598 Py_DECREF(sock);
599 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000600}
601
Thomas Woutersed03b412007-08-28 21:37:11 +0000602static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 char namebuf[X509_NAME_MAXLEN];
606 int buflen;
607 PyObject *name_obj;
608 PyObject *value_obj;
609 PyObject *attr;
610 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
613 if (buflen < 0) {
614 _setSSLError(NULL, 0, __FILE__, __LINE__);
615 goto fail;
616 }
617 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
618 if (name_obj == NULL)
619 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
622 if (buflen < 0) {
623 _setSSLError(NULL, 0, __FILE__, __LINE__);
624 Py_DECREF(name_obj);
625 goto fail;
626 }
627 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000628 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 OPENSSL_free(valuebuf);
630 if (value_obj == NULL) {
631 Py_DECREF(name_obj);
632 goto fail;
633 }
634 attr = PyTuple_New(2);
635 if (attr == NULL) {
636 Py_DECREF(name_obj);
637 Py_DECREF(value_obj);
638 goto fail;
639 }
640 PyTuple_SET_ITEM(attr, 0, name_obj);
641 PyTuple_SET_ITEM(attr, 1, value_obj);
642 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000643
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000646}
647
648static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000650{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
652 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
653 PyObject *rdnt;
654 PyObject *attr = NULL; /* tuple to hold an attribute */
655 int entry_count = X509_NAME_entry_count(xname);
656 X509_NAME_ENTRY *entry;
657 ASN1_OBJECT *name;
658 ASN1_STRING *value;
659 int index_counter;
660 int rdn_level = -1;
661 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 dn = PyList_New(0);
664 if (dn == NULL)
665 return NULL;
666 /* now create another tuple to hold the top-level RDN */
667 rdn = PyList_New(0);
668 if (rdn == NULL)
669 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000671 for (index_counter = 0;
672 index_counter < entry_count;
673 index_counter++)
674 {
675 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 /* check to see if we've gotten to a new RDN */
678 if (rdn_level >= 0) {
679 if (rdn_level != entry->set) {
680 /* yes, new RDN */
681 /* add old RDN to DN */
682 rdnt = PyList_AsTuple(rdn);
683 Py_DECREF(rdn);
684 if (rdnt == NULL)
685 goto fail0;
686 retcode = PyList_Append(dn, rdnt);
687 Py_DECREF(rdnt);
688 if (retcode < 0)
689 goto fail0;
690 /* create new RDN */
691 rdn = PyList_New(0);
692 if (rdn == NULL)
693 goto fail0;
694 }
695 }
696 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 /* now add this attribute to the current RDN */
699 name = X509_NAME_ENTRY_get_object(entry);
700 value = X509_NAME_ENTRY_get_data(entry);
701 attr = _create_tuple_for_attribute(name, value);
702 /*
703 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
704 entry->set,
705 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
706 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
707 */
708 if (attr == NULL)
709 goto fail1;
710 retcode = PyList_Append(rdn, attr);
711 Py_DECREF(attr);
712 if (retcode < 0)
713 goto fail1;
714 }
715 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100716 if (rdn != NULL) {
717 if (PyList_GET_SIZE(rdn) > 0) {
718 rdnt = PyList_AsTuple(rdn);
719 Py_DECREF(rdn);
720 if (rdnt == NULL)
721 goto fail0;
722 retcode = PyList_Append(dn, rdnt);
723 Py_DECREF(rdnt);
724 if (retcode < 0)
725 goto fail0;
726 }
727 else {
728 Py_DECREF(rdn);
729 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 /* convert list to tuple */
733 rdnt = PyList_AsTuple(dn);
734 Py_DECREF(dn);
735 if (rdnt == NULL)
736 return NULL;
737 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738
739 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741
742 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 Py_XDECREF(dn);
744 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745}
746
747static PyObject *
748_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 /* this code follows the procedure outlined in
751 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
752 function to extract the STACK_OF(GENERAL_NAME),
753 then iterates through the stack to add the
754 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 int i, j;
757 PyObject *peer_alt_names = Py_None;
758 PyObject *v, *t;
759 X509_EXTENSION *ext = NULL;
760 GENERAL_NAMES *names = NULL;
761 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000762 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 BIO *biobuf = NULL;
764 char buf[2048];
765 char *vptr;
766 int len;
767 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000768#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000770#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000772#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 if (certificate == NULL)
775 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 /* get a memory buffer */
778 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200780 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 while ((i = X509_get_ext_by_NID(
782 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 if (peer_alt_names == Py_None) {
785 peer_alt_names = PyList_New(0);
786 if (peer_alt_names == NULL)
787 goto fail;
788 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 /* now decode the altName */
791 ext = X509_get_ext(certificate, i);
792 if(!(method = X509V3_EXT_get(ext))) {
793 PyErr_SetString
794 (PySSLErrorObject,
795 ERRSTR("No method for internalizing subjectAltName!"));
796 goto fail;
797 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 p = ext->value->data;
800 if (method->it)
801 names = (GENERAL_NAMES*)
802 (ASN1_item_d2i(NULL,
803 &p,
804 ext->value->length,
805 ASN1_ITEM_ptr(method->it)));
806 else
807 names = (GENERAL_NAMES*)
808 (method->d2i(NULL,
809 &p,
810 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200814 int gntype;
815 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200818 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200819 switch (gntype) {
820 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 /* we special-case DirName as a tuple of
822 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 t = PyTuple_New(2);
825 if (t == NULL) {
826 goto fail;
827 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 v = PyUnicode_FromString("DirName");
830 if (v == NULL) {
831 Py_DECREF(t);
832 goto fail;
833 }
834 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 v = _create_tuple_for_X509_NAME (name->d.dirn);
837 if (v == NULL) {
838 Py_DECREF(t);
839 goto fail;
840 }
841 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200842 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000843
Christian Heimes824f7f32013-08-17 00:54:47 +0200844 case GEN_EMAIL:
845 case GEN_DNS:
846 case GEN_URI:
847 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
848 correctly, CVE-2013-4238 */
849 t = PyTuple_New(2);
850 if (t == NULL)
851 goto fail;
852 switch (gntype) {
853 case GEN_EMAIL:
854 v = PyUnicode_FromString("email");
855 as = name->d.rfc822Name;
856 break;
857 case GEN_DNS:
858 v = PyUnicode_FromString("DNS");
859 as = name->d.dNSName;
860 break;
861 case GEN_URI:
862 v = PyUnicode_FromString("URI");
863 as = name->d.uniformResourceIdentifier;
864 break;
865 }
866 if (v == NULL) {
867 Py_DECREF(t);
868 goto fail;
869 }
870 PyTuple_SET_ITEM(t, 0, v);
871 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
872 ASN1_STRING_length(as));
873 if (v == NULL) {
874 Py_DECREF(t);
875 goto fail;
876 }
877 PyTuple_SET_ITEM(t, 1, v);
878 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Christian Heimes824f7f32013-08-17 00:54:47 +0200880 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200882 switch (gntype) {
883 /* check for new general name type */
884 case GEN_OTHERNAME:
885 case GEN_X400:
886 case GEN_EDIPARTY:
887 case GEN_IPADD:
888 case GEN_RID:
889 break;
890 default:
891 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
892 "Unknown general name type %d",
893 gntype) == -1) {
894 goto fail;
895 }
896 break;
897 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 (void) BIO_reset(biobuf);
899 GENERAL_NAME_print(biobuf, name);
900 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
901 if (len < 0) {
902 _setSSLError(NULL, 0, __FILE__, __LINE__);
903 goto fail;
904 }
905 vptr = strchr(buf, ':');
906 if (vptr == NULL)
907 goto fail;
908 t = PyTuple_New(2);
909 if (t == NULL)
910 goto fail;
911 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
912 if (v == NULL) {
913 Py_DECREF(t);
914 goto fail;
915 }
916 PyTuple_SET_ITEM(t, 0, v);
917 v = PyUnicode_FromStringAndSize((vptr + 1),
918 (len - (vptr - buf + 1)));
919 if (v == NULL) {
920 Py_DECREF(t);
921 goto fail;
922 }
923 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200924 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 if (PyList_Append(peer_alt_names, t) < 0) {
930 Py_DECREF(t);
931 goto fail;
932 }
933 Py_DECREF(t);
934 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100935 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 }
937 BIO_free(biobuf);
938 if (peer_alt_names != Py_None) {
939 v = PyList_AsTuple(peer_alt_names);
940 Py_DECREF(peer_alt_names);
941 return v;
942 } else {
943 return peer_alt_names;
944 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000945
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946
947 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 if (biobuf != NULL)
949 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 if (peer_alt_names != Py_None) {
952 Py_XDECREF(peer_alt_names);
953 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956}
957
958static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000959_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PyObject *retval = NULL;
962 BIO *biobuf = NULL;
963 PyObject *peer;
964 PyObject *peer_alt_names = NULL;
965 PyObject *issuer;
966 PyObject *version;
967 PyObject *sn_obj;
968 ASN1_INTEGER *serialNumber;
969 char buf[2048];
970 int len;
971 ASN1_TIME *notBefore, *notAfter;
972 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 retval = PyDict_New();
975 if (retval == NULL)
976 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 peer = _create_tuple_for_X509_NAME(
979 X509_get_subject_name(certificate));
980 if (peer == NULL)
981 goto fail0;
982 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
983 Py_DECREF(peer);
984 goto fail0;
985 }
986 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000987
Antoine Pitroufb046912010-11-09 20:21:19 +0000988 issuer = _create_tuple_for_X509_NAME(
989 X509_get_issuer_name(certificate));
990 if (issuer == NULL)
991 goto fail0;
992 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000993 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000994 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000996 Py_DECREF(issuer);
997
998 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200999 if (version == NULL)
1000 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001001 if (PyDict_SetItemString(retval, "version", version) < 0) {
1002 Py_DECREF(version);
1003 goto fail0;
1004 }
1005 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* get a memory buffer */
1008 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001009
Antoine Pitroufb046912010-11-09 20:21:19 +00001010 (void) BIO_reset(biobuf);
1011 serialNumber = X509_get_serialNumber(certificate);
1012 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1013 i2a_ASN1_INTEGER(biobuf, serialNumber);
1014 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1015 if (len < 0) {
1016 _setSSLError(NULL, 0, __FILE__, __LINE__);
1017 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001019 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1020 if (sn_obj == NULL)
1021 goto fail1;
1022 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1023 Py_DECREF(sn_obj);
1024 goto fail1;
1025 }
1026 Py_DECREF(sn_obj);
1027
1028 (void) BIO_reset(biobuf);
1029 notBefore = X509_get_notBefore(certificate);
1030 ASN1_TIME_print(biobuf, notBefore);
1031 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1032 if (len < 0) {
1033 _setSSLError(NULL, 0, __FILE__, __LINE__);
1034 goto fail1;
1035 }
1036 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1037 if (pnotBefore == NULL)
1038 goto fail1;
1039 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1040 Py_DECREF(pnotBefore);
1041 goto fail1;
1042 }
1043 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 (void) BIO_reset(biobuf);
1046 notAfter = X509_get_notAfter(certificate);
1047 ASN1_TIME_print(biobuf, notAfter);
1048 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1049 if (len < 0) {
1050 _setSSLError(NULL, 0, __FILE__, __LINE__);
1051 goto fail1;
1052 }
1053 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1054 if (pnotAfter == NULL)
1055 goto fail1;
1056 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1057 Py_DECREF(pnotAfter);
1058 goto fail1;
1059 }
1060 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 peer_alt_names = _get_peer_alt_names(certificate);
1065 if (peer_alt_names == NULL)
1066 goto fail1;
1067 else if (peer_alt_names != Py_None) {
1068 if (PyDict_SetItemString(retval, "subjectAltName",
1069 peer_alt_names) < 0) {
1070 Py_DECREF(peer_alt_names);
1071 goto fail1;
1072 }
1073 Py_DECREF(peer_alt_names);
1074 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 BIO_free(biobuf);
1077 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001078
1079 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 if (biobuf != NULL)
1081 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001082 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 Py_XDECREF(retval);
1084 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001085}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001086
Christian Heimes9a5395a2013-06-17 15:44:12 +02001087static PyObject *
1088_certificate_to_der(X509 *certificate)
1089{
1090 unsigned char *bytes_buf = NULL;
1091 int len;
1092 PyObject *retval;
1093
1094 bytes_buf = NULL;
1095 len = i2d_X509(certificate, &bytes_buf);
1096 if (len < 0) {
1097 _setSSLError(NULL, 0, __FILE__, __LINE__);
1098 return NULL;
1099 }
1100 /* this is actually an immutable bytes sequence */
1101 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1102 OPENSSL_free(bytes_buf);
1103 return retval;
1104}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105
1106static PyObject *
1107PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001110 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 X509 *x=NULL;
1112 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113
Antoine Pitroufb046912010-11-09 20:21:19 +00001114 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1115 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1119 PyErr_SetString(PySSLErrorObject,
1120 "Can't malloc memory to read file");
1121 goto fail0;
1122 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Victor Stinner3800e1e2010-05-16 21:23:48 +00001124 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 PyErr_SetString(PySSLErrorObject,
1126 "Can't open file");
1127 goto fail0;
1128 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1131 if (x == NULL) {
1132 PyErr_SetString(PySSLErrorObject,
1133 "Error decoding PEM-encoded file");
1134 goto fail0;
1135 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroufb046912010-11-09 20:21:19 +00001137 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001138 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
1140 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001141 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 if (cert != NULL) BIO_free(cert);
1143 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144}
1145
1146
1147static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001148PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001151 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152
Antoine Pitrou721738f2012-08-15 23:20:39 +02001153 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 if (!self->peer_cert)
1157 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
Antoine Pitrou721738f2012-08-15 23:20:39 +02001159 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001161 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001163 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 if ((verification & SSL_VERIFY_PEER) == 0)
1165 return PyDict_New();
1166 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001167 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001169}
1170
1171PyDoc_STRVAR(PySSL_peercert_doc,
1172"peer_certificate([der=False]) -> certificate\n\
1173\n\
1174Returns the certificate for the peer. If no certificate was provided,\n\
1175returns None. If a certificate was provided, but not validated, returns\n\
1176an empty dictionary. Otherwise returns a dict containing information\n\
1177about the peer certificate.\n\
1178\n\
1179If the optional argument is True, returns a DER-encoded copy of the\n\
1180peer certificate, or None if no certificate was provided. This will\n\
1181return the certificate even if it wasn't validated.");
1182
Antoine Pitrou152efa22010-05-16 18:19:27 +00001183static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001186 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 char *cipher_name;
1188 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001191 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 current = SSL_get_current_cipher(self->ssl);
1193 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001194 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 retval = PyTuple_New(3);
1197 if (retval == NULL)
1198 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 cipher_name = (char *) SSL_CIPHER_get_name(current);
1201 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001202 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 PyTuple_SET_ITEM(retval, 0, Py_None);
1204 } else {
1205 v = PyUnicode_FromString(cipher_name);
1206 if (v == NULL)
1207 goto fail0;
1208 PyTuple_SET_ITEM(retval, 0, v);
1209 }
1210 cipher_protocol = SSL_CIPHER_get_version(current);
1211 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001212 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 PyTuple_SET_ITEM(retval, 1, Py_None);
1214 } else {
1215 v = PyUnicode_FromString(cipher_protocol);
1216 if (v == NULL)
1217 goto fail0;
1218 PyTuple_SET_ITEM(retval, 1, v);
1219 }
1220 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1221 if (v == NULL)
1222 goto fail0;
1223 PyTuple_SET_ITEM(retval, 2, v);
1224 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001225
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 Py_DECREF(retval);
1228 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229}
1230
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001231#ifdef OPENSSL_NPN_NEGOTIATED
1232static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1233 const unsigned char *out;
1234 unsigned int outlen;
1235
Victor Stinner4569cd52013-06-23 14:58:43 +02001236 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001237 &out, &outlen);
1238
1239 if (out == NULL)
1240 Py_RETURN_NONE;
1241 return PyUnicode_FromStringAndSize((char *) out, outlen);
1242}
1243#endif
1244
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001245static PyObject *PySSL_compression(PySSLSocket *self) {
1246#ifdef OPENSSL_NO_COMP
1247 Py_RETURN_NONE;
1248#else
1249 const COMP_METHOD *comp_method;
1250 const char *short_name;
1251
1252 if (self->ssl == NULL)
1253 Py_RETURN_NONE;
1254 comp_method = SSL_get_current_compression(self->ssl);
1255 if (comp_method == NULL || comp_method->type == NID_undef)
1256 Py_RETURN_NONE;
1257 short_name = OBJ_nid2sn(comp_method->type);
1258 if (short_name == NULL)
1259 Py_RETURN_NONE;
1260 return PyUnicode_DecodeFSDefault(short_name);
1261#endif
1262}
1263
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001264static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1265 Py_INCREF(self->ctx);
1266 return self->ctx;
1267}
1268
1269static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1270 void *closure) {
1271
1272 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001273#if !HAVE_SNI
1274 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1275 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001276 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001277#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001278 Py_INCREF(value);
1279 Py_DECREF(self->ctx);
1280 self->ctx = (PySSLContext *) value;
1281 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001282#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001283 } else {
1284 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1285 return -1;
1286 }
1287
1288 return 0;
1289}
1290
1291PyDoc_STRVAR(PySSL_set_context_doc,
1292"_setter_context(ctx)\n\
1293\
1294This changes the context associated with the SSLSocket. This is typically\n\
1295used from within a callback function set by the set_servername_callback\n\
1296on the SSLContext to change the certificate information associated with the\n\
1297SSLSocket before the cryptographic exchange handshake messages\n");
1298
1299
1300
Antoine Pitrou152efa22010-05-16 18:19:27 +00001301static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 if (self->peer_cert) /* Possible not to have one? */
1304 X509_free (self->peer_cert);
1305 if (self->ssl)
1306 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001308 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001310}
1311
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001312/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001313 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001314 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001315 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001316
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001317static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001318check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001319{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 fd_set fds;
1321 struct timeval tv;
1322 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1325 if (s->sock_timeout < 0.0)
1326 return SOCKET_IS_BLOCKING;
1327 else if (s->sock_timeout == 0.0)
1328 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* Guard against closed socket */
1331 if (s->sock_fd < 0)
1332 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* Prefer poll, if available, since you can poll() any fd
1335 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001336#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 {
1338 struct pollfd pollfd;
1339 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 pollfd.fd = s->sock_fd;
1342 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 /* s->sock_timeout is in seconds, timeout in ms */
1345 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1346 PySSL_BEGIN_ALLOW_THREADS
1347 rc = poll(&pollfd, 1, timeout);
1348 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 goto normal_return;
1351 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001352#endif
1353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001355 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 /* Construct the arguments to select */
1359 tv.tv_sec = (int)s->sock_timeout;
1360 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1361 FD_ZERO(&fds);
1362 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 /* See if the socket is ready */
1365 PySSL_BEGIN_ALLOW_THREADS
1366 if (writing)
1367 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1368 else
1369 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1370 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001371
Bill Janssen6e027db2007-11-15 22:23:56 +00001372#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001373normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001374#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1376 (when we are able to write or when there's something to read) */
1377 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001378}
1379
Antoine Pitrou152efa22010-05-16 18:19:27 +00001380static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001381{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 Py_buffer buf;
1383 int len;
1384 int sockstate;
1385 int err;
1386 int nonblocking;
1387 PySocketSockObject *sock
1388 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 if (((PyObject*)sock) == Py_None) {
1391 _setSSLError("Underlying socket connection gone",
1392 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1393 return NULL;
1394 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001395 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001397 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1398 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001400 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401
Victor Stinner6efa9652013-06-25 00:42:31 +02001402 if (buf.len > INT_MAX) {
1403 PyErr_Format(PyExc_OverflowError,
1404 "string longer than %d bytes", INT_MAX);
1405 goto error;
1406 }
1407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 /* just in case the blocking state of the socket has been changed */
1409 nonblocking = (sock->sock_timeout >= 0.0);
1410 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1411 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1412
1413 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1414 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001415 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 "The write operation timed out");
1417 goto error;
1418 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1419 PyErr_SetString(PySSLErrorObject,
1420 "Underlying socket has been closed.");
1421 goto error;
1422 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1423 PyErr_SetString(PySSLErrorObject,
1424 "Underlying socket too large for select().");
1425 goto error;
1426 }
1427 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001429 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 err = SSL_get_error(self->ssl, len);
1431 PySSL_END_ALLOW_THREADS
1432 if (PyErr_CheckSignals()) {
1433 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001434 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001436 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001438 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 } else {
1440 sockstate = SOCKET_OPERATION_OK;
1441 }
1442 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001443 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 "The write operation timed out");
1445 goto error;
1446 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1447 PyErr_SetString(PySSLErrorObject,
1448 "Underlying socket has been closed.");
1449 goto error;
1450 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1451 break;
1452 }
1453 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001454
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001455 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 PyBuffer_Release(&buf);
1457 if (len > 0)
1458 return PyLong_FromLong(len);
1459 else
1460 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001461
1462error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001463 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 PyBuffer_Release(&buf);
1465 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001466}
1467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001468PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001469"write(s) -> len\n\
1470\n\
1471Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001472of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001473
Antoine Pitrou152efa22010-05-16 18:19:27 +00001474static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001475{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 PySSL_BEGIN_ALLOW_THREADS
1479 count = SSL_pending(self->ssl);
1480 PySSL_END_ALLOW_THREADS
1481 if (count < 0)
1482 return PySSL_SetError(self, count, __FILE__, __LINE__);
1483 else
1484 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001485}
1486
1487PyDoc_STRVAR(PySSL_SSLpending_doc,
1488"pending() -> count\n\
1489\n\
1490Returns the number of already decrypted bytes available for read,\n\
1491pending on the connection.\n");
1492
Antoine Pitrou152efa22010-05-16 18:19:27 +00001493static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001494{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 PyObject *dest = NULL;
1496 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001498 int len, count;
1499 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 int sockstate;
1501 int err;
1502 int nonblocking;
1503 PySocketSockObject *sock
1504 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 if (((PyObject*)sock) == Py_None) {
1507 _setSSLError("Underlying socket connection gone",
1508 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1509 return NULL;
1510 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001511 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001513 buf.obj = NULL;
1514 buf.buf = NULL;
1515 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001516 goto error;
1517
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001518 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1519 dest = PyBytes_FromStringAndSize(NULL, len);
1520 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001521 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001522 mem = PyBytes_AS_STRING(dest);
1523 }
1524 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001526 mem = buf.buf;
1527 if (len <= 0 || len > buf.len) {
1528 len = (int) buf.len;
1529 if (buf.len != len) {
1530 PyErr_SetString(PyExc_OverflowError,
1531 "maximum length can't fit in a C 'int'");
1532 goto error;
1533 }
1534 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 }
1536
1537 /* just in case the blocking state of the socket has been changed */
1538 nonblocking = (sock->sock_timeout >= 0.0);
1539 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1540 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1541
1542 /* first check if there are bytes ready to be read */
1543 PySSL_BEGIN_ALLOW_THREADS
1544 count = SSL_pending(self->ssl);
1545 PySSL_END_ALLOW_THREADS
1546
1547 if (!count) {
1548 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1549 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001550 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 "The read operation timed out");
1552 goto error;
1553 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1554 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001555 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 goto error;
1557 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1558 count = 0;
1559 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001560 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 }
1562 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 PySSL_BEGIN_ALLOW_THREADS
1564 count = SSL_read(self->ssl, mem, len);
1565 err = SSL_get_error(self->ssl, count);
1566 PySSL_END_ALLOW_THREADS
1567 if (PyErr_CheckSignals())
1568 goto error;
1569 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001570 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001572 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1574 (SSL_get_shutdown(self->ssl) ==
1575 SSL_RECEIVED_SHUTDOWN))
1576 {
1577 count = 0;
1578 goto done;
1579 } else {
1580 sockstate = SOCKET_OPERATION_OK;
1581 }
1582 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001583 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 "The read operation timed out");
1585 goto error;
1586 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1587 break;
1588 }
1589 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1590 if (count <= 0) {
1591 PySSL_SetError(self, count, __FILE__, __LINE__);
1592 goto error;
1593 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001594
1595done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001596 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001597 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001598 _PyBytes_Resize(&dest, count);
1599 return dest;
1600 }
1601 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 PyBuffer_Release(&buf);
1603 return PyLong_FromLong(count);
1604 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001605
1606error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001607 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001608 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001609 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001610 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001613}
1614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001615PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001616"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001617\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001618Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001619
Antoine Pitrou152efa22010-05-16 18:19:27 +00001620static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001621{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 int err, ssl_err, sockstate, nonblocking;
1623 int zeros = 0;
1624 PySocketSockObject *sock
1625 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 /* Guard against closed socket */
1628 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1629 _setSSLError("Underlying socket connection gone",
1630 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1631 return NULL;
1632 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001633 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634
1635 /* Just in case the blocking state of the socket has been changed */
1636 nonblocking = (sock->sock_timeout >= 0.0);
1637 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1638 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1639
1640 while (1) {
1641 PySSL_BEGIN_ALLOW_THREADS
1642 /* Disable read-ahead so that unwrap can work correctly.
1643 * Otherwise OpenSSL might read in too much data,
1644 * eating clear text data that happens to be
1645 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001646 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 * function is used and the shutdown_seen_zero != 0
1648 * condition is met.
1649 */
1650 if (self->shutdown_seen_zero)
1651 SSL_set_read_ahead(self->ssl, 0);
1652 err = SSL_shutdown(self->ssl);
1653 PySSL_END_ALLOW_THREADS
1654 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1655 if (err > 0)
1656 break;
1657 if (err == 0) {
1658 /* Don't loop endlessly; instead preserve legacy
1659 behaviour of trying SSL_shutdown() only twice.
1660 This looks necessary for OpenSSL < 0.9.8m */
1661 if (++zeros > 1)
1662 break;
1663 /* Shutdown was sent, now try receiving */
1664 self->shutdown_seen_zero = 1;
1665 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001666 }
1667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 /* Possibly retry shutdown until timeout or failure */
1669 ssl_err = SSL_get_error(self->ssl, err);
1670 if (ssl_err == SSL_ERROR_WANT_READ)
1671 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1672 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1673 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1674 else
1675 break;
1676 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1677 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001678 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001679 "The read operation timed out");
1680 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001681 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001683 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 }
1685 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1686 PyErr_SetString(PySSLErrorObject,
1687 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001688 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 }
1690 else if (sockstate != SOCKET_OPERATION_OK)
1691 /* Retain the SSL error code */
1692 break;
1693 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001694
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001695 if (err < 0) {
1696 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001699 else
1700 /* It's already INCREF'ed */
1701 return (PyObject *) sock;
1702
1703error:
1704 Py_DECREF(sock);
1705 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001706}
1707
1708PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1709"shutdown(s) -> socket\n\
1710\n\
1711Does the SSL shutdown handshake with the remote end, and returns\n\
1712the underlying socket object.");
1713
Antoine Pitroud6494802011-07-21 01:11:30 +02001714#if HAVE_OPENSSL_FINISHED
1715static PyObject *
1716PySSL_tls_unique_cb(PySSLSocket *self)
1717{
1718 PyObject *retval = NULL;
1719 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001720 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001721
1722 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1723 /* if session is resumed XOR we are the client */
1724 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1725 }
1726 else {
1727 /* if a new session XOR we are the server */
1728 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1729 }
1730
1731 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001732 if (len == 0)
1733 Py_RETURN_NONE;
1734
1735 retval = PyBytes_FromStringAndSize(buf, len);
1736
1737 return retval;
1738}
1739
1740PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1741"tls_unique_cb() -> bytes\n\
1742\n\
1743Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1744\n\
1745If the TLS handshake is not yet complete, None is returned");
1746
1747#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001748
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001749static PyGetSetDef ssl_getsetlist[] = {
1750 {"context", (getter) PySSL_get_context,
1751 (setter) PySSL_set_context, PySSL_set_context_doc},
1752 {NULL}, /* sentinel */
1753};
1754
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001755static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1757 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1758 PySSL_SSLwrite_doc},
1759 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1760 PySSL_SSLread_doc},
1761 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1762 PySSL_SSLpending_doc},
1763 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1764 PySSL_peercert_doc},
1765 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001766#ifdef OPENSSL_NPN_NEGOTIATED
1767 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1768#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001769 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1771 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001772#if HAVE_OPENSSL_FINISHED
1773 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1774 PySSL_tls_unique_cb_doc},
1775#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001777};
1778
Antoine Pitrou152efa22010-05-16 18:19:27 +00001779static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001781 "_ssl._SSLSocket", /*tp_name*/
1782 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 0, /*tp_itemsize*/
1784 /* methods */
1785 (destructor)PySSL_dealloc, /*tp_dealloc*/
1786 0, /*tp_print*/
1787 0, /*tp_getattr*/
1788 0, /*tp_setattr*/
1789 0, /*tp_reserved*/
1790 0, /*tp_repr*/
1791 0, /*tp_as_number*/
1792 0, /*tp_as_sequence*/
1793 0, /*tp_as_mapping*/
1794 0, /*tp_hash*/
1795 0, /*tp_call*/
1796 0, /*tp_str*/
1797 0, /*tp_getattro*/
1798 0, /*tp_setattro*/
1799 0, /*tp_as_buffer*/
1800 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1801 0, /*tp_doc*/
1802 0, /*tp_traverse*/
1803 0, /*tp_clear*/
1804 0, /*tp_richcompare*/
1805 0, /*tp_weaklistoffset*/
1806 0, /*tp_iter*/
1807 0, /*tp_iternext*/
1808 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001809 0, /*tp_members*/
1810 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001811};
1812
Antoine Pitrou152efa22010-05-16 18:19:27 +00001813
1814/*
1815 * _SSLContext objects
1816 */
1817
1818static PyObject *
1819context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1820{
1821 char *kwlist[] = {"protocol", NULL};
1822 PySSLContext *self;
1823 int proto_version = PY_SSL_VERSION_SSL23;
1824 SSL_CTX *ctx = NULL;
1825
1826 if (!PyArg_ParseTupleAndKeywords(
1827 args, kwds, "i:_SSLContext", kwlist,
1828 &proto_version))
1829 return NULL;
1830
1831 PySSL_BEGIN_ALLOW_THREADS
1832 if (proto_version == PY_SSL_VERSION_TLS1)
1833 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001834#if HAVE_TLSv1_2
1835 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1836 ctx = SSL_CTX_new(TLSv1_1_method());
1837 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1838 ctx = SSL_CTX_new(TLSv1_2_method());
1839#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001840 else if (proto_version == PY_SSL_VERSION_SSL3)
1841 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001842#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001843 else if (proto_version == PY_SSL_VERSION_SSL2)
1844 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001845#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001846 else if (proto_version == PY_SSL_VERSION_SSL23)
1847 ctx = SSL_CTX_new(SSLv23_method());
1848 else
1849 proto_version = -1;
1850 PySSL_END_ALLOW_THREADS
1851
1852 if (proto_version == -1) {
1853 PyErr_SetString(PyExc_ValueError,
1854 "invalid protocol version");
1855 return NULL;
1856 }
1857 if (ctx == NULL) {
1858 PyErr_SetString(PySSLErrorObject,
1859 "failed to allocate SSL context");
1860 return NULL;
1861 }
1862
1863 assert(type != NULL && type->tp_alloc != NULL);
1864 self = (PySSLContext *) type->tp_alloc(type, 0);
1865 if (self == NULL) {
1866 SSL_CTX_free(ctx);
1867 return NULL;
1868 }
1869 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001870#ifdef OPENSSL_NPN_NEGOTIATED
1871 self->npn_protocols = NULL;
1872#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001873#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001874 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001875#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001876 /* Defaults */
1877 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001878 SSL_CTX_set_options(self->ctx,
1879 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001880
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001881#define SID_CTX "Python"
1882 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1883 sizeof(SID_CTX));
1884#undef SID_CTX
1885
Antoine Pitrou152efa22010-05-16 18:19:27 +00001886 return (PyObject *)self;
1887}
1888
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001889static int
1890context_traverse(PySSLContext *self, visitproc visit, void *arg)
1891{
1892#ifndef OPENSSL_NO_TLSEXT
1893 Py_VISIT(self->set_hostname);
1894#endif
1895 return 0;
1896}
1897
1898static int
1899context_clear(PySSLContext *self)
1900{
1901#ifndef OPENSSL_NO_TLSEXT
1902 Py_CLEAR(self->set_hostname);
1903#endif
1904 return 0;
1905}
1906
Antoine Pitrou152efa22010-05-16 18:19:27 +00001907static void
1908context_dealloc(PySSLContext *self)
1909{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001910 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001911 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001912#ifdef OPENSSL_NPN_NEGOTIATED
1913 PyMem_Free(self->npn_protocols);
1914#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915 Py_TYPE(self)->tp_free(self);
1916}
1917
1918static PyObject *
1919set_ciphers(PySSLContext *self, PyObject *args)
1920{
1921 int ret;
1922 const char *cipherlist;
1923
1924 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1925 return NULL;
1926 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1927 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001928 /* Clearing the error queue is necessary on some OpenSSL versions,
1929 otherwise the error will be reported again when another SSL call
1930 is done. */
1931 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001932 PyErr_SetString(PySSLErrorObject,
1933 "No cipher can be selected.");
1934 return NULL;
1935 }
1936 Py_RETURN_NONE;
1937}
1938
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001939#ifdef OPENSSL_NPN_NEGOTIATED
1940/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1941static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001942_advertiseNPN_cb(SSL *s,
1943 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001944 void *args)
1945{
1946 PySSLContext *ssl_ctx = (PySSLContext *) args;
1947
1948 if (ssl_ctx->npn_protocols == NULL) {
1949 *data = (unsigned char *) "";
1950 *len = 0;
1951 } else {
1952 *data = (unsigned char *) ssl_ctx->npn_protocols;
1953 *len = ssl_ctx->npn_protocols_len;
1954 }
1955
1956 return SSL_TLSEXT_ERR_OK;
1957}
1958/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1959static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001960_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001961 unsigned char **out, unsigned char *outlen,
1962 const unsigned char *server, unsigned int server_len,
1963 void *args)
1964{
1965 PySSLContext *ssl_ctx = (PySSLContext *) args;
1966
1967 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1968 int client_len;
1969
1970 if (client == NULL) {
1971 client = (unsigned char *) "";
1972 client_len = 0;
1973 } else {
1974 client_len = ssl_ctx->npn_protocols_len;
1975 }
1976
1977 SSL_select_next_proto(out, outlen,
1978 server, server_len,
1979 client, client_len);
1980
1981 return SSL_TLSEXT_ERR_OK;
1982}
1983#endif
1984
1985static PyObject *
1986_set_npn_protocols(PySSLContext *self, PyObject *args)
1987{
1988#ifdef OPENSSL_NPN_NEGOTIATED
1989 Py_buffer protos;
1990
1991 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1992 return NULL;
1993
Christian Heimes5cb31c92012-09-20 12:42:54 +02001994 if (self->npn_protocols != NULL) {
1995 PyMem_Free(self->npn_protocols);
1996 }
1997
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001998 self->npn_protocols = PyMem_Malloc(protos.len);
1999 if (self->npn_protocols == NULL) {
2000 PyBuffer_Release(&protos);
2001 return PyErr_NoMemory();
2002 }
2003 memcpy(self->npn_protocols, protos.buf, protos.len);
2004 self->npn_protocols_len = (int) protos.len;
2005
2006 /* set both server and client callbacks, because the context can
2007 * be used to create both types of sockets */
2008 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2009 _advertiseNPN_cb,
2010 self);
2011 SSL_CTX_set_next_proto_select_cb(self->ctx,
2012 _selectNPN_cb,
2013 self);
2014
2015 PyBuffer_Release(&protos);
2016 Py_RETURN_NONE;
2017#else
2018 PyErr_SetString(PyExc_NotImplementedError,
2019 "The NPN extension requires OpenSSL 1.0.1 or later.");
2020 return NULL;
2021#endif
2022}
2023
Antoine Pitrou152efa22010-05-16 18:19:27 +00002024static PyObject *
2025get_verify_mode(PySSLContext *self, void *c)
2026{
2027 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2028 case SSL_VERIFY_NONE:
2029 return PyLong_FromLong(PY_SSL_CERT_NONE);
2030 case SSL_VERIFY_PEER:
2031 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2032 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2033 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2034 }
2035 PyErr_SetString(PySSLErrorObject,
2036 "invalid return value from SSL_CTX_get_verify_mode");
2037 return NULL;
2038}
2039
2040static int
2041set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2042{
2043 int n, mode;
2044 if (!PyArg_Parse(arg, "i", &n))
2045 return -1;
2046 if (n == PY_SSL_CERT_NONE)
2047 mode = SSL_VERIFY_NONE;
2048 else if (n == PY_SSL_CERT_OPTIONAL)
2049 mode = SSL_VERIFY_PEER;
2050 else if (n == PY_SSL_CERT_REQUIRED)
2051 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2052 else {
2053 PyErr_SetString(PyExc_ValueError,
2054 "invalid value for verify_mode");
2055 return -1;
2056 }
2057 SSL_CTX_set_verify(self->ctx, mode, NULL);
2058 return 0;
2059}
2060
2061static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002062get_options(PySSLContext *self, void *c)
2063{
2064 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2065}
2066
2067static int
2068set_options(PySSLContext *self, PyObject *arg, void *c)
2069{
2070 long new_opts, opts, set, clear;
2071 if (!PyArg_Parse(arg, "l", &new_opts))
2072 return -1;
2073 opts = SSL_CTX_get_options(self->ctx);
2074 clear = opts & ~new_opts;
2075 set = ~opts & new_opts;
2076 if (clear) {
2077#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2078 SSL_CTX_clear_options(self->ctx, clear);
2079#else
2080 PyErr_SetString(PyExc_ValueError,
2081 "can't clear options before OpenSSL 0.9.8m");
2082 return -1;
2083#endif
2084 }
2085 if (set)
2086 SSL_CTX_set_options(self->ctx, set);
2087 return 0;
2088}
2089
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002090typedef struct {
2091 PyThreadState *thread_state;
2092 PyObject *callable;
2093 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002094 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002095 int error;
2096} _PySSLPasswordInfo;
2097
2098static int
2099_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2100 const char *bad_type_error)
2101{
2102 /* Set the password and size fields of a _PySSLPasswordInfo struct
2103 from a unicode, bytes, or byte array object.
2104 The password field will be dynamically allocated and must be freed
2105 by the caller */
2106 PyObject *password_bytes = NULL;
2107 const char *data = NULL;
2108 Py_ssize_t size;
2109
2110 if (PyUnicode_Check(password)) {
2111 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2112 if (!password_bytes) {
2113 goto error;
2114 }
2115 data = PyBytes_AS_STRING(password_bytes);
2116 size = PyBytes_GET_SIZE(password_bytes);
2117 } else if (PyBytes_Check(password)) {
2118 data = PyBytes_AS_STRING(password);
2119 size = PyBytes_GET_SIZE(password);
2120 } else if (PyByteArray_Check(password)) {
2121 data = PyByteArray_AS_STRING(password);
2122 size = PyByteArray_GET_SIZE(password);
2123 } else {
2124 PyErr_SetString(PyExc_TypeError, bad_type_error);
2125 goto error;
2126 }
2127
Victor Stinner9ee02032013-06-23 15:08:23 +02002128 if (size > (Py_ssize_t)INT_MAX) {
2129 PyErr_Format(PyExc_ValueError,
2130 "password cannot be longer than %d bytes", INT_MAX);
2131 goto error;
2132 }
2133
Victor Stinner11ebff22013-07-07 17:07:52 +02002134 PyMem_Free(pw_info->password);
2135 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002136 if (!pw_info->password) {
2137 PyErr_SetString(PyExc_MemoryError,
2138 "unable to allocate password buffer");
2139 goto error;
2140 }
2141 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002142 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002143
2144 Py_XDECREF(password_bytes);
2145 return 1;
2146
2147error:
2148 Py_XDECREF(password_bytes);
2149 return 0;
2150}
2151
2152static int
2153_password_callback(char *buf, int size, int rwflag, void *userdata)
2154{
2155 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2156 PyObject *fn_ret = NULL;
2157
2158 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2159
2160 if (pw_info->callable) {
2161 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2162 if (!fn_ret) {
2163 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2164 core python API, so we could use it to add a frame here */
2165 goto error;
2166 }
2167
2168 if (!_pwinfo_set(pw_info, fn_ret,
2169 "password callback must return a string")) {
2170 goto error;
2171 }
2172 Py_CLEAR(fn_ret);
2173 }
2174
2175 if (pw_info->size > size) {
2176 PyErr_Format(PyExc_ValueError,
2177 "password cannot be longer than %d bytes", size);
2178 goto error;
2179 }
2180
2181 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2182 memcpy(buf, pw_info->password, pw_info->size);
2183 return pw_info->size;
2184
2185error:
2186 Py_XDECREF(fn_ret);
2187 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2188 pw_info->error = 1;
2189 return -1;
2190}
2191
Antoine Pitroub5218772010-05-21 09:56:06 +00002192static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002193load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2194{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002195 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2196 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002197 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002198 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2199 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2200 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002201 int r;
2202
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002203 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002204 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002205 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002206 "O|OO:load_cert_chain", kwlist,
2207 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002208 return NULL;
2209 if (keyfile == Py_None)
2210 keyfile = NULL;
2211 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2212 PyErr_SetString(PyExc_TypeError,
2213 "certfile should be a valid filesystem path");
2214 return NULL;
2215 }
2216 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2217 PyErr_SetString(PyExc_TypeError,
2218 "keyfile should be a valid filesystem path");
2219 goto error;
2220 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002221 if (password && password != Py_None) {
2222 if (PyCallable_Check(password)) {
2223 pw_info.callable = password;
2224 } else if (!_pwinfo_set(&pw_info, password,
2225 "password should be a string or callable")) {
2226 goto error;
2227 }
2228 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2229 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2230 }
2231 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2233 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002234 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002235 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002236 if (pw_info.error) {
2237 ERR_clear_error();
2238 /* the password callback has already set the error information */
2239 }
2240 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002241 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002242 PyErr_SetFromErrno(PyExc_IOError);
2243 }
2244 else {
2245 _setSSLError(NULL, 0, __FILE__, __LINE__);
2246 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002247 goto error;
2248 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002249 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002250 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002251 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2252 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002253 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2254 Py_CLEAR(keyfile_bytes);
2255 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002256 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002257 if (pw_info.error) {
2258 ERR_clear_error();
2259 /* the password callback has already set the error information */
2260 }
2261 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002262 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002263 PyErr_SetFromErrno(PyExc_IOError);
2264 }
2265 else {
2266 _setSSLError(NULL, 0, __FILE__, __LINE__);
2267 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002268 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002269 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002270 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002271 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002272 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002273 if (r != 1) {
2274 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002275 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002276 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002277 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2278 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002279 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002280 Py_RETURN_NONE;
2281
2282error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002283 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2284 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002285 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002286 Py_XDECREF(keyfile_bytes);
2287 Py_XDECREF(certfile_bytes);
2288 return NULL;
2289}
2290
2291static PyObject *
2292load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2293{
2294 char *kwlist[] = {"cafile", "capath", NULL};
2295 PyObject *cafile = NULL, *capath = NULL;
2296 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2297 const char *cafile_buf = NULL, *capath_buf = NULL;
2298 int r;
2299
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002300 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002301 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2302 "|OO:load_verify_locations", kwlist,
2303 &cafile, &capath))
2304 return NULL;
2305 if (cafile == Py_None)
2306 cafile = NULL;
2307 if (capath == Py_None)
2308 capath = NULL;
2309 if (cafile == NULL && capath == NULL) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "cafile and capath cannot be both omitted");
2312 return NULL;
2313 }
2314 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2315 PyErr_SetString(PyExc_TypeError,
2316 "cafile should be a valid filesystem path");
2317 return NULL;
2318 }
2319 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002320 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002321 PyErr_SetString(PyExc_TypeError,
2322 "capath should be a valid filesystem path");
2323 return NULL;
2324 }
2325 if (cafile)
2326 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2327 if (capath)
2328 capath_buf = PyBytes_AS_STRING(capath_bytes);
2329 PySSL_BEGIN_ALLOW_THREADS
2330 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2331 PySSL_END_ALLOW_THREADS
2332 Py_XDECREF(cafile_bytes);
2333 Py_XDECREF(capath_bytes);
2334 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002335 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002336 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002337 PyErr_SetFromErrno(PyExc_IOError);
2338 }
2339 else {
2340 _setSSLError(NULL, 0, __FILE__, __LINE__);
2341 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002342 return NULL;
2343 }
2344 Py_RETURN_NONE;
2345}
2346
2347static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002348load_dh_params(PySSLContext *self, PyObject *filepath)
2349{
2350 FILE *f;
2351 DH *dh;
2352
Victor Stinnerdaf45552013-08-28 00:53:59 +02002353 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002354 if (f == NULL) {
2355 if (!PyErr_Occurred())
2356 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2357 return NULL;
2358 }
2359 errno = 0;
2360 PySSL_BEGIN_ALLOW_THREADS
2361 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002362 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002363 PySSL_END_ALLOW_THREADS
2364 if (dh == NULL) {
2365 if (errno != 0) {
2366 ERR_clear_error();
2367 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2368 }
2369 else {
2370 _setSSLError(NULL, 0, __FILE__, __LINE__);
2371 }
2372 return NULL;
2373 }
2374 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2375 _setSSLError(NULL, 0, __FILE__, __LINE__);
2376 DH_free(dh);
2377 Py_RETURN_NONE;
2378}
2379
2380static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002381context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2382{
Antoine Pitroud5323212010-10-22 18:19:07 +00002383 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002384 PySocketSockObject *sock;
2385 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002386 char *hostname = NULL;
2387 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002388
Antoine Pitroud5323212010-10-22 18:19:07 +00002389 /* server_hostname is either None (or absent), or to be encoded
2390 using the idna encoding. */
2391 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002392 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002393 &sock, &server_side,
2394 Py_TYPE(Py_None), &hostname_obj)) {
2395 PyErr_Clear();
2396 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2397 PySocketModule.Sock_Type,
2398 &sock, &server_side,
2399 "idna", &hostname))
2400 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002401#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002402 PyMem_Free(hostname);
2403 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2404 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002405 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002406#endif
2407 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002408
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002409 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002410 hostname);
2411 if (hostname != NULL)
2412 PyMem_Free(hostname);
2413 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414}
2415
Antoine Pitroub0182c82010-10-12 20:09:02 +00002416static PyObject *
2417session_stats(PySSLContext *self, PyObject *unused)
2418{
2419 int r;
2420 PyObject *value, *stats = PyDict_New();
2421 if (!stats)
2422 return NULL;
2423
2424#define ADD_STATS(SSL_NAME, KEY_NAME) \
2425 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2426 if (value == NULL) \
2427 goto error; \
2428 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2429 Py_DECREF(value); \
2430 if (r < 0) \
2431 goto error;
2432
2433 ADD_STATS(number, "number");
2434 ADD_STATS(connect, "connect");
2435 ADD_STATS(connect_good, "connect_good");
2436 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2437 ADD_STATS(accept, "accept");
2438 ADD_STATS(accept_good, "accept_good");
2439 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2440 ADD_STATS(accept, "accept");
2441 ADD_STATS(hits, "hits");
2442 ADD_STATS(misses, "misses");
2443 ADD_STATS(timeouts, "timeouts");
2444 ADD_STATS(cache_full, "cache_full");
2445
2446#undef ADD_STATS
2447
2448 return stats;
2449
2450error:
2451 Py_DECREF(stats);
2452 return NULL;
2453}
2454
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002455static PyObject *
2456set_default_verify_paths(PySSLContext *self, PyObject *unused)
2457{
2458 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2459 _setSSLError(NULL, 0, __FILE__, __LINE__);
2460 return NULL;
2461 }
2462 Py_RETURN_NONE;
2463}
2464
Antoine Pitrou501da612011-12-21 09:27:41 +01002465#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002466static PyObject *
2467set_ecdh_curve(PySSLContext *self, PyObject *name)
2468{
2469 PyObject *name_bytes;
2470 int nid;
2471 EC_KEY *key;
2472
2473 if (!PyUnicode_FSConverter(name, &name_bytes))
2474 return NULL;
2475 assert(PyBytes_Check(name_bytes));
2476 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2477 Py_DECREF(name_bytes);
2478 if (nid == 0) {
2479 PyErr_Format(PyExc_ValueError,
2480 "unknown elliptic curve name %R", name);
2481 return NULL;
2482 }
2483 key = EC_KEY_new_by_curve_name(nid);
2484 if (key == NULL) {
2485 _setSSLError(NULL, 0, __FILE__, __LINE__);
2486 return NULL;
2487 }
2488 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2489 EC_KEY_free(key);
2490 Py_RETURN_NONE;
2491}
Antoine Pitrou501da612011-12-21 09:27:41 +01002492#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002493
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002494#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002495static int
2496_servername_callback(SSL *s, int *al, void *args)
2497{
2498 int ret;
2499 PySSLContext *ssl_ctx = (PySSLContext *) args;
2500 PySSLSocket *ssl;
2501 PyObject *servername_o;
2502 PyObject *servername_idna;
2503 PyObject *result;
2504 /* The high-level ssl.SSLSocket object */
2505 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002506 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002507#ifdef WITH_THREAD
2508 PyGILState_STATE gstate = PyGILState_Ensure();
2509#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002510
2511 if (ssl_ctx->set_hostname == NULL) {
2512 /* remove race condition in this the call back while if removing the
2513 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002514#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002515 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002516#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002517 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002518 }
2519
2520 ssl = SSL_get_app_data(s);
2521 assert(PySSLSocket_Check(ssl));
2522 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2523 Py_INCREF(ssl_socket);
2524 if (ssl_socket == Py_None) {
2525 goto error;
2526 }
Victor Stinner7e001512013-06-25 00:44:31 +02002527
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002528 if (servername == NULL) {
2529 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2530 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002531 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002532 else {
2533 servername_o = PyBytes_FromString(servername);
2534 if (servername_o == NULL) {
2535 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2536 goto error;
2537 }
2538 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2539 if (servername_idna == NULL) {
2540 PyErr_WriteUnraisable(servername_o);
2541 Py_DECREF(servername_o);
2542 goto error;
2543 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002544 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002545 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2546 servername_idna, ssl_ctx, NULL);
2547 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002548 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002549 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002550
2551 if (result == NULL) {
2552 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2553 *al = SSL_AD_HANDSHAKE_FAILURE;
2554 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2555 }
2556 else {
2557 if (result != Py_None) {
2558 *al = (int) PyLong_AsLong(result);
2559 if (PyErr_Occurred()) {
2560 PyErr_WriteUnraisable(result);
2561 *al = SSL_AD_INTERNAL_ERROR;
2562 }
2563 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2564 }
2565 else {
2566 ret = SSL_TLSEXT_ERR_OK;
2567 }
2568 Py_DECREF(result);
2569 }
2570
Stefan Krah20d60802013-01-17 17:07:17 +01002571#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002572 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002573#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002574 return ret;
2575
2576error:
2577 Py_DECREF(ssl_socket);
2578 *al = SSL_AD_INTERNAL_ERROR;
2579 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002580#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002581 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002582#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002583 return ret;
2584}
Antoine Pitroua5963382013-03-30 16:39:00 +01002585#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002586
2587PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2588"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002589\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002590This sets a callback that will be called when a server name is provided by\n\
2591the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002592\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002593If the argument is None then the callback is disabled. The method is called\n\
2594with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002595See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002596
2597static PyObject *
2598set_servername_callback(PySSLContext *self, PyObject *args)
2599{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002600#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002601 PyObject *cb;
2602
2603 if (!PyArg_ParseTuple(args, "O", &cb))
2604 return NULL;
2605
2606 Py_CLEAR(self->set_hostname);
2607 if (cb == Py_None) {
2608 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2609 }
2610 else {
2611 if (!PyCallable_Check(cb)) {
2612 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2613 PyErr_SetString(PyExc_TypeError,
2614 "not a callable object");
2615 return NULL;
2616 }
2617 Py_INCREF(cb);
2618 self->set_hostname = cb;
2619 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2620 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2621 }
2622 Py_RETURN_NONE;
2623#else
2624 PyErr_SetString(PyExc_NotImplementedError,
2625 "The TLS extension servername callback, "
2626 "SSL_CTX_set_tlsext_servername_callback, "
2627 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002628 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002629#endif
2630}
2631
Christian Heimes9a5395a2013-06-17 15:44:12 +02002632PyDoc_STRVAR(PySSL_get_stats_doc,
2633"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2634\n\
2635Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2636CA extension and certificate revocation lists inside the context's cert\n\
2637store.\n\
2638NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2639been used at least once.");
2640
2641static PyObject *
2642cert_store_stats(PySSLContext *self)
2643{
2644 X509_STORE *store;
2645 X509_OBJECT *obj;
2646 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2647
2648 store = SSL_CTX_get_cert_store(self->ctx);
2649 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2650 obj = sk_X509_OBJECT_value(store->objs, i);
2651 switch (obj->type) {
2652 case X509_LU_X509:
2653 x509++;
2654 if (X509_check_ca(obj->data.x509)) {
2655 ca++;
2656 }
2657 break;
2658 case X509_LU_CRL:
2659 crl++;
2660 break;
2661 case X509_LU_PKEY:
2662 pkey++;
2663 break;
2664 default:
2665 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2666 * As far as I can tell they are internal states and never
2667 * stored in a cert store */
2668 break;
2669 }
2670 }
2671 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2672 "x509_ca", ca);
2673}
2674
2675PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2676"get_ca_certs([der=False]) -> list of loaded certificate\n\
2677\n\
2678Returns a list of dicts with information of loaded CA certs. If the\n\
2679optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2680NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2681been used at least once.");
2682
2683static PyObject *
2684get_ca_certs(PySSLContext *self, PyObject *args)
2685{
2686 X509_STORE *store;
2687 PyObject *ci = NULL, *rlist = NULL;
2688 int i;
2689 int binary_mode = 0;
2690
2691 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2692 return NULL;
2693 }
2694
2695 if ((rlist = PyList_New(0)) == NULL) {
2696 return NULL;
2697 }
2698
2699 store = SSL_CTX_get_cert_store(self->ctx);
2700 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2701 X509_OBJECT *obj;
2702 X509 *cert;
2703
2704 obj = sk_X509_OBJECT_value(store->objs, i);
2705 if (obj->type != X509_LU_X509) {
2706 /* not a x509 cert */
2707 continue;
2708 }
2709 /* CA for any purpose */
2710 cert = obj->data.x509;
2711 if (!X509_check_ca(cert)) {
2712 continue;
2713 }
2714 if (binary_mode) {
2715 ci = _certificate_to_der(cert);
2716 } else {
2717 ci = _decode_certificate(cert);
2718 }
2719 if (ci == NULL) {
2720 goto error;
2721 }
2722 if (PyList_Append(rlist, ci) == -1) {
2723 goto error;
2724 }
2725 Py_CLEAR(ci);
2726 }
2727 return rlist;
2728
2729 error:
2730 Py_XDECREF(ci);
2731 Py_XDECREF(rlist);
2732 return NULL;
2733}
2734
2735
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002737 {"options", (getter) get_options,
2738 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002739 {"verify_mode", (getter) get_verify_mode,
2740 (setter) set_verify_mode, NULL},
2741 {NULL}, /* sentinel */
2742};
2743
2744static struct PyMethodDef context_methods[] = {
2745 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2746 METH_VARARGS | METH_KEYWORDS, NULL},
2747 {"set_ciphers", (PyCFunction) set_ciphers,
2748 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002749 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2750 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002751 {"load_cert_chain", (PyCFunction) load_cert_chain,
2752 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002753 {"load_dh_params", (PyCFunction) load_dh_params,
2754 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002755 {"load_verify_locations", (PyCFunction) load_verify_locations,
2756 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002757 {"session_stats", (PyCFunction) session_stats,
2758 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002759 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2760 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002761#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002762 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2763 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002764#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002765 {"set_servername_callback", (PyCFunction) set_servername_callback,
2766 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002767 {"cert_store_stats", (PyCFunction) cert_store_stats,
2768 METH_NOARGS, PySSL_get_stats_doc},
2769 {"get_ca_certs", (PyCFunction) get_ca_certs,
2770 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002771 {NULL, NULL} /* sentinel */
2772};
2773
2774static PyTypeObject PySSLContext_Type = {
2775 PyVarObject_HEAD_INIT(NULL, 0)
2776 "_ssl._SSLContext", /*tp_name*/
2777 sizeof(PySSLContext), /*tp_basicsize*/
2778 0, /*tp_itemsize*/
2779 (destructor)context_dealloc, /*tp_dealloc*/
2780 0, /*tp_print*/
2781 0, /*tp_getattr*/
2782 0, /*tp_setattr*/
2783 0, /*tp_reserved*/
2784 0, /*tp_repr*/
2785 0, /*tp_as_number*/
2786 0, /*tp_as_sequence*/
2787 0, /*tp_as_mapping*/
2788 0, /*tp_hash*/
2789 0, /*tp_call*/
2790 0, /*tp_str*/
2791 0, /*tp_getattro*/
2792 0, /*tp_setattro*/
2793 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002794 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002795 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002796 (traverseproc) context_traverse, /*tp_traverse*/
2797 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798 0, /*tp_richcompare*/
2799 0, /*tp_weaklistoffset*/
2800 0, /*tp_iter*/
2801 0, /*tp_iternext*/
2802 context_methods, /*tp_methods*/
2803 0, /*tp_members*/
2804 context_getsetlist, /*tp_getset*/
2805 0, /*tp_base*/
2806 0, /*tp_dict*/
2807 0, /*tp_descr_get*/
2808 0, /*tp_descr_set*/
2809 0, /*tp_dictoffset*/
2810 0, /*tp_init*/
2811 0, /*tp_alloc*/
2812 context_new, /*tp_new*/
2813};
2814
2815
2816
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002817#ifdef HAVE_OPENSSL_RAND
2818
2819/* helper routines for seeding the SSL PRNG */
2820static PyObject *
2821PySSL_RAND_add(PyObject *self, PyObject *args)
2822{
2823 char *buf;
2824 int len;
2825 double entropy;
2826
2827 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002828 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002829 RAND_add(buf, len, entropy);
2830 Py_INCREF(Py_None);
2831 return Py_None;
2832}
2833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002834PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002835"RAND_add(string, entropy)\n\
2836\n\
2837Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002838bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002839
2840static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002841PySSL_RAND(int len, int pseudo)
2842{
2843 int ok;
2844 PyObject *bytes;
2845 unsigned long err;
2846 const char *errstr;
2847 PyObject *v;
2848
2849 bytes = PyBytes_FromStringAndSize(NULL, len);
2850 if (bytes == NULL)
2851 return NULL;
2852 if (pseudo) {
2853 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2854 if (ok == 0 || ok == 1)
2855 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2856 }
2857 else {
2858 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2859 if (ok == 1)
2860 return bytes;
2861 }
2862 Py_DECREF(bytes);
2863
2864 err = ERR_get_error();
2865 errstr = ERR_reason_error_string(err);
2866 v = Py_BuildValue("(ks)", err, errstr);
2867 if (v != NULL) {
2868 PyErr_SetObject(PySSLErrorObject, v);
2869 Py_DECREF(v);
2870 }
2871 return NULL;
2872}
2873
2874static PyObject *
2875PySSL_RAND_bytes(PyObject *self, PyObject *args)
2876{
2877 int len;
2878 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2879 return NULL;
2880 return PySSL_RAND(len, 0);
2881}
2882
2883PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2884"RAND_bytes(n) -> bytes\n\
2885\n\
2886Generate n cryptographically strong pseudo-random bytes.");
2887
2888static PyObject *
2889PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2890{
2891 int len;
2892 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2893 return NULL;
2894 return PySSL_RAND(len, 1);
2895}
2896
2897PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2898"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2899\n\
2900Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2901generated are cryptographically strong.");
2902
2903static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002904PySSL_RAND_status(PyObject *self)
2905{
Christian Heimes217cfd12007-12-02 14:31:20 +00002906 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002907}
2908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002909PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002910"RAND_status() -> 0 or 1\n\
2911\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002912Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2913It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2914using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002915
2916static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002917PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002918{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002919 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002920 int bytes;
2921
Jesus Ceac8754a12012-09-11 02:00:58 +02002922 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002923 PyUnicode_FSConverter, &path))
2924 return NULL;
2925
2926 bytes = RAND_egd(PyBytes_AsString(path));
2927 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002928 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002929 PyErr_SetString(PySSLErrorObject,
2930 "EGD connection failed or EGD did not return "
2931 "enough data to seed the PRNG");
2932 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002933 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002934 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002935}
2936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002937PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002938"RAND_egd(path) -> bytes\n\
2939\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002940Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2941Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002942fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002943
Christian Heimesf77b4b22013-08-21 13:26:05 +02002944/* Seed OpenSSL's PRNG at fork(), http://bugs.python.org/issue18747
2945 *
Christian Heimes80c5de92013-08-22 13:19:48 +02002946 * The parent handler seeds the PRNG from pseudo-random data like pid, the
Christian Heimes61636e72013-08-25 14:19:16 +02002947 * current time (miliseconds or seconds) and an uninitialized array.
Christian Heimes80c5de92013-08-22 13:19:48 +02002948 * The array contains stack variables that are impossible to predict
Christian Heimesf77b4b22013-08-21 13:26:05 +02002949 * on most systems, e.g. function return address (subject to ASLR), the
2950 * stack protection canary and automatic variables.
2951 * The code is inspired by Apache's ssl_rand_seed() function.
2952 *
2953 * Note:
2954 * The code uses pthread_atfork() until Python has a proper atfork API. The
Christian Heimes80c5de92013-08-22 13:19:48 +02002955 * handlers are not removed from the child process. A parent handler is used
Christian Heimes61636e72013-08-25 14:19:16 +02002956 * instead of a child handler because fork() is supposed to be async-signal
Christian Heimes80c5de92013-08-22 13:19:48 +02002957 * safe but the handler calls unsafe functions.
Christian Heimesf77b4b22013-08-21 13:26:05 +02002958 */
2959
2960#if defined(HAVE_PTHREAD_ATFORK) && defined(WITH_THREAD)
2961#define PYSSL_RAND_ATFORK 1
2962
2963static void
Christian Heimes80c5de92013-08-22 13:19:48 +02002964PySSL_RAND_atfork_parent(void)
Christian Heimesf77b4b22013-08-21 13:26:05 +02002965{
2966 struct {
2967 char stack[128]; /* uninitialized (!) stack data, 128 is an
2968 arbitrary number. */
2969 pid_t pid; /* current pid */
2970 _PyTime_timeval tp; /* current time */
2971 } seed;
2972
2973#ifdef WITH_VALGRIND
2974 VALGRIND_MAKE_MEM_DEFINED(seed.stack, sizeof(seed.stack));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002975#endif
Christian Heimesf77b4b22013-08-21 13:26:05 +02002976 seed.pid = getpid();
2977 _PyTime_gettimeofday(&(seed.tp));
Christian Heimesf77b4b22013-08-21 13:26:05 +02002978 RAND_add((unsigned char *)&seed, sizeof(seed), 0.0);
2979}
2980
2981static int
2982PySSL_RAND_atfork(void)
2983{
2984 static int registered = 0;
2985 int retval;
2986
2987 if (registered)
2988 return 0;
2989
2990 retval = pthread_atfork(NULL, /* prepare */
Christian Heimes80c5de92013-08-22 13:19:48 +02002991 PySSL_RAND_atfork_parent, /* parent */
2992 NULL); /* child */
Christian Heimesf77b4b22013-08-21 13:26:05 +02002993 if (retval != 0) {
2994 PyErr_SetFromErrno(PyExc_OSError);
2995 return -1;
2996 }
2997 registered = 1;
2998 return 0;
2999}
3000#endif /* HAVE_PTHREAD_ATFORK */
3001
3002#endif /* HAVE_OPENSSL_RAND */
3003
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003004
Christian Heimes6d7ad132013-06-09 18:02:55 +02003005PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3006"get_default_verify_paths() -> tuple\n\
3007\n\
3008Return search paths and environment vars that are used by SSLContext's\n\
3009set_default_verify_paths() to load default CAs. The values are\n\
3010'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3011
3012static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003013PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003014{
3015 PyObject *ofile_env = NULL;
3016 PyObject *ofile = NULL;
3017 PyObject *odir_env = NULL;
3018 PyObject *odir = NULL;
3019
3020#define convert(info, target) { \
3021 const char *tmp = (info); \
3022 target = NULL; \
3023 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3024 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3025 target = PyBytes_FromString(tmp); } \
3026 if (!target) goto error; \
3027 } while(0)
3028
3029 convert(X509_get_default_cert_file_env(), ofile_env);
3030 convert(X509_get_default_cert_file(), ofile);
3031 convert(X509_get_default_cert_dir_env(), odir_env);
3032 convert(X509_get_default_cert_dir(), odir);
3033#undef convert
3034
Christian Heimes200bb1b2013-06-14 15:14:29 +02003035 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003036
3037 error:
3038 Py_XDECREF(ofile_env);
3039 Py_XDECREF(ofile);
3040 Py_XDECREF(odir_env);
3041 Py_XDECREF(odir);
3042 return NULL;
3043}
3044
Christian Heimes46bebee2013-06-09 19:03:31 +02003045#ifdef _MSC_VER
3046PyDoc_STRVAR(PySSL_enum_cert_store_doc,
3047"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3048\n\
3049Retrieve certificates from Windows' cert store. store_name may be one of\n\
3050'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3051cert_type must be either 'certificate' or 'crl'.\n\
3052The function returns a list of (bytes, encoding_type) tuples. The\n\
3053encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3054PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003055
Christian Heimes46bebee2013-06-09 19:03:31 +02003056static PyObject *
3057PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3058{
3059 char *kwlist[] = {"store_name", "cert_type", NULL};
3060 char *store_name;
3061 char *cert_type = "certificate";
3062 HCERTSTORE hStore = NULL;
3063 PyObject *result = NULL;
3064 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3065 int ok = 1;
3066
3067 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3068 kwlist, &store_name, &cert_type)) {
3069 return NULL;
3070 }
3071
3072 if ((strcmp(cert_type, "certificate") != 0) &&
3073 (strcmp(cert_type, "crl") != 0)) {
3074 return PyErr_Format(PyExc_ValueError,
3075 "cert_type must be 'certificate' or 'crl', "
3076 "not %.100s", cert_type);
3077 }
3078
3079 if ((result = PyList_New(0)) == NULL) {
3080 return NULL;
3081 }
3082
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003083 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003084 Py_DECREF(result);
3085 return PyErr_SetFromWindowsErr(GetLastError());
3086 }
3087
3088 if (strcmp(cert_type, "certificate") == 0) {
3089 PCCERT_CONTEXT pCertCtx = NULL;
3090 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3091 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3092 pCertCtx->cbCertEncoded);
3093 if (!cert) {
3094 ok = 0;
3095 break;
3096 }
3097 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3098 ok = 0;
3099 break;
3100 }
3101 if ((tup = PyTuple_New(2)) == NULL) {
3102 ok = 0;
3103 break;
3104 }
3105 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3106 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3107
3108 if (PyList_Append(result, tup) < 0) {
3109 ok = 0;
3110 break;
3111 }
3112 Py_CLEAR(tup);
3113 }
3114 if (pCertCtx) {
3115 /* loop ended with an error, need to clean up context manually */
3116 CertFreeCertificateContext(pCertCtx);
3117 }
3118 } else {
3119 PCCRL_CONTEXT pCrlCtx = NULL;
3120 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3121 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3122 pCrlCtx->cbCrlEncoded);
3123 if (!cert) {
3124 ok = 0;
3125 break;
3126 }
3127 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3128 ok = 0;
3129 break;
3130 }
3131 if ((tup = PyTuple_New(2)) == NULL) {
3132 ok = 0;
3133 break;
3134 }
3135 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3136 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3137
3138 if (PyList_Append(result, tup) < 0) {
3139 ok = 0;
3140 break;
3141 }
3142 Py_CLEAR(tup);
3143 }
3144 if (pCrlCtx) {
3145 /* loop ended with an error, need to clean up context manually */
3146 CertFreeCRLContext(pCrlCtx);
3147 }
3148 }
3149
3150 /* In error cases cert, enc and tup may not be NULL */
3151 Py_XDECREF(cert);
3152 Py_XDECREF(enc);
3153 Py_XDECREF(tup);
3154
3155 if (!CertCloseStore(hStore, 0)) {
3156 /* This error case might shadow another exception.*/
3157 Py_DECREF(result);
3158 return PyErr_SetFromWindowsErr(GetLastError());
3159 }
3160 if (ok) {
3161 return result;
3162 } else {
3163 Py_DECREF(result);
3164 return NULL;
3165 }
3166}
3167#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003168
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003169/* List of functions exported by this module. */
3170
3171static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003172 {"_test_decode_cert", PySSL_test_decode_certificate,
3173 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003174#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003175 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3176 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003177 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3178 PySSL_RAND_bytes_doc},
3179 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3180 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003181 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003182 PySSL_RAND_egd_doc},
3183 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3184 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003185#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003186 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003187 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003188#ifdef _MSC_VER
3189 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3190 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3191#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003192 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003193};
3194
3195
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003196#ifdef WITH_THREAD
3197
3198/* an implementation of OpenSSL threading operations in terms
3199 of the Python C thread library */
3200
3201static PyThread_type_lock *_ssl_locks = NULL;
3202
Christian Heimes4d98ca92013-08-19 17:36:29 +02003203#if OPENSSL_VERSION_NUMBER >= 0x10000000
3204/* use new CRYPTO_THREADID API. */
3205static void
3206_ssl_threadid_callback(CRYPTO_THREADID *id)
3207{
3208 CRYPTO_THREADID_set_numeric(id,
3209 (unsigned long)PyThread_get_thread_ident());
3210}
3211#else
3212/* deprecated CRYPTO_set_id_callback() API. */
3213static unsigned long
3214_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003215 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003216}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003217#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003218
Bill Janssen6e027db2007-11-15 22:23:56 +00003219static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003220 (int mode, int n, const char *file, int line) {
3221 /* this function is needed to perform locking on shared data
3222 structures. (Note that OpenSSL uses a number of global data
3223 structures that will be implicitly shared whenever multiple
3224 threads use OpenSSL.) Multi-threaded applications will
3225 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003227 locking_function() must be able to handle up to
3228 CRYPTO_num_locks() different mutex locks. It sets the n-th
3229 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003231 file and line are the file number of the function setting the
3232 lock. They can be useful for debugging.
3233 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003235 if ((_ssl_locks == NULL) ||
3236 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3237 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003239 if (mode & CRYPTO_LOCK) {
3240 PyThread_acquire_lock(_ssl_locks[n], 1);
3241 } else {
3242 PyThread_release_lock(_ssl_locks[n]);
3243 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003244}
3245
3246static int _setup_ssl_threads(void) {
3247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003248 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003250 if (_ssl_locks == NULL) {
3251 _ssl_locks_count = CRYPTO_num_locks();
3252 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003253 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003254 if (_ssl_locks == NULL)
3255 return 0;
3256 memset(_ssl_locks, 0,
3257 sizeof(PyThread_type_lock) * _ssl_locks_count);
3258 for (i = 0; i < _ssl_locks_count; i++) {
3259 _ssl_locks[i] = PyThread_allocate_lock();
3260 if (_ssl_locks[i] == NULL) {
3261 unsigned int j;
3262 for (j = 0; j < i; j++) {
3263 PyThread_free_lock(_ssl_locks[j]);
3264 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003265 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003266 return 0;
3267 }
3268 }
3269 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003270#if OPENSSL_VERSION_NUMBER >= 0x10000000
3271 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3272#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003273 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003274#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003275 }
3276 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003277}
3278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003279#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003281PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003282"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003283for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003284
Martin v. Löwis1a214512008-06-11 05:26:20 +00003285
3286static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003287 PyModuleDef_HEAD_INIT,
3288 "_ssl",
3289 module_doc,
3290 -1,
3291 PySSL_methods,
3292 NULL,
3293 NULL,
3294 NULL,
3295 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003296};
3297
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003298
3299static void
3300parse_openssl_version(unsigned long libver,
3301 unsigned int *major, unsigned int *minor,
3302 unsigned int *fix, unsigned int *patch,
3303 unsigned int *status)
3304{
3305 *status = libver & 0xF;
3306 libver >>= 4;
3307 *patch = libver & 0xFF;
3308 libver >>= 8;
3309 *fix = libver & 0xFF;
3310 libver >>= 8;
3311 *minor = libver & 0xFF;
3312 libver >>= 8;
3313 *major = libver & 0xFF;
3314}
3315
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003316PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003317PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003319 PyObject *m, *d, *r;
3320 unsigned long libver;
3321 unsigned int major, minor, fix, patch, status;
3322 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003323 struct py_ssl_error_code *errcode;
3324 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003325
Antoine Pitrou152efa22010-05-16 18:19:27 +00003326 if (PyType_Ready(&PySSLContext_Type) < 0)
3327 return NULL;
3328 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003329 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003331 m = PyModule_Create(&_sslmodule);
3332 if (m == NULL)
3333 return NULL;
3334 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003336 /* Load _socket module and its C API */
3337 socket_api = PySocketModule_ImportModuleAndAPI();
3338 if (!socket_api)
3339 return NULL;
3340 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003342 /* Init OpenSSL */
3343 SSL_load_error_strings();
3344 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003345#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003346 /* note that this will start threading if not already started */
3347 if (!_setup_ssl_threads()) {
3348 return NULL;
3349 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003350#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003351 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003353 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003354 sslerror_type_slots[0].pfunc = PyExc_OSError;
3355 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003356 if (PySSLErrorObject == NULL)
3357 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003358
Antoine Pitrou41032a62011-10-27 23:56:55 +02003359 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3360 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3361 PySSLErrorObject, NULL);
3362 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3363 "ssl.SSLWantReadError", SSLWantReadError_doc,
3364 PySSLErrorObject, NULL);
3365 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3366 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3367 PySSLErrorObject, NULL);
3368 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3369 "ssl.SSLSyscallError", SSLSyscallError_doc,
3370 PySSLErrorObject, NULL);
3371 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3372 "ssl.SSLEOFError", SSLEOFError_doc,
3373 PySSLErrorObject, NULL);
3374 if (PySSLZeroReturnErrorObject == NULL
3375 || PySSLWantReadErrorObject == NULL
3376 || PySSLWantWriteErrorObject == NULL
3377 || PySSLSyscallErrorObject == NULL
3378 || PySSLEOFErrorObject == NULL)
3379 return NULL;
3380 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3381 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3382 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3383 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3384 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3385 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003386 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003387 if (PyDict_SetItemString(d, "_SSLContext",
3388 (PyObject *)&PySSLContext_Type) != 0)
3389 return NULL;
3390 if (PyDict_SetItemString(d, "_SSLSocket",
3391 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003392 return NULL;
3393 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3394 PY_SSL_ERROR_ZERO_RETURN);
3395 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3396 PY_SSL_ERROR_WANT_READ);
3397 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3398 PY_SSL_ERROR_WANT_WRITE);
3399 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3400 PY_SSL_ERROR_WANT_X509_LOOKUP);
3401 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3402 PY_SSL_ERROR_SYSCALL);
3403 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3404 PY_SSL_ERROR_SSL);
3405 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3406 PY_SSL_ERROR_WANT_CONNECT);
3407 /* non ssl.h errorcodes */
3408 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3409 PY_SSL_ERROR_EOF);
3410 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3411 PY_SSL_ERROR_INVALID_ERROR_CODE);
3412 /* cert requirements */
3413 PyModule_AddIntConstant(m, "CERT_NONE",
3414 PY_SSL_CERT_NONE);
3415 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3416 PY_SSL_CERT_OPTIONAL);
3417 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3418 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003419
Christian Heimes46bebee2013-06-09 19:03:31 +02003420#ifdef _MSC_VER
3421 /* Windows dwCertEncodingType */
3422 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3423 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3424#endif
3425
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003426 /* Alert Descriptions from ssl.h */
3427 /* note RESERVED constants no longer intended for use have been removed */
3428 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3429
3430#define ADD_AD_CONSTANT(s) \
3431 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3432 SSL_AD_##s)
3433
3434 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3435 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3436 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3437 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3438 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3439 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3440 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3441 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3442 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3443 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3444 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3445 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3446 ADD_AD_CONSTANT(UNKNOWN_CA);
3447 ADD_AD_CONSTANT(ACCESS_DENIED);
3448 ADD_AD_CONSTANT(DECODE_ERROR);
3449 ADD_AD_CONSTANT(DECRYPT_ERROR);
3450 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3451 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3452 ADD_AD_CONSTANT(INTERNAL_ERROR);
3453 ADD_AD_CONSTANT(USER_CANCELLED);
3454 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003455 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003456#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3457 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3458#endif
3459#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3460 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3461#endif
3462#ifdef SSL_AD_UNRECOGNIZED_NAME
3463 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3464#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003465#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3466 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3467#endif
3468#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3469 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3470#endif
3471#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3472 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3473#endif
3474
3475#undef ADD_AD_CONSTANT
3476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003477 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003478#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003479 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3480 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003481#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003482 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3483 PY_SSL_VERSION_SSL3);
3484 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3485 PY_SSL_VERSION_SSL23);
3486 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3487 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003488#if HAVE_TLSv1_2
3489 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3490 PY_SSL_VERSION_TLS1_1);
3491 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3492 PY_SSL_VERSION_TLS1_2);
3493#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003494
Antoine Pitroub5218772010-05-21 09:56:06 +00003495 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003496 PyModule_AddIntConstant(m, "OP_ALL",
3497 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003498 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3499 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3500 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003501#if HAVE_TLSv1_2
3502 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3503 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3504#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003505 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3506 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003507 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003508#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003509 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003510#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003511#ifdef SSL_OP_NO_COMPRESSION
3512 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3513 SSL_OP_NO_COMPRESSION);
3514#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003515
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003516#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003517 r = Py_True;
3518#else
3519 r = Py_False;
3520#endif
3521 Py_INCREF(r);
3522 PyModule_AddObject(m, "HAS_SNI", r);
3523
Antoine Pitroud6494802011-07-21 01:11:30 +02003524#if HAVE_OPENSSL_FINISHED
3525 r = Py_True;
3526#else
3527 r = Py_False;
3528#endif
3529 Py_INCREF(r);
3530 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3531
Antoine Pitrou501da612011-12-21 09:27:41 +01003532#ifdef OPENSSL_NO_ECDH
3533 r = Py_False;
3534#else
3535 r = Py_True;
3536#endif
3537 Py_INCREF(r);
3538 PyModule_AddObject(m, "HAS_ECDH", r);
3539
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003540#ifdef OPENSSL_NPN_NEGOTIATED
3541 r = Py_True;
3542#else
3543 r = Py_False;
3544#endif
3545 Py_INCREF(r);
3546 PyModule_AddObject(m, "HAS_NPN", r);
3547
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003548 /* Mappings for error codes */
3549 err_codes_to_names = PyDict_New();
3550 err_names_to_codes = PyDict_New();
3551 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3552 return NULL;
3553 errcode = error_codes;
3554 while (errcode->mnemonic != NULL) {
3555 PyObject *mnemo, *key;
3556 mnemo = PyUnicode_FromString(errcode->mnemonic);
3557 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3558 if (mnemo == NULL || key == NULL)
3559 return NULL;
3560 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3561 return NULL;
3562 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3563 return NULL;
3564 Py_DECREF(key);
3565 Py_DECREF(mnemo);
3566 errcode++;
3567 }
3568 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3569 return NULL;
3570 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3571 return NULL;
3572
3573 lib_codes_to_names = PyDict_New();
3574 if (lib_codes_to_names == NULL)
3575 return NULL;
3576 libcode = library_codes;
3577 while (libcode->library != NULL) {
3578 PyObject *mnemo, *key;
3579 key = PyLong_FromLong(libcode->code);
3580 mnemo = PyUnicode_FromString(libcode->library);
3581 if (key == NULL || mnemo == NULL)
3582 return NULL;
3583 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3584 return NULL;
3585 Py_DECREF(key);
3586 Py_DECREF(mnemo);
3587 libcode++;
3588 }
3589 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3590 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003592 /* OpenSSL version */
3593 /* SSLeay() gives us the version of the library linked against,
3594 which could be different from the headers version.
3595 */
3596 libver = SSLeay();
3597 r = PyLong_FromUnsignedLong(libver);
3598 if (r == NULL)
3599 return NULL;
3600 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3601 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003602 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003603 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3604 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3605 return NULL;
3606 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3607 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3608 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003609
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003610 libver = OPENSSL_VERSION_NUMBER;
3611 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3612 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3613 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3614 return NULL;
3615
Christian Heimesf77b4b22013-08-21 13:26:05 +02003616#ifdef PYSSL_RAND_ATFORK
3617 if (PySSL_RAND_atfork() == -1)
3618 return NULL;
3619#endif
3620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003621 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003622}