blob: 20d02123dd5b0cbb43fcb5f813105ba5a5f69227 [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;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200223 char shutdown_seen_zero;
224 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200225 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000226} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000227
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228static PyTypeObject PySSLContext_Type;
229static PyTypeObject PySSLSocket_Type;
230
231static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
232static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000233static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
236static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237
Antoine Pitrou152efa22010-05-16 18:19:27 +0000238#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
239#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000240
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000241typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000242 SOCKET_IS_NONBLOCKING,
243 SOCKET_IS_BLOCKING,
244 SOCKET_HAS_TIMED_OUT,
245 SOCKET_HAS_BEEN_CLOSED,
246 SOCKET_TOO_LARGE_FOR_SELECT,
247 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000248} timeout_state;
249
Thomas Woutersed03b412007-08-28 21:37:11 +0000250/* Wrap error strings with filename and line # */
251#define STRINGIFY1(x) #x
252#define STRINGIFY2(x) STRINGIFY1(x)
253#define ERRSTR1(x,y,z) (x ":" y ": " z)
254#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
255
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200256
257/*
258 * SSL errors.
259 */
260
261PyDoc_STRVAR(SSLError_doc,
262"An error occurred in the SSL implementation.");
263
264PyDoc_STRVAR(SSLZeroReturnError_doc,
265"SSL/TLS session closed cleanly.");
266
267PyDoc_STRVAR(SSLWantReadError_doc,
268"Non-blocking SSL socket needs to read more data\n"
269"before the requested operation can be completed.");
270
271PyDoc_STRVAR(SSLWantWriteError_doc,
272"Non-blocking SSL socket needs to write more data\n"
273"before the requested operation can be completed.");
274
275PyDoc_STRVAR(SSLSyscallError_doc,
276"System error when attempting SSL operation.");
277
278PyDoc_STRVAR(SSLEOFError_doc,
279"SSL/TLS connection terminated abruptly.");
280
281static PyObject *
282SSLError_str(PyOSErrorObject *self)
283{
284 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
285 Py_INCREF(self->strerror);
286 return self->strerror;
287 }
288 else
289 return PyObject_Str(self->args);
290}
291
292static PyType_Slot sslerror_type_slots[] = {
293 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
294 {Py_tp_doc, SSLError_doc},
295 {Py_tp_str, SSLError_str},
296 {0, 0},
297};
298
299static PyType_Spec sslerror_type_spec = {
300 "ssl.SSLError",
301 sizeof(PyOSErrorObject),
302 0,
303 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
304 sslerror_type_slots
305};
306
307static void
308fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
309 int lineno, unsigned long errcode)
310{
311 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
312 PyObject *init_value, *msg, *key;
313 _Py_IDENTIFIER(reason);
314 _Py_IDENTIFIER(library);
315
316 if (errcode != 0) {
317 int lib, reason;
318
319 lib = ERR_GET_LIB(errcode);
320 reason = ERR_GET_REASON(errcode);
321 key = Py_BuildValue("ii", lib, reason);
322 if (key == NULL)
323 goto fail;
324 reason_obj = PyDict_GetItem(err_codes_to_names, key);
325 Py_DECREF(key);
326 if (reason_obj == NULL) {
327 /* XXX if reason < 100, it might reflect a library number (!!) */
328 PyErr_Clear();
329 }
330 key = PyLong_FromLong(lib);
331 if (key == NULL)
332 goto fail;
333 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
334 Py_DECREF(key);
335 if (lib_obj == NULL) {
336 PyErr_Clear();
337 }
338 if (errstr == NULL)
339 errstr = ERR_reason_error_string(errcode);
340 }
341 if (errstr == NULL)
342 errstr = "unknown error";
343
344 if (reason_obj && lib_obj)
345 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
346 lib_obj, reason_obj, errstr, lineno);
347 else if (lib_obj)
348 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
349 lib_obj, errstr, lineno);
350 else
351 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
352
353 if (msg == NULL)
354 goto fail;
355 init_value = Py_BuildValue("iN", ssl_errno, msg);
356 err_value = PyObject_CallObject(type, init_value);
357 Py_DECREF(init_value);
358 if (err_value == NULL)
359 goto fail;
360 if (reason_obj == NULL)
361 reason_obj = Py_None;
362 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
363 goto fail;
364 if (lib_obj == NULL)
365 lib_obj = Py_None;
366 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
367 goto fail;
368 PyErr_SetObject(type, err_value);
369fail:
370 Py_XDECREF(err_value);
371}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000372
373static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000374PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200376 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000378 int err;
379 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200380 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200383 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 if (obj->ssl != NULL) {
386 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 switch (err) {
389 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200390 errstr = "TLS/SSL connection has been closed (EOF)";
391 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 p = PY_SSL_ERROR_ZERO_RETURN;
393 break;
394 case SSL_ERROR_WANT_READ:
395 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200396 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 p = PY_SSL_ERROR_WANT_READ;
398 break;
399 case SSL_ERROR_WANT_WRITE:
400 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000402 errstr = "The operation did not complete (write)";
403 break;
404 case SSL_ERROR_WANT_X509_LOOKUP:
405 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000406 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 break;
408 case SSL_ERROR_WANT_CONNECT:
409 p = PY_SSL_ERROR_WANT_CONNECT;
410 errstr = "The operation did not complete (connect)";
411 break;
412 case SSL_ERROR_SYSCALL:
413 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 if (e == 0) {
415 PySocketSockObject *s
416 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
417 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000418 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200419 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000420 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000422 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000423 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000424 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200425 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000426 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200427 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200430 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000431 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000432 }
433 } else {
434 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 }
436 break;
437 }
438 case SSL_ERROR_SSL:
439 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000440 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441 if (e == 0)
442 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000443 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000444 break;
445 }
446 default:
447 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
448 errstr = "Invalid error code";
449 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000452 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000453 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000454}
455
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000456static PyObject *
457_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
458
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200461 else
462 errcode = 0;
463 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000464 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466}
467
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468/*
469 * SSL objects
470 */
471
Antoine Pitrou152efa22010-05-16 18:19:27 +0000472static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100473newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000474 enum py_ssl_server_or_client socket_type,
475 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000476{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100478 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200479 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000480
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 if (self == NULL)
483 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 self->peer_cert = NULL;
486 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100488 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200489 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200490 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100491 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 /* Make sure the SSL error state is initialized */
494 (void) ERR_get_state();
495 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000497 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000498 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100500 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200502 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000503#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200504 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000505#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200506 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000507
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100508#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000509 if (server_hostname != NULL)
510 SSL_set_tlsext_host_name(self->ssl, server_hostname);
511#endif
512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 /* If the socket is in non-blocking mode or timeout mode, set the BIO
514 * to non-blocking mode (blocking is the default)
515 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000516 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
518 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
519 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 PySSL_BEGIN_ALLOW_THREADS
522 if (socket_type == PY_SSL_CLIENT)
523 SSL_set_connect_state(self->ssl);
524 else
525 SSL_set_accept_state(self->ssl);
526 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000527
Antoine Pitroud6494802011-07-21 01:11:30 +0200528 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000529 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000530 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000531}
532
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000533/* SSL object methods */
534
Antoine Pitrou152efa22010-05-16 18:19:27 +0000535static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000536{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000537 int ret;
538 int err;
539 int sockstate, nonblocking;
540 PySocketSockObject *sock
541 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 if (((PyObject*)sock) == Py_None) {
544 _setSSLError("Underlying socket connection gone",
545 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
546 return NULL;
547 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000548 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 /* just in case the blocking state of the socket has been changed */
551 nonblocking = (sock->sock_timeout >= 0.0);
552 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
553 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000555 /* Actually negotiate SSL connection */
556 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000557 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000558 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000559 ret = SSL_do_handshake(self->ssl);
560 err = SSL_get_error(self->ssl, ret);
561 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000562 if (PyErr_CheckSignals())
563 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 if (err == SSL_ERROR_WANT_READ) {
565 sockstate = check_socket_and_wait_for_timeout(sock, 0);
566 } else if (err == SSL_ERROR_WANT_WRITE) {
567 sockstate = check_socket_and_wait_for_timeout(sock, 1);
568 } else {
569 sockstate = SOCKET_OPERATION_OK;
570 }
571 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000572 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000573 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
576 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000577 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000578 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
580 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000581 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000582 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
584 break;
585 }
586 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 if (ret < 1)
589 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 if (self->peer_cert)
592 X509_free (self->peer_cert);
593 PySSL_BEGIN_ALLOW_THREADS
594 self->peer_cert = SSL_get_peer_certificate(self->ssl);
595 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200596 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597
598 Py_INCREF(Py_None);
599 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000600
601error:
602 Py_DECREF(sock);
603 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000604}
605
Thomas Woutersed03b412007-08-28 21:37:11 +0000606static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 char namebuf[X509_NAME_MAXLEN];
610 int buflen;
611 PyObject *name_obj;
612 PyObject *value_obj;
613 PyObject *attr;
614 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
617 if (buflen < 0) {
618 _setSSLError(NULL, 0, __FILE__, __LINE__);
619 goto fail;
620 }
621 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
622 if (name_obj == NULL)
623 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
626 if (buflen < 0) {
627 _setSSLError(NULL, 0, __FILE__, __LINE__);
628 Py_DECREF(name_obj);
629 goto fail;
630 }
631 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000632 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 OPENSSL_free(valuebuf);
634 if (value_obj == NULL) {
635 Py_DECREF(name_obj);
636 goto fail;
637 }
638 attr = PyTuple_New(2);
639 if (attr == NULL) {
640 Py_DECREF(name_obj);
641 Py_DECREF(value_obj);
642 goto fail;
643 }
644 PyTuple_SET_ITEM(attr, 0, name_obj);
645 PyTuple_SET_ITEM(attr, 1, value_obj);
646 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000647
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000650}
651
652static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000654{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000655 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
656 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
657 PyObject *rdnt;
658 PyObject *attr = NULL; /* tuple to hold an attribute */
659 int entry_count = X509_NAME_entry_count(xname);
660 X509_NAME_ENTRY *entry;
661 ASN1_OBJECT *name;
662 ASN1_STRING *value;
663 int index_counter;
664 int rdn_level = -1;
665 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 dn = PyList_New(0);
668 if (dn == NULL)
669 return NULL;
670 /* now create another tuple to hold the top-level RDN */
671 rdn = PyList_New(0);
672 if (rdn == NULL)
673 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 for (index_counter = 0;
676 index_counter < entry_count;
677 index_counter++)
678 {
679 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 /* check to see if we've gotten to a new RDN */
682 if (rdn_level >= 0) {
683 if (rdn_level != entry->set) {
684 /* yes, new RDN */
685 /* add old RDN to DN */
686 rdnt = PyList_AsTuple(rdn);
687 Py_DECREF(rdn);
688 if (rdnt == NULL)
689 goto fail0;
690 retcode = PyList_Append(dn, rdnt);
691 Py_DECREF(rdnt);
692 if (retcode < 0)
693 goto fail0;
694 /* create new RDN */
695 rdn = PyList_New(0);
696 if (rdn == NULL)
697 goto fail0;
698 }
699 }
700 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 /* now add this attribute to the current RDN */
703 name = X509_NAME_ENTRY_get_object(entry);
704 value = X509_NAME_ENTRY_get_data(entry);
705 attr = _create_tuple_for_attribute(name, value);
706 /*
707 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
708 entry->set,
709 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
710 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
711 */
712 if (attr == NULL)
713 goto fail1;
714 retcode = PyList_Append(rdn, attr);
715 Py_DECREF(attr);
716 if (retcode < 0)
717 goto fail1;
718 }
719 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100720 if (rdn != NULL) {
721 if (PyList_GET_SIZE(rdn) > 0) {
722 rdnt = PyList_AsTuple(rdn);
723 Py_DECREF(rdn);
724 if (rdnt == NULL)
725 goto fail0;
726 retcode = PyList_Append(dn, rdnt);
727 Py_DECREF(rdnt);
728 if (retcode < 0)
729 goto fail0;
730 }
731 else {
732 Py_DECREF(rdn);
733 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 /* convert list to tuple */
737 rdnt = PyList_AsTuple(dn);
738 Py_DECREF(dn);
739 if (rdnt == NULL)
740 return NULL;
741 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
743 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
746 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 Py_XDECREF(dn);
748 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749}
750
751static PyObject *
752_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 /* this code follows the procedure outlined in
755 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
756 function to extract the STACK_OF(GENERAL_NAME),
757 then iterates through the stack to add the
758 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 int i, j;
761 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200762 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 X509_EXTENSION *ext = NULL;
764 GENERAL_NAMES *names = NULL;
765 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000766 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 BIO *biobuf = NULL;
768 char buf[2048];
769 char *vptr;
770 int len;
771 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000772#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000774#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000776#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000777
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 if (certificate == NULL)
779 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 /* get a memory buffer */
782 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200784 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 while ((i = X509_get_ext_by_NID(
786 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 if (peer_alt_names == Py_None) {
789 peer_alt_names = PyList_New(0);
790 if (peer_alt_names == NULL)
791 goto fail;
792 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 /* now decode the altName */
795 ext = X509_get_ext(certificate, i);
796 if(!(method = X509V3_EXT_get(ext))) {
797 PyErr_SetString
798 (PySSLErrorObject,
799 ERRSTR("No method for internalizing subjectAltName!"));
800 goto fail;
801 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 p = ext->value->data;
804 if (method->it)
805 names = (GENERAL_NAMES*)
806 (ASN1_item_d2i(NULL,
807 &p,
808 ext->value->length,
809 ASN1_ITEM_ptr(method->it)));
810 else
811 names = (GENERAL_NAMES*)
812 (method->d2i(NULL,
813 &p,
814 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200818 int gntype;
819 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200822 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200823 switch (gntype) {
824 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 /* we special-case DirName as a tuple of
826 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 t = PyTuple_New(2);
829 if (t == NULL) {
830 goto fail;
831 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 v = PyUnicode_FromString("DirName");
834 if (v == NULL) {
835 Py_DECREF(t);
836 goto fail;
837 }
838 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 v = _create_tuple_for_X509_NAME (name->d.dirn);
841 if (v == NULL) {
842 Py_DECREF(t);
843 goto fail;
844 }
845 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200846 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000847
Christian Heimes824f7f32013-08-17 00:54:47 +0200848 case GEN_EMAIL:
849 case GEN_DNS:
850 case GEN_URI:
851 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
852 correctly, CVE-2013-4238 */
853 t = PyTuple_New(2);
854 if (t == NULL)
855 goto fail;
856 switch (gntype) {
857 case GEN_EMAIL:
858 v = PyUnicode_FromString("email");
859 as = name->d.rfc822Name;
860 break;
861 case GEN_DNS:
862 v = PyUnicode_FromString("DNS");
863 as = name->d.dNSName;
864 break;
865 case GEN_URI:
866 v = PyUnicode_FromString("URI");
867 as = name->d.uniformResourceIdentifier;
868 break;
869 }
870 if (v == NULL) {
871 Py_DECREF(t);
872 goto fail;
873 }
874 PyTuple_SET_ITEM(t, 0, v);
875 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
876 ASN1_STRING_length(as));
877 if (v == NULL) {
878 Py_DECREF(t);
879 goto fail;
880 }
881 PyTuple_SET_ITEM(t, 1, v);
882 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Christian Heimes824f7f32013-08-17 00:54:47 +0200884 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200886 switch (gntype) {
887 /* check for new general name type */
888 case GEN_OTHERNAME:
889 case GEN_X400:
890 case GEN_EDIPARTY:
891 case GEN_IPADD:
892 case GEN_RID:
893 break;
894 default:
895 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
896 "Unknown general name type %d",
897 gntype) == -1) {
898 goto fail;
899 }
900 break;
901 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 (void) BIO_reset(biobuf);
903 GENERAL_NAME_print(biobuf, name);
904 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
905 if (len < 0) {
906 _setSSLError(NULL, 0, __FILE__, __LINE__);
907 goto fail;
908 }
909 vptr = strchr(buf, ':');
910 if (vptr == NULL)
911 goto fail;
912 t = PyTuple_New(2);
913 if (t == NULL)
914 goto fail;
915 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
916 if (v == NULL) {
917 Py_DECREF(t);
918 goto fail;
919 }
920 PyTuple_SET_ITEM(t, 0, v);
921 v = PyUnicode_FromStringAndSize((vptr + 1),
922 (len - (vptr - buf + 1)));
923 if (v == NULL) {
924 Py_DECREF(t);
925 goto fail;
926 }
927 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200928 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 if (PyList_Append(peer_alt_names, t) < 0) {
934 Py_DECREF(t);
935 goto fail;
936 }
937 Py_DECREF(t);
938 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100939 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 }
941 BIO_free(biobuf);
942 if (peer_alt_names != Py_None) {
943 v = PyList_AsTuple(peer_alt_names);
944 Py_DECREF(peer_alt_names);
945 return v;
946 } else {
947 return peer_alt_names;
948 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000949
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950
951 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 if (biobuf != NULL)
953 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 if (peer_alt_names != Py_None) {
956 Py_XDECREF(peer_alt_names);
957 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960}
961
962static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000963_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 PyObject *retval = NULL;
966 BIO *biobuf = NULL;
967 PyObject *peer;
968 PyObject *peer_alt_names = NULL;
969 PyObject *issuer;
970 PyObject *version;
971 PyObject *sn_obj;
972 ASN1_INTEGER *serialNumber;
973 char buf[2048];
974 int len;
975 ASN1_TIME *notBefore, *notAfter;
976 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 retval = PyDict_New();
979 if (retval == NULL)
980 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 peer = _create_tuple_for_X509_NAME(
983 X509_get_subject_name(certificate));
984 if (peer == NULL)
985 goto fail0;
986 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
987 Py_DECREF(peer);
988 goto fail0;
989 }
990 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000991
Antoine Pitroufb046912010-11-09 20:21:19 +0000992 issuer = _create_tuple_for_X509_NAME(
993 X509_get_issuer_name(certificate));
994 if (issuer == NULL)
995 goto fail0;
996 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000998 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001000 Py_DECREF(issuer);
1001
1002 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001003 if (version == NULL)
1004 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001005 if (PyDict_SetItemString(retval, "version", version) < 0) {
1006 Py_DECREF(version);
1007 goto fail0;
1008 }
1009 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 /* get a memory buffer */
1012 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001013
Antoine Pitroufb046912010-11-09 20:21:19 +00001014 (void) BIO_reset(biobuf);
1015 serialNumber = X509_get_serialNumber(certificate);
1016 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1017 i2a_ASN1_INTEGER(biobuf, serialNumber);
1018 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1019 if (len < 0) {
1020 _setSSLError(NULL, 0, __FILE__, __LINE__);
1021 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001023 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1024 if (sn_obj == NULL)
1025 goto fail1;
1026 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1027 Py_DECREF(sn_obj);
1028 goto fail1;
1029 }
1030 Py_DECREF(sn_obj);
1031
1032 (void) BIO_reset(biobuf);
1033 notBefore = X509_get_notBefore(certificate);
1034 ASN1_TIME_print(biobuf, notBefore);
1035 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1036 if (len < 0) {
1037 _setSSLError(NULL, 0, __FILE__, __LINE__);
1038 goto fail1;
1039 }
1040 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1041 if (pnotBefore == NULL)
1042 goto fail1;
1043 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1044 Py_DECREF(pnotBefore);
1045 goto fail1;
1046 }
1047 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 (void) BIO_reset(biobuf);
1050 notAfter = X509_get_notAfter(certificate);
1051 ASN1_TIME_print(biobuf, notAfter);
1052 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1053 if (len < 0) {
1054 _setSSLError(NULL, 0, __FILE__, __LINE__);
1055 goto fail1;
1056 }
1057 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1058 if (pnotAfter == NULL)
1059 goto fail1;
1060 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1061 Py_DECREF(pnotAfter);
1062 goto fail1;
1063 }
1064 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 peer_alt_names = _get_peer_alt_names(certificate);
1069 if (peer_alt_names == NULL)
1070 goto fail1;
1071 else if (peer_alt_names != Py_None) {
1072 if (PyDict_SetItemString(retval, "subjectAltName",
1073 peer_alt_names) < 0) {
1074 Py_DECREF(peer_alt_names);
1075 goto fail1;
1076 }
1077 Py_DECREF(peer_alt_names);
1078 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 BIO_free(biobuf);
1081 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001082
1083 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 if (biobuf != NULL)
1085 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001086 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 Py_XDECREF(retval);
1088 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001089}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001090
Christian Heimes9a5395a2013-06-17 15:44:12 +02001091static PyObject *
1092_certificate_to_der(X509 *certificate)
1093{
1094 unsigned char *bytes_buf = NULL;
1095 int len;
1096 PyObject *retval;
1097
1098 bytes_buf = NULL;
1099 len = i2d_X509(certificate, &bytes_buf);
1100 if (len < 0) {
1101 _setSSLError(NULL, 0, __FILE__, __LINE__);
1102 return NULL;
1103 }
1104 /* this is actually an immutable bytes sequence */
1105 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1106 OPENSSL_free(bytes_buf);
1107 return retval;
1108}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
1110static PyObject *
1111PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001114 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 X509 *x=NULL;
1116 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroufb046912010-11-09 20:21:19 +00001118 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1119 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1123 PyErr_SetString(PySSLErrorObject,
1124 "Can't malloc memory to read file");
1125 goto fail0;
1126 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127
Victor Stinner3800e1e2010-05-16 21:23:48 +00001128 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 PyErr_SetString(PySSLErrorObject,
1130 "Can't open file");
1131 goto fail0;
1132 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1135 if (x == NULL) {
1136 PyErr_SetString(PySSLErrorObject,
1137 "Error decoding PEM-encoded file");
1138 goto fail0;
1139 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroufb046912010-11-09 20:21:19 +00001141 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001142 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143
1144 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001145 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 if (cert != NULL) BIO_free(cert);
1147 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148}
1149
1150
1151static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001152PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001155 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001156
Antoine Pitrou721738f2012-08-15 23:20:39 +02001157 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001159
Antoine Pitrou20b85552013-09-29 19:50:53 +02001160 if (!self->handshake_done) {
1161 PyErr_SetString(PyExc_ValueError,
1162 "handshake not done yet");
1163 return NULL;
1164 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 if (!self->peer_cert)
1166 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167
Antoine Pitrou721738f2012-08-15 23:20:39 +02001168 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001170 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001172 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 if ((verification & SSL_VERIFY_PEER) == 0)
1174 return PyDict_New();
1175 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001176 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178}
1179
1180PyDoc_STRVAR(PySSL_peercert_doc,
1181"peer_certificate([der=False]) -> certificate\n\
1182\n\
1183Returns the certificate for the peer. If no certificate was provided,\n\
1184returns None. If a certificate was provided, but not validated, returns\n\
1185an empty dictionary. Otherwise returns a dict containing information\n\
1186about the peer certificate.\n\
1187\n\
1188If the optional argument is True, returns a DER-encoded copy of the\n\
1189peer certificate, or None if no certificate was provided. This will\n\
1190return the certificate even if it wasn't validated.");
1191
Antoine Pitrou152efa22010-05-16 18:19:27 +00001192static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001195 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 char *cipher_name;
1197 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001200 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 current = SSL_get_current_cipher(self->ssl);
1202 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001203 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205 retval = PyTuple_New(3);
1206 if (retval == NULL)
1207 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 cipher_name = (char *) SSL_CIPHER_get_name(current);
1210 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001211 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001212 PyTuple_SET_ITEM(retval, 0, Py_None);
1213 } else {
1214 v = PyUnicode_FromString(cipher_name);
1215 if (v == NULL)
1216 goto fail0;
1217 PyTuple_SET_ITEM(retval, 0, v);
1218 }
1219 cipher_protocol = SSL_CIPHER_get_version(current);
1220 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001221 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 PyTuple_SET_ITEM(retval, 1, Py_None);
1223 } else {
1224 v = PyUnicode_FromString(cipher_protocol);
1225 if (v == NULL)
1226 goto fail0;
1227 PyTuple_SET_ITEM(retval, 1, v);
1228 }
1229 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1230 if (v == NULL)
1231 goto fail0;
1232 PyTuple_SET_ITEM(retval, 2, v);
1233 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001234
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 Py_DECREF(retval);
1237 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238}
1239
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001240#ifdef OPENSSL_NPN_NEGOTIATED
1241static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1242 const unsigned char *out;
1243 unsigned int outlen;
1244
Victor Stinner4569cd52013-06-23 14:58:43 +02001245 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001246 &out, &outlen);
1247
1248 if (out == NULL)
1249 Py_RETURN_NONE;
1250 return PyUnicode_FromStringAndSize((char *) out, outlen);
1251}
1252#endif
1253
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001254static PyObject *PySSL_compression(PySSLSocket *self) {
1255#ifdef OPENSSL_NO_COMP
1256 Py_RETURN_NONE;
1257#else
1258 const COMP_METHOD *comp_method;
1259 const char *short_name;
1260
1261 if (self->ssl == NULL)
1262 Py_RETURN_NONE;
1263 comp_method = SSL_get_current_compression(self->ssl);
1264 if (comp_method == NULL || comp_method->type == NID_undef)
1265 Py_RETURN_NONE;
1266 short_name = OBJ_nid2sn(comp_method->type);
1267 if (short_name == NULL)
1268 Py_RETURN_NONE;
1269 return PyUnicode_DecodeFSDefault(short_name);
1270#endif
1271}
1272
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001273static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1274 Py_INCREF(self->ctx);
1275 return self->ctx;
1276}
1277
1278static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1279 void *closure) {
1280
1281 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001282#if !HAVE_SNI
1283 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1284 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001285 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001286#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001287 Py_INCREF(value);
1288 Py_DECREF(self->ctx);
1289 self->ctx = (PySSLContext *) value;
1290 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001291#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001292 } else {
1293 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1294 return -1;
1295 }
1296
1297 return 0;
1298}
1299
1300PyDoc_STRVAR(PySSL_set_context_doc,
1301"_setter_context(ctx)\n\
1302\
1303This changes the context associated with the SSLSocket. This is typically\n\
1304used from within a callback function set by the set_servername_callback\n\
1305on the SSLContext to change the certificate information associated with the\n\
1306SSLSocket before the cryptographic exchange handshake messages\n");
1307
1308
1309
Antoine Pitrou152efa22010-05-16 18:19:27 +00001310static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001311{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (self->peer_cert) /* Possible not to have one? */
1313 X509_free (self->peer_cert);
1314 if (self->ssl)
1315 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001317 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001319}
1320
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001321/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001322 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001323 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001324 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001325
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001326static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001327check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001328{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 fd_set fds;
1330 struct timeval tv;
1331 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1334 if (s->sock_timeout < 0.0)
1335 return SOCKET_IS_BLOCKING;
1336 else if (s->sock_timeout == 0.0)
1337 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 /* Guard against closed socket */
1340 if (s->sock_fd < 0)
1341 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 /* Prefer poll, if available, since you can poll() any fd
1344 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001345#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 {
1347 struct pollfd pollfd;
1348 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 pollfd.fd = s->sock_fd;
1351 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 /* s->sock_timeout is in seconds, timeout in ms */
1354 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1355 PySSL_BEGIN_ALLOW_THREADS
1356 rc = poll(&pollfd, 1, timeout);
1357 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 goto normal_return;
1360 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001361#endif
1362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001364 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 /* Construct the arguments to select */
1368 tv.tv_sec = (int)s->sock_timeout;
1369 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1370 FD_ZERO(&fds);
1371 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 /* See if the socket is ready */
1374 PySSL_BEGIN_ALLOW_THREADS
1375 if (writing)
1376 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1377 else
1378 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1379 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001380
Bill Janssen6e027db2007-11-15 22:23:56 +00001381#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001382normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001383#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1385 (when we are able to write or when there's something to read) */
1386 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001387}
1388
Antoine Pitrou152efa22010-05-16 18:19:27 +00001389static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001390{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 Py_buffer buf;
1392 int len;
1393 int sockstate;
1394 int err;
1395 int nonblocking;
1396 PySocketSockObject *sock
1397 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 if (((PyObject*)sock) == Py_None) {
1400 _setSSLError("Underlying socket connection gone",
1401 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1402 return NULL;
1403 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001404 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001406 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1407 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001409 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410
Victor Stinner6efa9652013-06-25 00:42:31 +02001411 if (buf.len > INT_MAX) {
1412 PyErr_Format(PyExc_OverflowError,
1413 "string longer than %d bytes", INT_MAX);
1414 goto error;
1415 }
1416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 /* just in case the blocking state of the socket has been changed */
1418 nonblocking = (sock->sock_timeout >= 0.0);
1419 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1420 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1421
1422 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1423 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001424 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 "The write operation timed out");
1426 goto error;
1427 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1428 PyErr_SetString(PySSLErrorObject,
1429 "Underlying socket has been closed.");
1430 goto error;
1431 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1432 PyErr_SetString(PySSLErrorObject,
1433 "Underlying socket too large for select().");
1434 goto error;
1435 }
1436 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001438 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 err = SSL_get_error(self->ssl, len);
1440 PySSL_END_ALLOW_THREADS
1441 if (PyErr_CheckSignals()) {
1442 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001443 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001445 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001447 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001448 } else {
1449 sockstate = SOCKET_OPERATION_OK;
1450 }
1451 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001452 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 "The write operation timed out");
1454 goto error;
1455 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1456 PyErr_SetString(PySSLErrorObject,
1457 "Underlying socket has been closed.");
1458 goto error;
1459 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1460 break;
1461 }
1462 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001463
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001464 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 PyBuffer_Release(&buf);
1466 if (len > 0)
1467 return PyLong_FromLong(len);
1468 else
1469 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001470
1471error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001472 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 PyBuffer_Release(&buf);
1474 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001475}
1476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478"write(s) -> len\n\
1479\n\
1480Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001481of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482
Antoine Pitrou152efa22010-05-16 18:19:27 +00001483static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001484{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 PySSL_BEGIN_ALLOW_THREADS
1488 count = SSL_pending(self->ssl);
1489 PySSL_END_ALLOW_THREADS
1490 if (count < 0)
1491 return PySSL_SetError(self, count, __FILE__, __LINE__);
1492 else
1493 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001494}
1495
1496PyDoc_STRVAR(PySSL_SSLpending_doc,
1497"pending() -> count\n\
1498\n\
1499Returns the number of already decrypted bytes available for read,\n\
1500pending on the connection.\n");
1501
Antoine Pitrou152efa22010-05-16 18:19:27 +00001502static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001503{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 PyObject *dest = NULL;
1505 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001507 int len, count;
1508 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 int sockstate;
1510 int err;
1511 int nonblocking;
1512 PySocketSockObject *sock
1513 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 if (((PyObject*)sock) == Py_None) {
1516 _setSSLError("Underlying socket connection gone",
1517 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1518 return NULL;
1519 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001520 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001522 buf.obj = NULL;
1523 buf.buf = NULL;
1524 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001525 goto error;
1526
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001527 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1528 dest = PyBytes_FromStringAndSize(NULL, len);
1529 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001530 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001531 mem = PyBytes_AS_STRING(dest);
1532 }
1533 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001535 mem = buf.buf;
1536 if (len <= 0 || len > buf.len) {
1537 len = (int) buf.len;
1538 if (buf.len != len) {
1539 PyErr_SetString(PyExc_OverflowError,
1540 "maximum length can't fit in a C 'int'");
1541 goto error;
1542 }
1543 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 }
1545
1546 /* just in case the blocking state of the socket has been changed */
1547 nonblocking = (sock->sock_timeout >= 0.0);
1548 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1549 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1550
1551 /* first check if there are bytes ready to be read */
1552 PySSL_BEGIN_ALLOW_THREADS
1553 count = SSL_pending(self->ssl);
1554 PySSL_END_ALLOW_THREADS
1555
1556 if (!count) {
1557 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1558 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001559 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 "The read operation timed out");
1561 goto error;
1562 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1563 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001564 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565 goto error;
1566 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1567 count = 0;
1568 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001569 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 }
1571 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 PySSL_BEGIN_ALLOW_THREADS
1573 count = SSL_read(self->ssl, mem, len);
1574 err = SSL_get_error(self->ssl, count);
1575 PySSL_END_ALLOW_THREADS
1576 if (PyErr_CheckSignals())
1577 goto error;
1578 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001579 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001581 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1583 (SSL_get_shutdown(self->ssl) ==
1584 SSL_RECEIVED_SHUTDOWN))
1585 {
1586 count = 0;
1587 goto done;
1588 } else {
1589 sockstate = SOCKET_OPERATION_OK;
1590 }
1591 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001592 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 "The read operation timed out");
1594 goto error;
1595 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1596 break;
1597 }
1598 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1599 if (count <= 0) {
1600 PySSL_SetError(self, count, __FILE__, __LINE__);
1601 goto error;
1602 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001603
1604done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001605 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001607 _PyBytes_Resize(&dest, count);
1608 return dest;
1609 }
1610 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 PyBuffer_Release(&buf);
1612 return PyLong_FromLong(count);
1613 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001614
1615error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001616 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001617 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001618 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001619 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622}
1623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001624PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001625"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001626\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001627Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001628
Antoine Pitrou152efa22010-05-16 18:19:27 +00001629static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001630{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 int err, ssl_err, sockstate, nonblocking;
1632 int zeros = 0;
1633 PySocketSockObject *sock
1634 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 /* Guard against closed socket */
1637 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1638 _setSSLError("Underlying socket connection gone",
1639 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1640 return NULL;
1641 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001642 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643
1644 /* Just in case the blocking state of the socket has been changed */
1645 nonblocking = (sock->sock_timeout >= 0.0);
1646 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1647 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1648
1649 while (1) {
1650 PySSL_BEGIN_ALLOW_THREADS
1651 /* Disable read-ahead so that unwrap can work correctly.
1652 * Otherwise OpenSSL might read in too much data,
1653 * eating clear text data that happens to be
1654 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001655 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001656 * function is used and the shutdown_seen_zero != 0
1657 * condition is met.
1658 */
1659 if (self->shutdown_seen_zero)
1660 SSL_set_read_ahead(self->ssl, 0);
1661 err = SSL_shutdown(self->ssl);
1662 PySSL_END_ALLOW_THREADS
1663 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1664 if (err > 0)
1665 break;
1666 if (err == 0) {
1667 /* Don't loop endlessly; instead preserve legacy
1668 behaviour of trying SSL_shutdown() only twice.
1669 This looks necessary for OpenSSL < 0.9.8m */
1670 if (++zeros > 1)
1671 break;
1672 /* Shutdown was sent, now try receiving */
1673 self->shutdown_seen_zero = 1;
1674 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001675 }
1676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 /* Possibly retry shutdown until timeout or failure */
1678 ssl_err = SSL_get_error(self->ssl, err);
1679 if (ssl_err == SSL_ERROR_WANT_READ)
1680 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1681 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1682 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1683 else
1684 break;
1685 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1686 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001687 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 "The read operation timed out");
1689 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001690 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001692 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 }
1694 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1695 PyErr_SetString(PySSLErrorObject,
1696 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001697 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 }
1699 else if (sockstate != SOCKET_OPERATION_OK)
1700 /* Retain the SSL error code */
1701 break;
1702 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001703
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001704 if (err < 0) {
1705 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001706 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001708 else
1709 /* It's already INCREF'ed */
1710 return (PyObject *) sock;
1711
1712error:
1713 Py_DECREF(sock);
1714 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001715}
1716
1717PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1718"shutdown(s) -> socket\n\
1719\n\
1720Does the SSL shutdown handshake with the remote end, and returns\n\
1721the underlying socket object.");
1722
Antoine Pitroud6494802011-07-21 01:11:30 +02001723#if HAVE_OPENSSL_FINISHED
1724static PyObject *
1725PySSL_tls_unique_cb(PySSLSocket *self)
1726{
1727 PyObject *retval = NULL;
1728 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001729 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001730
1731 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1732 /* if session is resumed XOR we are the client */
1733 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1734 }
1735 else {
1736 /* if a new session XOR we are the server */
1737 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1738 }
1739
1740 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001741 if (len == 0)
1742 Py_RETURN_NONE;
1743
1744 retval = PyBytes_FromStringAndSize(buf, len);
1745
1746 return retval;
1747}
1748
1749PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1750"tls_unique_cb() -> bytes\n\
1751\n\
1752Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1753\n\
1754If the TLS handshake is not yet complete, None is returned");
1755
1756#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001757
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001758static PyGetSetDef ssl_getsetlist[] = {
1759 {"context", (getter) PySSL_get_context,
1760 (setter) PySSL_set_context, PySSL_set_context_doc},
1761 {NULL}, /* sentinel */
1762};
1763
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001764static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1766 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1767 PySSL_SSLwrite_doc},
1768 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1769 PySSL_SSLread_doc},
1770 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1771 PySSL_SSLpending_doc},
1772 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1773 PySSL_peercert_doc},
1774 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001775#ifdef OPENSSL_NPN_NEGOTIATED
1776 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1777#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001778 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1780 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001781#if HAVE_OPENSSL_FINISHED
1782 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1783 PySSL_tls_unique_cb_doc},
1784#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001786};
1787
Antoine Pitrou152efa22010-05-16 18:19:27 +00001788static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001790 "_ssl._SSLSocket", /*tp_name*/
1791 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 0, /*tp_itemsize*/
1793 /* methods */
1794 (destructor)PySSL_dealloc, /*tp_dealloc*/
1795 0, /*tp_print*/
1796 0, /*tp_getattr*/
1797 0, /*tp_setattr*/
1798 0, /*tp_reserved*/
1799 0, /*tp_repr*/
1800 0, /*tp_as_number*/
1801 0, /*tp_as_sequence*/
1802 0, /*tp_as_mapping*/
1803 0, /*tp_hash*/
1804 0, /*tp_call*/
1805 0, /*tp_str*/
1806 0, /*tp_getattro*/
1807 0, /*tp_setattro*/
1808 0, /*tp_as_buffer*/
1809 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1810 0, /*tp_doc*/
1811 0, /*tp_traverse*/
1812 0, /*tp_clear*/
1813 0, /*tp_richcompare*/
1814 0, /*tp_weaklistoffset*/
1815 0, /*tp_iter*/
1816 0, /*tp_iternext*/
1817 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001818 0, /*tp_members*/
1819 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001820};
1821
Antoine Pitrou152efa22010-05-16 18:19:27 +00001822
1823/*
1824 * _SSLContext objects
1825 */
1826
1827static PyObject *
1828context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1829{
1830 char *kwlist[] = {"protocol", NULL};
1831 PySSLContext *self;
1832 int proto_version = PY_SSL_VERSION_SSL23;
1833 SSL_CTX *ctx = NULL;
1834
1835 if (!PyArg_ParseTupleAndKeywords(
1836 args, kwds, "i:_SSLContext", kwlist,
1837 &proto_version))
1838 return NULL;
1839
1840 PySSL_BEGIN_ALLOW_THREADS
1841 if (proto_version == PY_SSL_VERSION_TLS1)
1842 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001843#if HAVE_TLSv1_2
1844 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1845 ctx = SSL_CTX_new(TLSv1_1_method());
1846 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1847 ctx = SSL_CTX_new(TLSv1_2_method());
1848#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001849 else if (proto_version == PY_SSL_VERSION_SSL3)
1850 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001851#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001852 else if (proto_version == PY_SSL_VERSION_SSL2)
1853 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001854#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001855 else if (proto_version == PY_SSL_VERSION_SSL23)
1856 ctx = SSL_CTX_new(SSLv23_method());
1857 else
1858 proto_version = -1;
1859 PySSL_END_ALLOW_THREADS
1860
1861 if (proto_version == -1) {
1862 PyErr_SetString(PyExc_ValueError,
1863 "invalid protocol version");
1864 return NULL;
1865 }
1866 if (ctx == NULL) {
1867 PyErr_SetString(PySSLErrorObject,
1868 "failed to allocate SSL context");
1869 return NULL;
1870 }
1871
1872 assert(type != NULL && type->tp_alloc != NULL);
1873 self = (PySSLContext *) type->tp_alloc(type, 0);
1874 if (self == NULL) {
1875 SSL_CTX_free(ctx);
1876 return NULL;
1877 }
1878 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001879#ifdef OPENSSL_NPN_NEGOTIATED
1880 self->npn_protocols = NULL;
1881#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001882#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001883 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001884#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001885 /* Defaults */
1886 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001887 SSL_CTX_set_options(self->ctx,
1888 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001889
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001890#define SID_CTX "Python"
1891 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1892 sizeof(SID_CTX));
1893#undef SID_CTX
1894
Antoine Pitrou152efa22010-05-16 18:19:27 +00001895 return (PyObject *)self;
1896}
1897
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001898static int
1899context_traverse(PySSLContext *self, visitproc visit, void *arg)
1900{
1901#ifndef OPENSSL_NO_TLSEXT
1902 Py_VISIT(self->set_hostname);
1903#endif
1904 return 0;
1905}
1906
1907static int
1908context_clear(PySSLContext *self)
1909{
1910#ifndef OPENSSL_NO_TLSEXT
1911 Py_CLEAR(self->set_hostname);
1912#endif
1913 return 0;
1914}
1915
Antoine Pitrou152efa22010-05-16 18:19:27 +00001916static void
1917context_dealloc(PySSLContext *self)
1918{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001919 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001920 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001921#ifdef OPENSSL_NPN_NEGOTIATED
1922 PyMem_Free(self->npn_protocols);
1923#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001924 Py_TYPE(self)->tp_free(self);
1925}
1926
1927static PyObject *
1928set_ciphers(PySSLContext *self, PyObject *args)
1929{
1930 int ret;
1931 const char *cipherlist;
1932
1933 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1934 return NULL;
1935 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1936 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001937 /* Clearing the error queue is necessary on some OpenSSL versions,
1938 otherwise the error will be reported again when another SSL call
1939 is done. */
1940 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001941 PyErr_SetString(PySSLErrorObject,
1942 "No cipher can be selected.");
1943 return NULL;
1944 }
1945 Py_RETURN_NONE;
1946}
1947
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001948#ifdef OPENSSL_NPN_NEGOTIATED
1949/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1950static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001951_advertiseNPN_cb(SSL *s,
1952 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001953 void *args)
1954{
1955 PySSLContext *ssl_ctx = (PySSLContext *) args;
1956
1957 if (ssl_ctx->npn_protocols == NULL) {
1958 *data = (unsigned char *) "";
1959 *len = 0;
1960 } else {
1961 *data = (unsigned char *) ssl_ctx->npn_protocols;
1962 *len = ssl_ctx->npn_protocols_len;
1963 }
1964
1965 return SSL_TLSEXT_ERR_OK;
1966}
1967/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1968static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001969_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001970 unsigned char **out, unsigned char *outlen,
1971 const unsigned char *server, unsigned int server_len,
1972 void *args)
1973{
1974 PySSLContext *ssl_ctx = (PySSLContext *) args;
1975
1976 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1977 int client_len;
1978
1979 if (client == NULL) {
1980 client = (unsigned char *) "";
1981 client_len = 0;
1982 } else {
1983 client_len = ssl_ctx->npn_protocols_len;
1984 }
1985
1986 SSL_select_next_proto(out, outlen,
1987 server, server_len,
1988 client, client_len);
1989
1990 return SSL_TLSEXT_ERR_OK;
1991}
1992#endif
1993
1994static PyObject *
1995_set_npn_protocols(PySSLContext *self, PyObject *args)
1996{
1997#ifdef OPENSSL_NPN_NEGOTIATED
1998 Py_buffer protos;
1999
2000 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2001 return NULL;
2002
Christian Heimes5cb31c92012-09-20 12:42:54 +02002003 if (self->npn_protocols != NULL) {
2004 PyMem_Free(self->npn_protocols);
2005 }
2006
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002007 self->npn_protocols = PyMem_Malloc(protos.len);
2008 if (self->npn_protocols == NULL) {
2009 PyBuffer_Release(&protos);
2010 return PyErr_NoMemory();
2011 }
2012 memcpy(self->npn_protocols, protos.buf, protos.len);
2013 self->npn_protocols_len = (int) protos.len;
2014
2015 /* set both server and client callbacks, because the context can
2016 * be used to create both types of sockets */
2017 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2018 _advertiseNPN_cb,
2019 self);
2020 SSL_CTX_set_next_proto_select_cb(self->ctx,
2021 _selectNPN_cb,
2022 self);
2023
2024 PyBuffer_Release(&protos);
2025 Py_RETURN_NONE;
2026#else
2027 PyErr_SetString(PyExc_NotImplementedError,
2028 "The NPN extension requires OpenSSL 1.0.1 or later.");
2029 return NULL;
2030#endif
2031}
2032
Antoine Pitrou152efa22010-05-16 18:19:27 +00002033static PyObject *
2034get_verify_mode(PySSLContext *self, void *c)
2035{
2036 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2037 case SSL_VERIFY_NONE:
2038 return PyLong_FromLong(PY_SSL_CERT_NONE);
2039 case SSL_VERIFY_PEER:
2040 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2041 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2042 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2043 }
2044 PyErr_SetString(PySSLErrorObject,
2045 "invalid return value from SSL_CTX_get_verify_mode");
2046 return NULL;
2047}
2048
2049static int
2050set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2051{
2052 int n, mode;
2053 if (!PyArg_Parse(arg, "i", &n))
2054 return -1;
2055 if (n == PY_SSL_CERT_NONE)
2056 mode = SSL_VERIFY_NONE;
2057 else if (n == PY_SSL_CERT_OPTIONAL)
2058 mode = SSL_VERIFY_PEER;
2059 else if (n == PY_SSL_CERT_REQUIRED)
2060 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2061 else {
2062 PyErr_SetString(PyExc_ValueError,
2063 "invalid value for verify_mode");
2064 return -1;
2065 }
2066 SSL_CTX_set_verify(self->ctx, mode, NULL);
2067 return 0;
2068}
2069
2070static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002071get_options(PySSLContext *self, void *c)
2072{
2073 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2074}
2075
2076static int
2077set_options(PySSLContext *self, PyObject *arg, void *c)
2078{
2079 long new_opts, opts, set, clear;
2080 if (!PyArg_Parse(arg, "l", &new_opts))
2081 return -1;
2082 opts = SSL_CTX_get_options(self->ctx);
2083 clear = opts & ~new_opts;
2084 set = ~opts & new_opts;
2085 if (clear) {
2086#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2087 SSL_CTX_clear_options(self->ctx, clear);
2088#else
2089 PyErr_SetString(PyExc_ValueError,
2090 "can't clear options before OpenSSL 0.9.8m");
2091 return -1;
2092#endif
2093 }
2094 if (set)
2095 SSL_CTX_set_options(self->ctx, set);
2096 return 0;
2097}
2098
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002099typedef struct {
2100 PyThreadState *thread_state;
2101 PyObject *callable;
2102 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002103 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002104 int error;
2105} _PySSLPasswordInfo;
2106
2107static int
2108_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2109 const char *bad_type_error)
2110{
2111 /* Set the password and size fields of a _PySSLPasswordInfo struct
2112 from a unicode, bytes, or byte array object.
2113 The password field will be dynamically allocated and must be freed
2114 by the caller */
2115 PyObject *password_bytes = NULL;
2116 const char *data = NULL;
2117 Py_ssize_t size;
2118
2119 if (PyUnicode_Check(password)) {
2120 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2121 if (!password_bytes) {
2122 goto error;
2123 }
2124 data = PyBytes_AS_STRING(password_bytes);
2125 size = PyBytes_GET_SIZE(password_bytes);
2126 } else if (PyBytes_Check(password)) {
2127 data = PyBytes_AS_STRING(password);
2128 size = PyBytes_GET_SIZE(password);
2129 } else if (PyByteArray_Check(password)) {
2130 data = PyByteArray_AS_STRING(password);
2131 size = PyByteArray_GET_SIZE(password);
2132 } else {
2133 PyErr_SetString(PyExc_TypeError, bad_type_error);
2134 goto error;
2135 }
2136
Victor Stinner9ee02032013-06-23 15:08:23 +02002137 if (size > (Py_ssize_t)INT_MAX) {
2138 PyErr_Format(PyExc_ValueError,
2139 "password cannot be longer than %d bytes", INT_MAX);
2140 goto error;
2141 }
2142
Victor Stinner11ebff22013-07-07 17:07:52 +02002143 PyMem_Free(pw_info->password);
2144 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002145 if (!pw_info->password) {
2146 PyErr_SetString(PyExc_MemoryError,
2147 "unable to allocate password buffer");
2148 goto error;
2149 }
2150 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002151 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002152
2153 Py_XDECREF(password_bytes);
2154 return 1;
2155
2156error:
2157 Py_XDECREF(password_bytes);
2158 return 0;
2159}
2160
2161static int
2162_password_callback(char *buf, int size, int rwflag, void *userdata)
2163{
2164 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2165 PyObject *fn_ret = NULL;
2166
2167 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2168
2169 if (pw_info->callable) {
2170 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2171 if (!fn_ret) {
2172 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2173 core python API, so we could use it to add a frame here */
2174 goto error;
2175 }
2176
2177 if (!_pwinfo_set(pw_info, fn_ret,
2178 "password callback must return a string")) {
2179 goto error;
2180 }
2181 Py_CLEAR(fn_ret);
2182 }
2183
2184 if (pw_info->size > size) {
2185 PyErr_Format(PyExc_ValueError,
2186 "password cannot be longer than %d bytes", size);
2187 goto error;
2188 }
2189
2190 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2191 memcpy(buf, pw_info->password, pw_info->size);
2192 return pw_info->size;
2193
2194error:
2195 Py_XDECREF(fn_ret);
2196 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2197 pw_info->error = 1;
2198 return -1;
2199}
2200
Antoine Pitroub5218772010-05-21 09:56:06 +00002201static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002202load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2203{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002204 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2205 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002206 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002207 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2208 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2209 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 int r;
2211
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002212 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002213 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002214 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002215 "O|OO:load_cert_chain", kwlist,
2216 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217 return NULL;
2218 if (keyfile == Py_None)
2219 keyfile = NULL;
2220 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2221 PyErr_SetString(PyExc_TypeError,
2222 "certfile should be a valid filesystem path");
2223 return NULL;
2224 }
2225 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2226 PyErr_SetString(PyExc_TypeError,
2227 "keyfile should be a valid filesystem path");
2228 goto error;
2229 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002230 if (password && password != Py_None) {
2231 if (PyCallable_Check(password)) {
2232 pw_info.callable = password;
2233 } else if (!_pwinfo_set(&pw_info, password,
2234 "password should be a string or callable")) {
2235 goto error;
2236 }
2237 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2238 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2239 }
2240 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002241 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2242 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002243 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002244 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002245 if (pw_info.error) {
2246 ERR_clear_error();
2247 /* the password callback has already set the error information */
2248 }
2249 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002250 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002251 PyErr_SetFromErrno(PyExc_IOError);
2252 }
2253 else {
2254 _setSSLError(NULL, 0, __FILE__, __LINE__);
2255 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002256 goto error;
2257 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002258 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002259 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002260 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2261 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002262 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2263 Py_CLEAR(keyfile_bytes);
2264 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002265 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002266 if (pw_info.error) {
2267 ERR_clear_error();
2268 /* the password callback has already set the error information */
2269 }
2270 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002271 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002272 PyErr_SetFromErrno(PyExc_IOError);
2273 }
2274 else {
2275 _setSSLError(NULL, 0, __FILE__, __LINE__);
2276 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002277 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002278 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002279 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002280 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002281 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002282 if (r != 1) {
2283 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002284 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002285 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002286 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2287 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002288 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002289 Py_RETURN_NONE;
2290
2291error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002292 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2293 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002294 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002295 Py_XDECREF(keyfile_bytes);
2296 Py_XDECREF(certfile_bytes);
2297 return NULL;
2298}
2299
2300static PyObject *
2301load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2302{
2303 char *kwlist[] = {"cafile", "capath", NULL};
2304 PyObject *cafile = NULL, *capath = NULL;
2305 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2306 const char *cafile_buf = NULL, *capath_buf = NULL;
2307 int r;
2308
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002309 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002310 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2311 "|OO:load_verify_locations", kwlist,
2312 &cafile, &capath))
2313 return NULL;
2314 if (cafile == Py_None)
2315 cafile = NULL;
2316 if (capath == Py_None)
2317 capath = NULL;
2318 if (cafile == NULL && capath == NULL) {
2319 PyErr_SetString(PyExc_TypeError,
2320 "cafile and capath cannot be both omitted");
2321 return NULL;
2322 }
2323 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2324 PyErr_SetString(PyExc_TypeError,
2325 "cafile should be a valid filesystem path");
2326 return NULL;
2327 }
2328 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002329 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002330 PyErr_SetString(PyExc_TypeError,
2331 "capath should be a valid filesystem path");
2332 return NULL;
2333 }
2334 if (cafile)
2335 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2336 if (capath)
2337 capath_buf = PyBytes_AS_STRING(capath_bytes);
2338 PySSL_BEGIN_ALLOW_THREADS
2339 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2340 PySSL_END_ALLOW_THREADS
2341 Py_XDECREF(cafile_bytes);
2342 Py_XDECREF(capath_bytes);
2343 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002344 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002345 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002346 PyErr_SetFromErrno(PyExc_IOError);
2347 }
2348 else {
2349 _setSSLError(NULL, 0, __FILE__, __LINE__);
2350 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002351 return NULL;
2352 }
2353 Py_RETURN_NONE;
2354}
2355
2356static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002357load_dh_params(PySSLContext *self, PyObject *filepath)
2358{
2359 FILE *f;
2360 DH *dh;
2361
Victor Stinnerdaf45552013-08-28 00:53:59 +02002362 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002363 if (f == NULL) {
2364 if (!PyErr_Occurred())
2365 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2366 return NULL;
2367 }
2368 errno = 0;
2369 PySSL_BEGIN_ALLOW_THREADS
2370 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002371 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002372 PySSL_END_ALLOW_THREADS
2373 if (dh == NULL) {
2374 if (errno != 0) {
2375 ERR_clear_error();
2376 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2377 }
2378 else {
2379 _setSSLError(NULL, 0, __FILE__, __LINE__);
2380 }
2381 return NULL;
2382 }
2383 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2384 _setSSLError(NULL, 0, __FILE__, __LINE__);
2385 DH_free(dh);
2386 Py_RETURN_NONE;
2387}
2388
2389static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002390context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2391{
Antoine Pitroud5323212010-10-22 18:19:07 +00002392 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002393 PySocketSockObject *sock;
2394 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002395 char *hostname = NULL;
2396 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002397
Antoine Pitroud5323212010-10-22 18:19:07 +00002398 /* server_hostname is either None (or absent), or to be encoded
2399 using the idna encoding. */
2400 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002401 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002402 &sock, &server_side,
2403 Py_TYPE(Py_None), &hostname_obj)) {
2404 PyErr_Clear();
2405 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2406 PySocketModule.Sock_Type,
2407 &sock, &server_side,
2408 "idna", &hostname))
2409 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002410#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002411 PyMem_Free(hostname);
2412 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2413 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002415#endif
2416 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002417
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002418 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002419 hostname);
2420 if (hostname != NULL)
2421 PyMem_Free(hostname);
2422 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002423}
2424
Antoine Pitroub0182c82010-10-12 20:09:02 +00002425static PyObject *
2426session_stats(PySSLContext *self, PyObject *unused)
2427{
2428 int r;
2429 PyObject *value, *stats = PyDict_New();
2430 if (!stats)
2431 return NULL;
2432
2433#define ADD_STATS(SSL_NAME, KEY_NAME) \
2434 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2435 if (value == NULL) \
2436 goto error; \
2437 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2438 Py_DECREF(value); \
2439 if (r < 0) \
2440 goto error;
2441
2442 ADD_STATS(number, "number");
2443 ADD_STATS(connect, "connect");
2444 ADD_STATS(connect_good, "connect_good");
2445 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2446 ADD_STATS(accept, "accept");
2447 ADD_STATS(accept_good, "accept_good");
2448 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2449 ADD_STATS(accept, "accept");
2450 ADD_STATS(hits, "hits");
2451 ADD_STATS(misses, "misses");
2452 ADD_STATS(timeouts, "timeouts");
2453 ADD_STATS(cache_full, "cache_full");
2454
2455#undef ADD_STATS
2456
2457 return stats;
2458
2459error:
2460 Py_DECREF(stats);
2461 return NULL;
2462}
2463
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002464static PyObject *
2465set_default_verify_paths(PySSLContext *self, PyObject *unused)
2466{
2467 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2468 _setSSLError(NULL, 0, __FILE__, __LINE__);
2469 return NULL;
2470 }
2471 Py_RETURN_NONE;
2472}
2473
Antoine Pitrou501da612011-12-21 09:27:41 +01002474#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002475static PyObject *
2476set_ecdh_curve(PySSLContext *self, PyObject *name)
2477{
2478 PyObject *name_bytes;
2479 int nid;
2480 EC_KEY *key;
2481
2482 if (!PyUnicode_FSConverter(name, &name_bytes))
2483 return NULL;
2484 assert(PyBytes_Check(name_bytes));
2485 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2486 Py_DECREF(name_bytes);
2487 if (nid == 0) {
2488 PyErr_Format(PyExc_ValueError,
2489 "unknown elliptic curve name %R", name);
2490 return NULL;
2491 }
2492 key = EC_KEY_new_by_curve_name(nid);
2493 if (key == NULL) {
2494 _setSSLError(NULL, 0, __FILE__, __LINE__);
2495 return NULL;
2496 }
2497 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2498 EC_KEY_free(key);
2499 Py_RETURN_NONE;
2500}
Antoine Pitrou501da612011-12-21 09:27:41 +01002501#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002502
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002503#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002504static int
2505_servername_callback(SSL *s, int *al, void *args)
2506{
2507 int ret;
2508 PySSLContext *ssl_ctx = (PySSLContext *) args;
2509 PySSLSocket *ssl;
2510 PyObject *servername_o;
2511 PyObject *servername_idna;
2512 PyObject *result;
2513 /* The high-level ssl.SSLSocket object */
2514 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002515 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002516#ifdef WITH_THREAD
2517 PyGILState_STATE gstate = PyGILState_Ensure();
2518#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002519
2520 if (ssl_ctx->set_hostname == NULL) {
2521 /* remove race condition in this the call back while if removing the
2522 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002523#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002525#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002526 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002527 }
2528
2529 ssl = SSL_get_app_data(s);
2530 assert(PySSLSocket_Check(ssl));
2531 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2532 Py_INCREF(ssl_socket);
2533 if (ssl_socket == Py_None) {
2534 goto error;
2535 }
Victor Stinner7e001512013-06-25 00:44:31 +02002536
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002537 if (servername == NULL) {
2538 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2539 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002540 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002541 else {
2542 servername_o = PyBytes_FromString(servername);
2543 if (servername_o == NULL) {
2544 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2545 goto error;
2546 }
2547 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2548 if (servername_idna == NULL) {
2549 PyErr_WriteUnraisable(servername_o);
2550 Py_DECREF(servername_o);
2551 goto error;
2552 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002553 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002554 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2555 servername_idna, ssl_ctx, NULL);
2556 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002557 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002558 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002559
2560 if (result == NULL) {
2561 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2562 *al = SSL_AD_HANDSHAKE_FAILURE;
2563 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2564 }
2565 else {
2566 if (result != Py_None) {
2567 *al = (int) PyLong_AsLong(result);
2568 if (PyErr_Occurred()) {
2569 PyErr_WriteUnraisable(result);
2570 *al = SSL_AD_INTERNAL_ERROR;
2571 }
2572 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2573 }
2574 else {
2575 ret = SSL_TLSEXT_ERR_OK;
2576 }
2577 Py_DECREF(result);
2578 }
2579
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
2585error:
2586 Py_DECREF(ssl_socket);
2587 *al = SSL_AD_INTERNAL_ERROR;
2588 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002589#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002590 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002591#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002592 return ret;
2593}
Antoine Pitroua5963382013-03-30 16:39:00 +01002594#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002595
2596PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2597"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002598\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002599This sets a callback that will be called when a server name is provided by\n\
2600the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002601\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002602If the argument is None then the callback is disabled. The method is called\n\
2603with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002604See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002605
2606static PyObject *
2607set_servername_callback(PySSLContext *self, PyObject *args)
2608{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002609#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002610 PyObject *cb;
2611
2612 if (!PyArg_ParseTuple(args, "O", &cb))
2613 return NULL;
2614
2615 Py_CLEAR(self->set_hostname);
2616 if (cb == Py_None) {
2617 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2618 }
2619 else {
2620 if (!PyCallable_Check(cb)) {
2621 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2622 PyErr_SetString(PyExc_TypeError,
2623 "not a callable object");
2624 return NULL;
2625 }
2626 Py_INCREF(cb);
2627 self->set_hostname = cb;
2628 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2629 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2630 }
2631 Py_RETURN_NONE;
2632#else
2633 PyErr_SetString(PyExc_NotImplementedError,
2634 "The TLS extension servername callback, "
2635 "SSL_CTX_set_tlsext_servername_callback, "
2636 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002637 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002638#endif
2639}
2640
Christian Heimes9a5395a2013-06-17 15:44:12 +02002641PyDoc_STRVAR(PySSL_get_stats_doc,
2642"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2643\n\
2644Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2645CA extension and certificate revocation lists inside the context's cert\n\
2646store.\n\
2647NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2648been used at least once.");
2649
2650static PyObject *
2651cert_store_stats(PySSLContext *self)
2652{
2653 X509_STORE *store;
2654 X509_OBJECT *obj;
2655 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2656
2657 store = SSL_CTX_get_cert_store(self->ctx);
2658 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2659 obj = sk_X509_OBJECT_value(store->objs, i);
2660 switch (obj->type) {
2661 case X509_LU_X509:
2662 x509++;
2663 if (X509_check_ca(obj->data.x509)) {
2664 ca++;
2665 }
2666 break;
2667 case X509_LU_CRL:
2668 crl++;
2669 break;
2670 case X509_LU_PKEY:
2671 pkey++;
2672 break;
2673 default:
2674 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2675 * As far as I can tell they are internal states and never
2676 * stored in a cert store */
2677 break;
2678 }
2679 }
2680 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2681 "x509_ca", ca);
2682}
2683
2684PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2685"get_ca_certs([der=False]) -> list of loaded certificate\n\
2686\n\
2687Returns a list of dicts with information of loaded CA certs. If the\n\
2688optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2689NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2690been used at least once.");
2691
2692static PyObject *
2693get_ca_certs(PySSLContext *self, PyObject *args)
2694{
2695 X509_STORE *store;
2696 PyObject *ci = NULL, *rlist = NULL;
2697 int i;
2698 int binary_mode = 0;
2699
2700 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2701 return NULL;
2702 }
2703
2704 if ((rlist = PyList_New(0)) == NULL) {
2705 return NULL;
2706 }
2707
2708 store = SSL_CTX_get_cert_store(self->ctx);
2709 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2710 X509_OBJECT *obj;
2711 X509 *cert;
2712
2713 obj = sk_X509_OBJECT_value(store->objs, i);
2714 if (obj->type != X509_LU_X509) {
2715 /* not a x509 cert */
2716 continue;
2717 }
2718 /* CA for any purpose */
2719 cert = obj->data.x509;
2720 if (!X509_check_ca(cert)) {
2721 continue;
2722 }
2723 if (binary_mode) {
2724 ci = _certificate_to_der(cert);
2725 } else {
2726 ci = _decode_certificate(cert);
2727 }
2728 if (ci == NULL) {
2729 goto error;
2730 }
2731 if (PyList_Append(rlist, ci) == -1) {
2732 goto error;
2733 }
2734 Py_CLEAR(ci);
2735 }
2736 return rlist;
2737
2738 error:
2739 Py_XDECREF(ci);
2740 Py_XDECREF(rlist);
2741 return NULL;
2742}
2743
2744
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002746 {"options", (getter) get_options,
2747 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002748 {"verify_mode", (getter) get_verify_mode,
2749 (setter) set_verify_mode, NULL},
2750 {NULL}, /* sentinel */
2751};
2752
2753static struct PyMethodDef context_methods[] = {
2754 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2755 METH_VARARGS | METH_KEYWORDS, NULL},
2756 {"set_ciphers", (PyCFunction) set_ciphers,
2757 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002758 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2759 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760 {"load_cert_chain", (PyCFunction) load_cert_chain,
2761 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002762 {"load_dh_params", (PyCFunction) load_dh_params,
2763 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002764 {"load_verify_locations", (PyCFunction) load_verify_locations,
2765 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002766 {"session_stats", (PyCFunction) session_stats,
2767 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002768 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2769 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002770#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002771 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2772 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002773#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002774 {"set_servername_callback", (PyCFunction) set_servername_callback,
2775 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002776 {"cert_store_stats", (PyCFunction) cert_store_stats,
2777 METH_NOARGS, PySSL_get_stats_doc},
2778 {"get_ca_certs", (PyCFunction) get_ca_certs,
2779 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002780 {NULL, NULL} /* sentinel */
2781};
2782
2783static PyTypeObject PySSLContext_Type = {
2784 PyVarObject_HEAD_INIT(NULL, 0)
2785 "_ssl._SSLContext", /*tp_name*/
2786 sizeof(PySSLContext), /*tp_basicsize*/
2787 0, /*tp_itemsize*/
2788 (destructor)context_dealloc, /*tp_dealloc*/
2789 0, /*tp_print*/
2790 0, /*tp_getattr*/
2791 0, /*tp_setattr*/
2792 0, /*tp_reserved*/
2793 0, /*tp_repr*/
2794 0, /*tp_as_number*/
2795 0, /*tp_as_sequence*/
2796 0, /*tp_as_mapping*/
2797 0, /*tp_hash*/
2798 0, /*tp_call*/
2799 0, /*tp_str*/
2800 0, /*tp_getattro*/
2801 0, /*tp_setattro*/
2802 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002803 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002804 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002805 (traverseproc) context_traverse, /*tp_traverse*/
2806 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807 0, /*tp_richcompare*/
2808 0, /*tp_weaklistoffset*/
2809 0, /*tp_iter*/
2810 0, /*tp_iternext*/
2811 context_methods, /*tp_methods*/
2812 0, /*tp_members*/
2813 context_getsetlist, /*tp_getset*/
2814 0, /*tp_base*/
2815 0, /*tp_dict*/
2816 0, /*tp_descr_get*/
2817 0, /*tp_descr_set*/
2818 0, /*tp_dictoffset*/
2819 0, /*tp_init*/
2820 0, /*tp_alloc*/
2821 context_new, /*tp_new*/
2822};
2823
2824
2825
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002826#ifdef HAVE_OPENSSL_RAND
2827
2828/* helper routines for seeding the SSL PRNG */
2829static PyObject *
2830PySSL_RAND_add(PyObject *self, PyObject *args)
2831{
2832 char *buf;
2833 int len;
2834 double entropy;
2835
2836 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002837 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002838 RAND_add(buf, len, entropy);
2839 Py_INCREF(Py_None);
2840 return Py_None;
2841}
2842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002843PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002844"RAND_add(string, entropy)\n\
2845\n\
2846Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002847bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002848
2849static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002850PySSL_RAND(int len, int pseudo)
2851{
2852 int ok;
2853 PyObject *bytes;
2854 unsigned long err;
2855 const char *errstr;
2856 PyObject *v;
2857
2858 bytes = PyBytes_FromStringAndSize(NULL, len);
2859 if (bytes == NULL)
2860 return NULL;
2861 if (pseudo) {
2862 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2863 if (ok == 0 || ok == 1)
2864 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2865 }
2866 else {
2867 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2868 if (ok == 1)
2869 return bytes;
2870 }
2871 Py_DECREF(bytes);
2872
2873 err = ERR_get_error();
2874 errstr = ERR_reason_error_string(err);
2875 v = Py_BuildValue("(ks)", err, errstr);
2876 if (v != NULL) {
2877 PyErr_SetObject(PySSLErrorObject, v);
2878 Py_DECREF(v);
2879 }
2880 return NULL;
2881}
2882
2883static PyObject *
2884PySSL_RAND_bytes(PyObject *self, PyObject *args)
2885{
2886 int len;
2887 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2888 return NULL;
2889 return PySSL_RAND(len, 0);
2890}
2891
2892PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2893"RAND_bytes(n) -> bytes\n\
2894\n\
2895Generate n cryptographically strong pseudo-random bytes.");
2896
2897static PyObject *
2898PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2899{
2900 int len;
2901 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2902 return NULL;
2903 return PySSL_RAND(len, 1);
2904}
2905
2906PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2907"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2908\n\
2909Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2910generated are cryptographically strong.");
2911
2912static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002913PySSL_RAND_status(PyObject *self)
2914{
Christian Heimes217cfd12007-12-02 14:31:20 +00002915 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002916}
2917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002918PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002919"RAND_status() -> 0 or 1\n\
2920\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002921Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2922It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2923using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002924
2925static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002926PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002927{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002928 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002929 int bytes;
2930
Jesus Ceac8754a12012-09-11 02:00:58 +02002931 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002932 PyUnicode_FSConverter, &path))
2933 return NULL;
2934
2935 bytes = RAND_egd(PyBytes_AsString(path));
2936 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002937 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002938 PyErr_SetString(PySSLErrorObject,
2939 "EGD connection failed or EGD did not return "
2940 "enough data to seed the PRNG");
2941 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002942 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002943 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002944}
2945
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002946PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002947"RAND_egd(path) -> bytes\n\
2948\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002949Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2950Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002951fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002952
Christian Heimesf77b4b22013-08-21 13:26:05 +02002953/* Seed OpenSSL's PRNG at fork(), http://bugs.python.org/issue18747
2954 *
Christian Heimes80c5de92013-08-22 13:19:48 +02002955 * The parent handler seeds the PRNG from pseudo-random data like pid, the
Christian Heimes61636e72013-08-25 14:19:16 +02002956 * current time (miliseconds or seconds) and an uninitialized array.
Christian Heimes80c5de92013-08-22 13:19:48 +02002957 * The array contains stack variables that are impossible to predict
Christian Heimesf77b4b22013-08-21 13:26:05 +02002958 * on most systems, e.g. function return address (subject to ASLR), the
2959 * stack protection canary and automatic variables.
2960 * The code is inspired by Apache's ssl_rand_seed() function.
2961 *
2962 * Note:
2963 * The code uses pthread_atfork() until Python has a proper atfork API. The
Christian Heimes80c5de92013-08-22 13:19:48 +02002964 * handlers are not removed from the child process. A parent handler is used
Christian Heimes61636e72013-08-25 14:19:16 +02002965 * instead of a child handler because fork() is supposed to be async-signal
Christian Heimes80c5de92013-08-22 13:19:48 +02002966 * safe but the handler calls unsafe functions.
Christian Heimesf77b4b22013-08-21 13:26:05 +02002967 */
2968
2969#if defined(HAVE_PTHREAD_ATFORK) && defined(WITH_THREAD)
2970#define PYSSL_RAND_ATFORK 1
2971
2972static void
Christian Heimes80c5de92013-08-22 13:19:48 +02002973PySSL_RAND_atfork_parent(void)
Christian Heimesf77b4b22013-08-21 13:26:05 +02002974{
2975 struct {
2976 char stack[128]; /* uninitialized (!) stack data, 128 is an
2977 arbitrary number. */
2978 pid_t pid; /* current pid */
2979 _PyTime_timeval tp; /* current time */
2980 } seed;
2981
2982#ifdef WITH_VALGRIND
2983 VALGRIND_MAKE_MEM_DEFINED(seed.stack, sizeof(seed.stack));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002984#endif
Christian Heimesf77b4b22013-08-21 13:26:05 +02002985 seed.pid = getpid();
2986 _PyTime_gettimeofday(&(seed.tp));
Christian Heimesf77b4b22013-08-21 13:26:05 +02002987 RAND_add((unsigned char *)&seed, sizeof(seed), 0.0);
2988}
2989
2990static int
2991PySSL_RAND_atfork(void)
2992{
2993 static int registered = 0;
2994 int retval;
2995
2996 if (registered)
2997 return 0;
2998
2999 retval = pthread_atfork(NULL, /* prepare */
Christian Heimes80c5de92013-08-22 13:19:48 +02003000 PySSL_RAND_atfork_parent, /* parent */
3001 NULL); /* child */
Christian Heimesf77b4b22013-08-21 13:26:05 +02003002 if (retval != 0) {
3003 PyErr_SetFromErrno(PyExc_OSError);
3004 return -1;
3005 }
3006 registered = 1;
3007 return 0;
3008}
3009#endif /* HAVE_PTHREAD_ATFORK */
3010
3011#endif /* HAVE_OPENSSL_RAND */
3012
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003013
Christian Heimes6d7ad132013-06-09 18:02:55 +02003014PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3015"get_default_verify_paths() -> tuple\n\
3016\n\
3017Return search paths and environment vars that are used by SSLContext's\n\
3018set_default_verify_paths() to load default CAs. The values are\n\
3019'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3020
3021static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003022PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003023{
3024 PyObject *ofile_env = NULL;
3025 PyObject *ofile = NULL;
3026 PyObject *odir_env = NULL;
3027 PyObject *odir = NULL;
3028
3029#define convert(info, target) { \
3030 const char *tmp = (info); \
3031 target = NULL; \
3032 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3033 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3034 target = PyBytes_FromString(tmp); } \
3035 if (!target) goto error; \
3036 } while(0)
3037
3038 convert(X509_get_default_cert_file_env(), ofile_env);
3039 convert(X509_get_default_cert_file(), ofile);
3040 convert(X509_get_default_cert_dir_env(), odir_env);
3041 convert(X509_get_default_cert_dir(), odir);
3042#undef convert
3043
Christian Heimes200bb1b2013-06-14 15:14:29 +02003044 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003045
3046 error:
3047 Py_XDECREF(ofile_env);
3048 Py_XDECREF(ofile);
3049 Py_XDECREF(odir_env);
3050 Py_XDECREF(odir);
3051 return NULL;
3052}
3053
Christian Heimes46bebee2013-06-09 19:03:31 +02003054#ifdef _MSC_VER
3055PyDoc_STRVAR(PySSL_enum_cert_store_doc,
3056"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3057\n\
3058Retrieve certificates from Windows' cert store. store_name may be one of\n\
3059'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3060cert_type must be either 'certificate' or 'crl'.\n\
3061The function returns a list of (bytes, encoding_type) tuples. The\n\
3062encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3063PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003064
Christian Heimes46bebee2013-06-09 19:03:31 +02003065static PyObject *
3066PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3067{
3068 char *kwlist[] = {"store_name", "cert_type", NULL};
3069 char *store_name;
3070 char *cert_type = "certificate";
3071 HCERTSTORE hStore = NULL;
3072 PyObject *result = NULL;
3073 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3074 int ok = 1;
3075
3076 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3077 kwlist, &store_name, &cert_type)) {
3078 return NULL;
3079 }
3080
3081 if ((strcmp(cert_type, "certificate") != 0) &&
3082 (strcmp(cert_type, "crl") != 0)) {
3083 return PyErr_Format(PyExc_ValueError,
3084 "cert_type must be 'certificate' or 'crl', "
3085 "not %.100s", cert_type);
3086 }
3087
3088 if ((result = PyList_New(0)) == NULL) {
3089 return NULL;
3090 }
3091
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003092 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003093 Py_DECREF(result);
3094 return PyErr_SetFromWindowsErr(GetLastError());
3095 }
3096
3097 if (strcmp(cert_type, "certificate") == 0) {
3098 PCCERT_CONTEXT pCertCtx = NULL;
3099 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3100 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3101 pCertCtx->cbCertEncoded);
3102 if (!cert) {
3103 ok = 0;
3104 break;
3105 }
3106 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3107 ok = 0;
3108 break;
3109 }
3110 if ((tup = PyTuple_New(2)) == NULL) {
3111 ok = 0;
3112 break;
3113 }
3114 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3115 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3116
3117 if (PyList_Append(result, tup) < 0) {
3118 ok = 0;
3119 break;
3120 }
3121 Py_CLEAR(tup);
3122 }
3123 if (pCertCtx) {
3124 /* loop ended with an error, need to clean up context manually */
3125 CertFreeCertificateContext(pCertCtx);
3126 }
3127 } else {
3128 PCCRL_CONTEXT pCrlCtx = NULL;
3129 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3130 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3131 pCrlCtx->cbCrlEncoded);
3132 if (!cert) {
3133 ok = 0;
3134 break;
3135 }
3136 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3137 ok = 0;
3138 break;
3139 }
3140 if ((tup = PyTuple_New(2)) == NULL) {
3141 ok = 0;
3142 break;
3143 }
3144 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3145 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3146
3147 if (PyList_Append(result, tup) < 0) {
3148 ok = 0;
3149 break;
3150 }
3151 Py_CLEAR(tup);
3152 }
3153 if (pCrlCtx) {
3154 /* loop ended with an error, need to clean up context manually */
3155 CertFreeCRLContext(pCrlCtx);
3156 }
3157 }
3158
3159 /* In error cases cert, enc and tup may not be NULL */
3160 Py_XDECREF(cert);
3161 Py_XDECREF(enc);
3162 Py_XDECREF(tup);
3163
3164 if (!CertCloseStore(hStore, 0)) {
3165 /* This error case might shadow another exception.*/
3166 Py_DECREF(result);
3167 return PyErr_SetFromWindowsErr(GetLastError());
3168 }
3169 if (ok) {
3170 return result;
3171 } else {
3172 Py_DECREF(result);
3173 return NULL;
3174 }
3175}
3176#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003177
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003178/* List of functions exported by this module. */
3179
3180static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003181 {"_test_decode_cert", PySSL_test_decode_certificate,
3182 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003183#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003184 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3185 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003186 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3187 PySSL_RAND_bytes_doc},
3188 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3189 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003190 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003191 PySSL_RAND_egd_doc},
3192 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3193 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003194#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003195 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003196 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003197#ifdef _MSC_VER
3198 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3199 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3200#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003201 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003202};
3203
3204
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003205#ifdef WITH_THREAD
3206
3207/* an implementation of OpenSSL threading operations in terms
3208 of the Python C thread library */
3209
3210static PyThread_type_lock *_ssl_locks = NULL;
3211
Christian Heimes4d98ca92013-08-19 17:36:29 +02003212#if OPENSSL_VERSION_NUMBER >= 0x10000000
3213/* use new CRYPTO_THREADID API. */
3214static void
3215_ssl_threadid_callback(CRYPTO_THREADID *id)
3216{
3217 CRYPTO_THREADID_set_numeric(id,
3218 (unsigned long)PyThread_get_thread_ident());
3219}
3220#else
3221/* deprecated CRYPTO_set_id_callback() API. */
3222static unsigned long
3223_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003224 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003225}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003226#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003227
Bill Janssen6e027db2007-11-15 22:23:56 +00003228static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003229 (int mode, int n, const char *file, int line) {
3230 /* this function is needed to perform locking on shared data
3231 structures. (Note that OpenSSL uses a number of global data
3232 structures that will be implicitly shared whenever multiple
3233 threads use OpenSSL.) Multi-threaded applications will
3234 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003236 locking_function() must be able to handle up to
3237 CRYPTO_num_locks() different mutex locks. It sets the n-th
3238 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003240 file and line are the file number of the function setting the
3241 lock. They can be useful for debugging.
3242 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003244 if ((_ssl_locks == NULL) ||
3245 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3246 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003248 if (mode & CRYPTO_LOCK) {
3249 PyThread_acquire_lock(_ssl_locks[n], 1);
3250 } else {
3251 PyThread_release_lock(_ssl_locks[n]);
3252 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003253}
3254
3255static int _setup_ssl_threads(void) {
3256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003257 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003259 if (_ssl_locks == NULL) {
3260 _ssl_locks_count = CRYPTO_num_locks();
3261 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003262 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003263 if (_ssl_locks == NULL)
3264 return 0;
3265 memset(_ssl_locks, 0,
3266 sizeof(PyThread_type_lock) * _ssl_locks_count);
3267 for (i = 0; i < _ssl_locks_count; i++) {
3268 _ssl_locks[i] = PyThread_allocate_lock();
3269 if (_ssl_locks[i] == NULL) {
3270 unsigned int j;
3271 for (j = 0; j < i; j++) {
3272 PyThread_free_lock(_ssl_locks[j]);
3273 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003274 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003275 return 0;
3276 }
3277 }
3278 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003279#if OPENSSL_VERSION_NUMBER >= 0x10000000
3280 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3281#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003282 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003283#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003284 }
3285 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003286}
3287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003288#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003289
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003290PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003291"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003292for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003293
Martin v. Löwis1a214512008-06-11 05:26:20 +00003294
3295static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003296 PyModuleDef_HEAD_INIT,
3297 "_ssl",
3298 module_doc,
3299 -1,
3300 PySSL_methods,
3301 NULL,
3302 NULL,
3303 NULL,
3304 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003305};
3306
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003307
3308static void
3309parse_openssl_version(unsigned long libver,
3310 unsigned int *major, unsigned int *minor,
3311 unsigned int *fix, unsigned int *patch,
3312 unsigned int *status)
3313{
3314 *status = libver & 0xF;
3315 libver >>= 4;
3316 *patch = libver & 0xFF;
3317 libver >>= 8;
3318 *fix = libver & 0xFF;
3319 libver >>= 8;
3320 *minor = libver & 0xFF;
3321 libver >>= 8;
3322 *major = libver & 0xFF;
3323}
3324
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003325PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003326PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003327{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003328 PyObject *m, *d, *r;
3329 unsigned long libver;
3330 unsigned int major, minor, fix, patch, status;
3331 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003332 struct py_ssl_error_code *errcode;
3333 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003334
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335 if (PyType_Ready(&PySSLContext_Type) < 0)
3336 return NULL;
3337 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003338 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003340 m = PyModule_Create(&_sslmodule);
3341 if (m == NULL)
3342 return NULL;
3343 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003345 /* Load _socket module and its C API */
3346 socket_api = PySocketModule_ImportModuleAndAPI();
3347 if (!socket_api)
3348 return NULL;
3349 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003351 /* Init OpenSSL */
3352 SSL_load_error_strings();
3353 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003354#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003355 /* note that this will start threading if not already started */
3356 if (!_setup_ssl_threads()) {
3357 return NULL;
3358 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003359#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003360 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003361
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003362 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003363 sslerror_type_slots[0].pfunc = PyExc_OSError;
3364 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003365 if (PySSLErrorObject == NULL)
3366 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003367
Antoine Pitrou41032a62011-10-27 23:56:55 +02003368 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3369 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3370 PySSLErrorObject, NULL);
3371 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3372 "ssl.SSLWantReadError", SSLWantReadError_doc,
3373 PySSLErrorObject, NULL);
3374 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3375 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3376 PySSLErrorObject, NULL);
3377 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3378 "ssl.SSLSyscallError", SSLSyscallError_doc,
3379 PySSLErrorObject, NULL);
3380 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3381 "ssl.SSLEOFError", SSLEOFError_doc,
3382 PySSLErrorObject, NULL);
3383 if (PySSLZeroReturnErrorObject == NULL
3384 || PySSLWantReadErrorObject == NULL
3385 || PySSLWantWriteErrorObject == NULL
3386 || PySSLSyscallErrorObject == NULL
3387 || PySSLEOFErrorObject == NULL)
3388 return NULL;
3389 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3390 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3391 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3392 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3393 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3394 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003395 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003396 if (PyDict_SetItemString(d, "_SSLContext",
3397 (PyObject *)&PySSLContext_Type) != 0)
3398 return NULL;
3399 if (PyDict_SetItemString(d, "_SSLSocket",
3400 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003401 return NULL;
3402 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3403 PY_SSL_ERROR_ZERO_RETURN);
3404 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3405 PY_SSL_ERROR_WANT_READ);
3406 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3407 PY_SSL_ERROR_WANT_WRITE);
3408 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3409 PY_SSL_ERROR_WANT_X509_LOOKUP);
3410 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3411 PY_SSL_ERROR_SYSCALL);
3412 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3413 PY_SSL_ERROR_SSL);
3414 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3415 PY_SSL_ERROR_WANT_CONNECT);
3416 /* non ssl.h errorcodes */
3417 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3418 PY_SSL_ERROR_EOF);
3419 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3420 PY_SSL_ERROR_INVALID_ERROR_CODE);
3421 /* cert requirements */
3422 PyModule_AddIntConstant(m, "CERT_NONE",
3423 PY_SSL_CERT_NONE);
3424 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3425 PY_SSL_CERT_OPTIONAL);
3426 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3427 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003428
Christian Heimes46bebee2013-06-09 19:03:31 +02003429#ifdef _MSC_VER
3430 /* Windows dwCertEncodingType */
3431 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3432 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3433#endif
3434
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003435 /* Alert Descriptions from ssl.h */
3436 /* note RESERVED constants no longer intended for use have been removed */
3437 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3438
3439#define ADD_AD_CONSTANT(s) \
3440 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3441 SSL_AD_##s)
3442
3443 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3444 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3445 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3446 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3447 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3448 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3449 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3450 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3451 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3452 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3453 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3454 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3455 ADD_AD_CONSTANT(UNKNOWN_CA);
3456 ADD_AD_CONSTANT(ACCESS_DENIED);
3457 ADD_AD_CONSTANT(DECODE_ERROR);
3458 ADD_AD_CONSTANT(DECRYPT_ERROR);
3459 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3460 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3461 ADD_AD_CONSTANT(INTERNAL_ERROR);
3462 ADD_AD_CONSTANT(USER_CANCELLED);
3463 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003464 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003465#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3466 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3467#endif
3468#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3469 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3470#endif
3471#ifdef SSL_AD_UNRECOGNIZED_NAME
3472 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3473#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003474#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3475 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3476#endif
3477#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3478 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3479#endif
3480#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3481 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3482#endif
3483
3484#undef ADD_AD_CONSTANT
3485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003486 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003487#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003488 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3489 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003490#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003491 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3492 PY_SSL_VERSION_SSL3);
3493 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3494 PY_SSL_VERSION_SSL23);
3495 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3496 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003497#if HAVE_TLSv1_2
3498 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3499 PY_SSL_VERSION_TLS1_1);
3500 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3501 PY_SSL_VERSION_TLS1_2);
3502#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003503
Antoine Pitroub5218772010-05-21 09:56:06 +00003504 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003505 PyModule_AddIntConstant(m, "OP_ALL",
3506 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003507 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3508 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3509 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003510#if HAVE_TLSv1_2
3511 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3512 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3513#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003514 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3515 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003516 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003517#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003518 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003519#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003520#ifdef SSL_OP_NO_COMPRESSION
3521 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3522 SSL_OP_NO_COMPRESSION);
3523#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003524
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003525#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003526 r = Py_True;
3527#else
3528 r = Py_False;
3529#endif
3530 Py_INCREF(r);
3531 PyModule_AddObject(m, "HAS_SNI", r);
3532
Antoine Pitroud6494802011-07-21 01:11:30 +02003533#if HAVE_OPENSSL_FINISHED
3534 r = Py_True;
3535#else
3536 r = Py_False;
3537#endif
3538 Py_INCREF(r);
3539 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3540
Antoine Pitrou501da612011-12-21 09:27:41 +01003541#ifdef OPENSSL_NO_ECDH
3542 r = Py_False;
3543#else
3544 r = Py_True;
3545#endif
3546 Py_INCREF(r);
3547 PyModule_AddObject(m, "HAS_ECDH", r);
3548
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003549#ifdef OPENSSL_NPN_NEGOTIATED
3550 r = Py_True;
3551#else
3552 r = Py_False;
3553#endif
3554 Py_INCREF(r);
3555 PyModule_AddObject(m, "HAS_NPN", r);
3556
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003557 /* Mappings for error codes */
3558 err_codes_to_names = PyDict_New();
3559 err_names_to_codes = PyDict_New();
3560 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3561 return NULL;
3562 errcode = error_codes;
3563 while (errcode->mnemonic != NULL) {
3564 PyObject *mnemo, *key;
3565 mnemo = PyUnicode_FromString(errcode->mnemonic);
3566 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3567 if (mnemo == NULL || key == NULL)
3568 return NULL;
3569 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3570 return NULL;
3571 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3572 return NULL;
3573 Py_DECREF(key);
3574 Py_DECREF(mnemo);
3575 errcode++;
3576 }
3577 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3578 return NULL;
3579 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3580 return NULL;
3581
3582 lib_codes_to_names = PyDict_New();
3583 if (lib_codes_to_names == NULL)
3584 return NULL;
3585 libcode = library_codes;
3586 while (libcode->library != NULL) {
3587 PyObject *mnemo, *key;
3588 key = PyLong_FromLong(libcode->code);
3589 mnemo = PyUnicode_FromString(libcode->library);
3590 if (key == NULL || mnemo == NULL)
3591 return NULL;
3592 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3593 return NULL;
3594 Py_DECREF(key);
3595 Py_DECREF(mnemo);
3596 libcode++;
3597 }
3598 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3599 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003601 /* OpenSSL version */
3602 /* SSLeay() gives us the version of the library linked against,
3603 which could be different from the headers version.
3604 */
3605 libver = SSLeay();
3606 r = PyLong_FromUnsignedLong(libver);
3607 if (r == NULL)
3608 return NULL;
3609 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3610 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003611 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003612 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3613 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3614 return NULL;
3615 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3616 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3617 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003618
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003619 libver = OPENSSL_VERSION_NUMBER;
3620 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3621 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3622 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3623 return NULL;
3624
Christian Heimesf77b4b22013-08-21 13:26:05 +02003625#ifdef PYSSL_RAND_ATFORK
3626 if (PySSL_RAND_atfork() == -1)
3627 return NULL;
3628#endif
3629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003630 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003631}