blob: 503147698d88936c772c5a430285340b16a38558 [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
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020023#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
25#define PySSL_END_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000028 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020029 PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
31#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000034#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save)
37#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038#define PySSL_BEGIN_ALLOW_THREADS
39#define PySSL_BLOCK_THREADS
40#define PySSL_UNBLOCK_THREADS
41#define PySSL_END_ALLOW_THREADS
42
43#endif
44
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010045/* Include symbols from _socket module */
46#include "socketmodule.h"
47
48static PySocketModule_APIObject PySocketModule;
49
50#if defined(HAVE_POLL_H)
51#include <poll.h>
52#elif defined(HAVE_SYS_POLL_H)
53#include <sys/poll.h>
54#endif
55
56/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
65
66/* SSL error object */
67static PyObject *PySSLErrorObject;
68static PyObject *PySSLZeroReturnErrorObject;
69static PyObject *PySSLWantReadErrorObject;
70static PyObject *PySSLWantWriteErrorObject;
71static PyObject *PySSLSyscallErrorObject;
72static PyObject *PySSLEOFErrorObject;
73
74/* Error mappings */
75static PyObject *err_codes_to_names;
76static PyObject *err_names_to_codes;
77static PyObject *lib_codes_to_names;
78
79struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83struct py_ssl_library_code {
84 const char *library;
85 int code;
86};
87
88/* Include generated data (error codes) */
89#include "_ssl_data.h"
90
91/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
92 http://www.openssl.org/news/changelog.html
93 */
94#if OPENSSL_VERSION_NUMBER >= 0x10001000L
95# define HAVE_TLSv1_2 1
96#else
97# define HAVE_TLSv1_2 0
98#endif
99
Christian Heimes470fba12013-11-28 15:12:15 +0100100/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100101 * This includes the SSL_set_SSL_CTX() function.
102 */
103#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
104# define HAVE_SNI 1
105#else
106# define HAVE_SNI 0
107#endif
108
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000109enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000110 /* these mirror ssl.h */
111 PY_SSL_ERROR_NONE,
112 PY_SSL_ERROR_SSL,
113 PY_SSL_ERROR_WANT_READ,
114 PY_SSL_ERROR_WANT_WRITE,
115 PY_SSL_ERROR_WANT_X509_LOOKUP,
116 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
117 PY_SSL_ERROR_ZERO_RETURN,
118 PY_SSL_ERROR_WANT_CONNECT,
119 /* start of non ssl.h errorcodes */
120 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
121 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
122 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000123};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000124
Thomas Woutersed03b412007-08-28 21:37:11 +0000125enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PY_SSL_CLIENT,
127 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000128};
129
130enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000131 PY_SSL_CERT_NONE,
132 PY_SSL_CERT_OPTIONAL,
133 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000134};
135
136enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000137 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200138 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140#if HAVE_TLSv1_2
141 PY_SSL_VERSION_TLS1,
142 PY_SSL_VERSION_TLS1_1,
143 PY_SSL_VERSION_TLS1_2
144#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200148
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000149#ifdef WITH_THREAD
150
151/* serves as a flag to see whether we've initialized the SSL thread support. */
152/* 0 means no, greater than 0 means yes */
153
154static unsigned int _ssl_locks_count = 0;
155
156#endif /* def WITH_THREAD */
157
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158/* SSL socket object */
159
160#define X509_NAME_MAXLEN 256
161
162/* RAND_* APIs got added to OpenSSL in 0.9.5 */
163#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
164# define HAVE_OPENSSL_RAND 1
165#else
166# undef HAVE_OPENSSL_RAND
167#endif
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
182/* SSL_get_finished got added to OpenSSL in 0.9.5 */
183#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
184# define HAVE_OPENSSL_FINISHED 1
185#else
186# define HAVE_OPENSSL_FINISHED 0
187#endif
188
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100189/* ECDH support got added to OpenSSL in 0.9.8 */
190#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
191# define OPENSSL_NO_ECDH
192#endif
193
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100194/* compression support got added to OpenSSL in 0.9.8 */
195#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
196# define OPENSSL_NO_COMP
197#endif
198
Christian Heimes2427b502013-11-23 11:24:32 +0100199/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
200#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
201# define HAVE_OPENSSL_VERIFY_PARAM
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
Christian Heimes1aa9a752013-12-02 02:41:19 +0100215 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000216} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000217
Antoine Pitrou152efa22010-05-16 18:19:27 +0000218typedef struct {
219 PyObject_HEAD
220 PyObject *Socket; /* weakref to socket on which we're layered */
221 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100222 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200224 char shutdown_seen_zero;
225 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200226 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000227} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000228
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229static PyTypeObject PySSLContext_Type;
230static PyTypeObject PySSLSocket_Type;
231
232static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
233static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000234static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000235 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000236static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
237static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Antoine Pitrou152efa22010-05-16 18:19:27 +0000239#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
240#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000241
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000243 SOCKET_IS_NONBLOCKING,
244 SOCKET_IS_BLOCKING,
245 SOCKET_HAS_TIMED_OUT,
246 SOCKET_HAS_BEEN_CLOSED,
247 SOCKET_TOO_LARGE_FOR_SELECT,
248 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000249} timeout_state;
250
Thomas Woutersed03b412007-08-28 21:37:11 +0000251/* Wrap error strings with filename and line # */
252#define STRINGIFY1(x) #x
253#define STRINGIFY2(x) STRINGIFY1(x)
254#define ERRSTR1(x,y,z) (x ":" y ": " z)
255#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
256
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200257
258/*
259 * SSL errors.
260 */
261
262PyDoc_STRVAR(SSLError_doc,
263"An error occurred in the SSL implementation.");
264
265PyDoc_STRVAR(SSLZeroReturnError_doc,
266"SSL/TLS session closed cleanly.");
267
268PyDoc_STRVAR(SSLWantReadError_doc,
269"Non-blocking SSL socket needs to read more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLWantWriteError_doc,
273"Non-blocking SSL socket needs to write more data\n"
274"before the requested operation can be completed.");
275
276PyDoc_STRVAR(SSLSyscallError_doc,
277"System error when attempting SSL operation.");
278
279PyDoc_STRVAR(SSLEOFError_doc,
280"SSL/TLS connection terminated abruptly.");
281
282static PyObject *
283SSLError_str(PyOSErrorObject *self)
284{
285 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
286 Py_INCREF(self->strerror);
287 return self->strerror;
288 }
289 else
290 return PyObject_Str(self->args);
291}
292
293static PyType_Slot sslerror_type_slots[] = {
294 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
295 {Py_tp_doc, SSLError_doc},
296 {Py_tp_str, SSLError_str},
297 {0, 0},
298};
299
300static PyType_Spec sslerror_type_spec = {
301 "ssl.SSLError",
302 sizeof(PyOSErrorObject),
303 0,
304 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
305 sslerror_type_slots
306};
307
308static void
309fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
310 int lineno, unsigned long errcode)
311{
312 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
313 PyObject *init_value, *msg, *key;
314 _Py_IDENTIFIER(reason);
315 _Py_IDENTIFIER(library);
316
317 if (errcode != 0) {
318 int lib, reason;
319
320 lib = ERR_GET_LIB(errcode);
321 reason = ERR_GET_REASON(errcode);
322 key = Py_BuildValue("ii", lib, reason);
323 if (key == NULL)
324 goto fail;
325 reason_obj = PyDict_GetItem(err_codes_to_names, key);
326 Py_DECREF(key);
327 if (reason_obj == NULL) {
328 /* XXX if reason < 100, it might reflect a library number (!!) */
329 PyErr_Clear();
330 }
331 key = PyLong_FromLong(lib);
332 if (key == NULL)
333 goto fail;
334 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
335 Py_DECREF(key);
336 if (lib_obj == NULL) {
337 PyErr_Clear();
338 }
339 if (errstr == NULL)
340 errstr = ERR_reason_error_string(errcode);
341 }
342 if (errstr == NULL)
343 errstr = "unknown error";
344
345 if (reason_obj && lib_obj)
346 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
347 lib_obj, reason_obj, errstr, lineno);
348 else if (lib_obj)
349 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
350 lib_obj, errstr, lineno);
351 else
352 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200353 if (msg == NULL)
354 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100355
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100357 if (init_value == NULL)
358 goto fail;
359
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200360 err_value = PyObject_CallObject(type, init_value);
361 Py_DECREF(init_value);
362 if (err_value == NULL)
363 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100364
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200365 if (reason_obj == NULL)
366 reason_obj = Py_None;
367 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
368 goto fail;
369 if (lib_obj == NULL)
370 lib_obj = Py_None;
371 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
372 goto fail;
373 PyErr_SetObject(type, err_value);
374fail:
375 Py_XDECREF(err_value);
376}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377
378static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000379PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200381 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 int err;
384 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200388 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 if (obj->ssl != NULL) {
391 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 switch (err) {
394 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 errstr = "TLS/SSL connection has been closed (EOF)";
396 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 p = PY_SSL_ERROR_ZERO_RETURN;
398 break;
399 case SSL_ERROR_WANT_READ:
400 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000402 p = PY_SSL_ERROR_WANT_READ;
403 break;
404 case SSL_ERROR_WANT_WRITE:
405 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200406 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 errstr = "The operation did not complete (write)";
408 break;
409 case SSL_ERROR_WANT_X509_LOOKUP:
410 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000411 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000412 break;
413 case SSL_ERROR_WANT_CONNECT:
414 p = PY_SSL_ERROR_WANT_CONNECT;
415 errstr = "The operation did not complete (connect)";
416 break;
417 case SSL_ERROR_SYSCALL:
418 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 if (e == 0) {
420 PySocketSockObject *s
421 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
422 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200424 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000428 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000429 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000431 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000434 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200435 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 }
438 } else {
439 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000440 }
441 break;
442 }
443 case SSL_ERROR_SSL:
444 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200446 if (e == 0)
447 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000448 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 break;
450 }
451 default:
452 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
453 errstr = "Invalid error code";
454 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000457 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459}
460
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461static PyObject *
462_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
463
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 else
467 errcode = 0;
468 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000469 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471}
472
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473/*
474 * SSL objects
475 */
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100478newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000479 enum py_ssl_server_or_client socket_type,
480 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100483 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200484 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
Antoine Pitrou152efa22010-05-16 18:19:27 +0000486 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 if (self == NULL)
488 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 self->peer_cert = NULL;
491 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100493 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200494 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200495 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100496 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 /* Make sure the SSL error state is initialized */
499 (void) ERR_get_state();
500 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000503 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100505 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100506 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000508#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000510#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200511 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000512
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100513#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000514 if (server_hostname != NULL)
515 SSL_set_tlsext_host_name(self->ssl, server_hostname);
516#endif
517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 /* If the socket is in non-blocking mode or timeout mode, set the BIO
519 * to non-blocking mode (blocking is the default)
520 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
523 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
524 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 PySSL_BEGIN_ALLOW_THREADS
527 if (socket_type == PY_SSL_CLIENT)
528 SSL_set_connect_state(self->ssl);
529 else
530 SSL_set_accept_state(self->ssl);
531 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000532
Antoine Pitroud6494802011-07-21 01:11:30 +0200533 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000534 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100535 if (self->Socket == NULL) {
536 Py_DECREF(self);
537 return NULL;
538 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000540}
541
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542/* SSL object methods */
543
Antoine Pitrou152efa22010-05-16 18:19:27 +0000544static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000545{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 int ret;
547 int err;
548 int sockstate, nonblocking;
549 PySocketSockObject *sock
550 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 if (((PyObject*)sock) == Py_None) {
553 _setSSLError("Underlying socket connection gone",
554 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
555 return NULL;
556 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000557 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000559 /* just in case the blocking state of the socket has been changed */
560 nonblocking = (sock->sock_timeout >= 0.0);
561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 /* Actually negotiate SSL connection */
565 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000567 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 ret = SSL_do_handshake(self->ssl);
569 err = SSL_get_error(self->ssl, ret);
570 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 if (PyErr_CheckSignals())
572 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 if (err == SSL_ERROR_WANT_READ) {
574 sockstate = check_socket_and_wait_for_timeout(sock, 0);
575 } else if (err == SSL_ERROR_WANT_WRITE) {
576 sockstate = check_socket_and_wait_for_timeout(sock, 1);
577 } else {
578 sockstate = SOCKET_OPERATION_OK;
579 }
580 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000581 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
585 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000586 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
589 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000590 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
593 break;
594 }
595 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000596 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 if (ret < 1)
598 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 if (self->peer_cert)
601 X509_free (self->peer_cert);
602 PySSL_BEGIN_ALLOW_THREADS
603 self->peer_cert = SSL_get_peer_certificate(self->ssl);
604 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200605 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606
607 Py_INCREF(Py_None);
608 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000609
610error:
611 Py_DECREF(sock);
612 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613}
614
Thomas Woutersed03b412007-08-28 21:37:11 +0000615static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 char namebuf[X509_NAME_MAXLEN];
619 int buflen;
620 PyObject *name_obj;
621 PyObject *value_obj;
622 PyObject *attr;
623 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
626 if (buflen < 0) {
627 _setSSLError(NULL, 0, __FILE__, __LINE__);
628 goto fail;
629 }
630 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
631 if (name_obj == NULL)
632 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
635 if (buflen < 0) {
636 _setSSLError(NULL, 0, __FILE__, __LINE__);
637 Py_DECREF(name_obj);
638 goto fail;
639 }
640 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000641 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 OPENSSL_free(valuebuf);
643 if (value_obj == NULL) {
644 Py_DECREF(name_obj);
645 goto fail;
646 }
647 attr = PyTuple_New(2);
648 if (attr == NULL) {
649 Py_DECREF(name_obj);
650 Py_DECREF(value_obj);
651 goto fail;
652 }
653 PyTuple_SET_ITEM(attr, 0, name_obj);
654 PyTuple_SET_ITEM(attr, 1, value_obj);
655 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000659}
660
661static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
665 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
666 PyObject *rdnt;
667 PyObject *attr = NULL; /* tuple to hold an attribute */
668 int entry_count = X509_NAME_entry_count(xname);
669 X509_NAME_ENTRY *entry;
670 ASN1_OBJECT *name;
671 ASN1_STRING *value;
672 int index_counter;
673 int rdn_level = -1;
674 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 dn = PyList_New(0);
677 if (dn == NULL)
678 return NULL;
679 /* now create another tuple to hold the top-level RDN */
680 rdn = PyList_New(0);
681 if (rdn == NULL)
682 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 for (index_counter = 0;
685 index_counter < entry_count;
686 index_counter++)
687 {
688 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 /* check to see if we've gotten to a new RDN */
691 if (rdn_level >= 0) {
692 if (rdn_level != entry->set) {
693 /* yes, new RDN */
694 /* add old RDN to DN */
695 rdnt = PyList_AsTuple(rdn);
696 Py_DECREF(rdn);
697 if (rdnt == NULL)
698 goto fail0;
699 retcode = PyList_Append(dn, rdnt);
700 Py_DECREF(rdnt);
701 if (retcode < 0)
702 goto fail0;
703 /* create new RDN */
704 rdn = PyList_New(0);
705 if (rdn == NULL)
706 goto fail0;
707 }
708 }
709 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 /* now add this attribute to the current RDN */
712 name = X509_NAME_ENTRY_get_object(entry);
713 value = X509_NAME_ENTRY_get_data(entry);
714 attr = _create_tuple_for_attribute(name, value);
715 /*
716 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
717 entry->set,
718 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
719 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
720 */
721 if (attr == NULL)
722 goto fail1;
723 retcode = PyList_Append(rdn, attr);
724 Py_DECREF(attr);
725 if (retcode < 0)
726 goto fail1;
727 }
728 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100729 if (rdn != NULL) {
730 if (PyList_GET_SIZE(rdn) > 0) {
731 rdnt = PyList_AsTuple(rdn);
732 Py_DECREF(rdn);
733 if (rdnt == NULL)
734 goto fail0;
735 retcode = PyList_Append(dn, rdnt);
736 Py_DECREF(rdnt);
737 if (retcode < 0)
738 goto fail0;
739 }
740 else {
741 Py_DECREF(rdn);
742 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* convert list to tuple */
746 rdnt = PyList_AsTuple(dn);
747 Py_DECREF(dn);
748 if (rdnt == NULL)
749 return NULL;
750 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
752 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754
755 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 Py_XDECREF(dn);
757 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758}
759
760static PyObject *
761_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 /* this code follows the procedure outlined in
764 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
765 function to extract the STACK_OF(GENERAL_NAME),
766 then iterates through the stack to add the
767 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 int i, j;
770 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200771 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 X509_EXTENSION *ext = NULL;
773 GENERAL_NAMES *names = NULL;
774 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000775 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 BIO *biobuf = NULL;
777 char buf[2048];
778 char *vptr;
779 int len;
780 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000781#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000783#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000785#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 if (certificate == NULL)
788 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 /* get a memory buffer */
791 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200793 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 while ((i = X509_get_ext_by_NID(
795 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 if (peer_alt_names == Py_None) {
798 peer_alt_names = PyList_New(0);
799 if (peer_alt_names == NULL)
800 goto fail;
801 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* now decode the altName */
804 ext = X509_get_ext(certificate, i);
805 if(!(method = X509V3_EXT_get(ext))) {
806 PyErr_SetString
807 (PySSLErrorObject,
808 ERRSTR("No method for internalizing subjectAltName!"));
809 goto fail;
810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 p = ext->value->data;
813 if (method->it)
814 names = (GENERAL_NAMES*)
815 (ASN1_item_d2i(NULL,
816 &p,
817 ext->value->length,
818 ASN1_ITEM_ptr(method->it)));
819 else
820 names = (GENERAL_NAMES*)
821 (method->d2i(NULL,
822 &p,
823 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200827 int gntype;
828 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200831 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200832 switch (gntype) {
833 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* we special-case DirName as a tuple of
835 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 t = PyTuple_New(2);
838 if (t == NULL) {
839 goto fail;
840 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 v = PyUnicode_FromString("DirName");
843 if (v == NULL) {
844 Py_DECREF(t);
845 goto fail;
846 }
847 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 v = _create_tuple_for_X509_NAME (name->d.dirn);
850 if (v == NULL) {
851 Py_DECREF(t);
852 goto fail;
853 }
854 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200855 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000856
Christian Heimes824f7f32013-08-17 00:54:47 +0200857 case GEN_EMAIL:
858 case GEN_DNS:
859 case GEN_URI:
860 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
861 correctly, CVE-2013-4238 */
862 t = PyTuple_New(2);
863 if (t == NULL)
864 goto fail;
865 switch (gntype) {
866 case GEN_EMAIL:
867 v = PyUnicode_FromString("email");
868 as = name->d.rfc822Name;
869 break;
870 case GEN_DNS:
871 v = PyUnicode_FromString("DNS");
872 as = name->d.dNSName;
873 break;
874 case GEN_URI:
875 v = PyUnicode_FromString("URI");
876 as = name->d.uniformResourceIdentifier;
877 break;
878 }
879 if (v == NULL) {
880 Py_DECREF(t);
881 goto fail;
882 }
883 PyTuple_SET_ITEM(t, 0, v);
884 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
885 ASN1_STRING_length(as));
886 if (v == NULL) {
887 Py_DECREF(t);
888 goto fail;
889 }
890 PyTuple_SET_ITEM(t, 1, v);
891 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Christian Heimes824f7f32013-08-17 00:54:47 +0200893 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 switch (gntype) {
896 /* check for new general name type */
897 case GEN_OTHERNAME:
898 case GEN_X400:
899 case GEN_EDIPARTY:
900 case GEN_IPADD:
901 case GEN_RID:
902 break;
903 default:
904 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
905 "Unknown general name type %d",
906 gntype) == -1) {
907 goto fail;
908 }
909 break;
910 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 (void) BIO_reset(biobuf);
912 GENERAL_NAME_print(biobuf, name);
913 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
914 if (len < 0) {
915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 goto fail;
917 }
918 vptr = strchr(buf, ':');
919 if (vptr == NULL)
920 goto fail;
921 t = PyTuple_New(2);
922 if (t == NULL)
923 goto fail;
924 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
925 if (v == NULL) {
926 Py_DECREF(t);
927 goto fail;
928 }
929 PyTuple_SET_ITEM(t, 0, v);
930 v = PyUnicode_FromStringAndSize((vptr + 1),
931 (len - (vptr - buf + 1)));
932 if (v == NULL) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 if (PyList_Append(peer_alt_names, t) < 0) {
943 Py_DECREF(t);
944 goto fail;
945 }
946 Py_DECREF(t);
947 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100948 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 }
950 BIO_free(biobuf);
951 if (peer_alt_names != Py_None) {
952 v = PyList_AsTuple(peer_alt_names);
953 Py_DECREF(peer_alt_names);
954 return v;
955 } else {
956 return peer_alt_names;
957 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000958
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
960 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 if (biobuf != NULL)
962 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 if (peer_alt_names != Py_None) {
965 Py_XDECREF(peer_alt_names);
966 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969}
970
971static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100972_get_aia_uri(X509 *certificate, int nid) {
973 PyObject *lst = NULL, *ostr = NULL;
974 int i, result;
975 AUTHORITY_INFO_ACCESS *info;
976
977 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
978 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
979 return Py_None;
980 }
981
982 if ((lst = PyList_New(0)) == NULL) {
983 goto fail;
984 }
985
986 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
987 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
988 ASN1_IA5STRING *uri;
989
990 if ((OBJ_obj2nid(ad->method) != nid) ||
991 (ad->location->type != GEN_URI)) {
992 continue;
993 }
994 uri = ad->location->d.uniformResourceIdentifier;
995 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
996 uri->length);
997 if (ostr == NULL) {
998 goto fail;
999 }
1000 result = PyList_Append(lst, ostr);
1001 Py_DECREF(ostr);
1002 if (result < 0) {
1003 goto fail;
1004 }
1005 }
1006 AUTHORITY_INFO_ACCESS_free(info);
1007
1008 /* convert to tuple or None */
1009 if (PyList_Size(lst) == 0) {
1010 Py_DECREF(lst);
1011 return Py_None;
1012 } else {
1013 PyObject *tup;
1014 tup = PyList_AsTuple(lst);
1015 Py_DECREF(lst);
1016 return tup;
1017 }
1018
1019 fail:
1020 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001021 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001022 return NULL;
1023}
1024
1025static PyObject *
1026_get_crl_dp(X509 *certificate) {
1027 STACK_OF(DIST_POINT) *dps;
1028 int i, j, result;
1029 PyObject *lst;
1030
Christian Heimes949ec142013-11-21 16:26:51 +01001031#if OPENSSL_VERSION_NUMBER < 0x10001000L
1032 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1033 NULL, NULL);
1034#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001035 /* Calls x509v3_cache_extensions and sets up crldp */
1036 X509_check_ca(certificate);
1037 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001038#endif
1039
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001040 if (dps == NULL) {
1041 return Py_None;
1042 }
1043
1044 if ((lst = PyList_New(0)) == NULL) {
1045 return NULL;
1046 }
1047
1048 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1049 DIST_POINT *dp;
1050 STACK_OF(GENERAL_NAME) *gns;
1051
1052 dp = sk_DIST_POINT_value(dps, i);
1053 gns = dp->distpoint->name.fullname;
1054
1055 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1056 GENERAL_NAME *gn;
1057 ASN1_IA5STRING *uri;
1058 PyObject *ouri;
1059
1060 gn = sk_GENERAL_NAME_value(gns, j);
1061 if (gn->type != GEN_URI) {
1062 continue;
1063 }
1064 uri = gn->d.uniformResourceIdentifier;
1065 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1066 uri->length);
1067 if (ouri == NULL) {
1068 Py_DECREF(lst);
1069 return NULL;
1070 }
1071 result = PyList_Append(lst, ouri);
1072 Py_DECREF(ouri);
1073 if (result < 0) {
1074 Py_DECREF(lst);
1075 return NULL;
1076 }
1077 }
1078 }
1079 /* convert to tuple or None */
1080 if (PyList_Size(lst) == 0) {
1081 Py_DECREF(lst);
1082 return Py_None;
1083 } else {
1084 PyObject *tup;
1085 tup = PyList_AsTuple(lst);
1086 Py_DECREF(lst);
1087 return tup;
1088 }
1089}
1090
1091static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001092_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 PyObject *retval = NULL;
1095 BIO *biobuf = NULL;
1096 PyObject *peer;
1097 PyObject *peer_alt_names = NULL;
1098 PyObject *issuer;
1099 PyObject *version;
1100 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001101 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 ASN1_INTEGER *serialNumber;
1103 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001104 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 ASN1_TIME *notBefore, *notAfter;
1106 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 retval = PyDict_New();
1109 if (retval == NULL)
1110 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 peer = _create_tuple_for_X509_NAME(
1113 X509_get_subject_name(certificate));
1114 if (peer == NULL)
1115 goto fail0;
1116 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1117 Py_DECREF(peer);
1118 goto fail0;
1119 }
1120 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001121
Antoine Pitroufb046912010-11-09 20:21:19 +00001122 issuer = _create_tuple_for_X509_NAME(
1123 X509_get_issuer_name(certificate));
1124 if (issuer == NULL)
1125 goto fail0;
1126 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001128 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001130 Py_DECREF(issuer);
1131
1132 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001133 if (version == NULL)
1134 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001135 if (PyDict_SetItemString(retval, "version", version) < 0) {
1136 Py_DECREF(version);
1137 goto fail0;
1138 }
1139 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 /* get a memory buffer */
1142 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001143
Antoine Pitroufb046912010-11-09 20:21:19 +00001144 (void) BIO_reset(biobuf);
1145 serialNumber = X509_get_serialNumber(certificate);
1146 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1147 i2a_ASN1_INTEGER(biobuf, serialNumber);
1148 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1149 if (len < 0) {
1150 _setSSLError(NULL, 0, __FILE__, __LINE__);
1151 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001153 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1154 if (sn_obj == NULL)
1155 goto fail1;
1156 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1157 Py_DECREF(sn_obj);
1158 goto fail1;
1159 }
1160 Py_DECREF(sn_obj);
1161
1162 (void) BIO_reset(biobuf);
1163 notBefore = X509_get_notBefore(certificate);
1164 ASN1_TIME_print(biobuf, notBefore);
1165 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1166 if (len < 0) {
1167 _setSSLError(NULL, 0, __FILE__, __LINE__);
1168 goto fail1;
1169 }
1170 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1171 if (pnotBefore == NULL)
1172 goto fail1;
1173 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1174 Py_DECREF(pnotBefore);
1175 goto fail1;
1176 }
1177 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 (void) BIO_reset(biobuf);
1180 notAfter = X509_get_notAfter(certificate);
1181 ASN1_TIME_print(biobuf, notAfter);
1182 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1183 if (len < 0) {
1184 _setSSLError(NULL, 0, __FILE__, __LINE__);
1185 goto fail1;
1186 }
1187 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1188 if (pnotAfter == NULL)
1189 goto fail1;
1190 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1191 Py_DECREF(pnotAfter);
1192 goto fail1;
1193 }
1194 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 peer_alt_names = _get_peer_alt_names(certificate);
1199 if (peer_alt_names == NULL)
1200 goto fail1;
1201 else if (peer_alt_names != Py_None) {
1202 if (PyDict_SetItemString(retval, "subjectAltName",
1203 peer_alt_names) < 0) {
1204 Py_DECREF(peer_alt_names);
1205 goto fail1;
1206 }
1207 Py_DECREF(peer_alt_names);
1208 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001209
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 /* Authority Information Access: OCSP URIs */
1211 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1212 if (obj == NULL) {
1213 goto fail1;
1214 } else if (obj != Py_None) {
1215 result = PyDict_SetItemString(retval, "OCSP", obj);
1216 Py_DECREF(obj);
1217 if (result < 0) {
1218 goto fail1;
1219 }
1220 }
1221
1222 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1223 if (obj == NULL) {
1224 goto fail1;
1225 } else if (obj != Py_None) {
1226 result = PyDict_SetItemString(retval, "caIssuers", obj);
1227 Py_DECREF(obj);
1228 if (result < 0) {
1229 goto fail1;
1230 }
1231 }
1232
1233 /* CDP (CRL distribution points) */
1234 obj = _get_crl_dp(certificate);
1235 if (obj == NULL) {
1236 goto fail1;
1237 } else if (obj != Py_None) {
1238 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1239 Py_DECREF(obj);
1240 if (result < 0) {
1241 goto fail1;
1242 }
1243 }
1244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 BIO_free(biobuf);
1246 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001247
1248 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 if (biobuf != NULL)
1250 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001251 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 Py_XDECREF(retval);
1253 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001254}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255
Christian Heimes9a5395a2013-06-17 15:44:12 +02001256static PyObject *
1257_certificate_to_der(X509 *certificate)
1258{
1259 unsigned char *bytes_buf = NULL;
1260 int len;
1261 PyObject *retval;
1262
1263 bytes_buf = NULL;
1264 len = i2d_X509(certificate, &bytes_buf);
1265 if (len < 0) {
1266 _setSSLError(NULL, 0, __FILE__, __LINE__);
1267 return NULL;
1268 }
1269 /* this is actually an immutable bytes sequence */
1270 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1271 OPENSSL_free(bytes_buf);
1272 return retval;
1273}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
1275static PyObject *
1276PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001279 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 X509 *x=NULL;
1281 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
Antoine Pitroufb046912010-11-09 20:21:19 +00001283 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1284 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1288 PyErr_SetString(PySSLErrorObject,
1289 "Can't malloc memory to read file");
1290 goto fail0;
1291 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292
Victor Stinner3800e1e2010-05-16 21:23:48 +00001293 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 PyErr_SetString(PySSLErrorObject,
1295 "Can't open file");
1296 goto fail0;
1297 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1300 if (x == NULL) {
1301 PyErr_SetString(PySSLErrorObject,
1302 "Error decoding PEM-encoded file");
1303 goto fail0;
1304 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001305
Antoine Pitroufb046912010-11-09 20:21:19 +00001306 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001307 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
1309 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001310 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 if (cert != NULL) BIO_free(cert);
1312 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313}
1314
1315
1316static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001317PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001320 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Antoine Pitrou721738f2012-08-15 23:20:39 +02001322 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324
Antoine Pitrou20b85552013-09-29 19:50:53 +02001325 if (!self->handshake_done) {
1326 PyErr_SetString(PyExc_ValueError,
1327 "handshake not done yet");
1328 return NULL;
1329 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 if (!self->peer_cert)
1331 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitrou721738f2012-08-15 23:20:39 +02001333 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001335 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001337 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 if ((verification & SSL_VERIFY_PEER) == 0)
1339 return PyDict_New();
1340 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001341 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343}
1344
1345PyDoc_STRVAR(PySSL_peercert_doc,
1346"peer_certificate([der=False]) -> certificate\n\
1347\n\
1348Returns the certificate for the peer. If no certificate was provided,\n\
1349returns None. If a certificate was provided, but not validated, returns\n\
1350an empty dictionary. Otherwise returns a dict containing information\n\
1351about the peer certificate.\n\
1352\n\
1353If the optional argument is True, returns a DER-encoded copy of the\n\
1354peer certificate, or None if no certificate was provided. This will\n\
1355return the certificate even if it wasn't validated.");
1356
Antoine Pitrou152efa22010-05-16 18:19:27 +00001357static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001360 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 char *cipher_name;
1362 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001365 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 current = SSL_get_current_cipher(self->ssl);
1367 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001368 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 retval = PyTuple_New(3);
1371 if (retval == NULL)
1372 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 cipher_name = (char *) SSL_CIPHER_get_name(current);
1375 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001376 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 PyTuple_SET_ITEM(retval, 0, Py_None);
1378 } else {
1379 v = PyUnicode_FromString(cipher_name);
1380 if (v == NULL)
1381 goto fail0;
1382 PyTuple_SET_ITEM(retval, 0, v);
1383 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001384 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001386 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 PyTuple_SET_ITEM(retval, 1, Py_None);
1388 } else {
1389 v = PyUnicode_FromString(cipher_protocol);
1390 if (v == NULL)
1391 goto fail0;
1392 PyTuple_SET_ITEM(retval, 1, v);
1393 }
1394 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1395 if (v == NULL)
1396 goto fail0;
1397 PyTuple_SET_ITEM(retval, 2, v);
1398 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 Py_DECREF(retval);
1402 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403}
1404
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001405#ifdef OPENSSL_NPN_NEGOTIATED
1406static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1407 const unsigned char *out;
1408 unsigned int outlen;
1409
Victor Stinner4569cd52013-06-23 14:58:43 +02001410 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001411 &out, &outlen);
1412
1413 if (out == NULL)
1414 Py_RETURN_NONE;
1415 return PyUnicode_FromStringAndSize((char *) out, outlen);
1416}
1417#endif
1418
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001419static PyObject *PySSL_compression(PySSLSocket *self) {
1420#ifdef OPENSSL_NO_COMP
1421 Py_RETURN_NONE;
1422#else
1423 const COMP_METHOD *comp_method;
1424 const char *short_name;
1425
1426 if (self->ssl == NULL)
1427 Py_RETURN_NONE;
1428 comp_method = SSL_get_current_compression(self->ssl);
1429 if (comp_method == NULL || comp_method->type == NID_undef)
1430 Py_RETURN_NONE;
1431 short_name = OBJ_nid2sn(comp_method->type);
1432 if (short_name == NULL)
1433 Py_RETURN_NONE;
1434 return PyUnicode_DecodeFSDefault(short_name);
1435#endif
1436}
1437
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001438static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1439 Py_INCREF(self->ctx);
1440 return self->ctx;
1441}
1442
1443static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1444 void *closure) {
1445
1446 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001447#if !HAVE_SNI
1448 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1449 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001450 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001451#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001452 Py_INCREF(value);
1453 Py_DECREF(self->ctx);
1454 self->ctx = (PySSLContext *) value;
1455 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001456#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001457 } else {
1458 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1459 return -1;
1460 }
1461
1462 return 0;
1463}
1464
1465PyDoc_STRVAR(PySSL_set_context_doc,
1466"_setter_context(ctx)\n\
1467\
1468This changes the context associated with the SSLSocket. This is typically\n\
1469used from within a callback function set by the set_servername_callback\n\
1470on the SSLContext to change the certificate information associated with the\n\
1471SSLSocket before the cryptographic exchange handshake messages\n");
1472
1473
1474
Antoine Pitrou152efa22010-05-16 18:19:27 +00001475static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001476{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 if (self->peer_cert) /* Possible not to have one? */
1478 X509_free (self->peer_cert);
1479 if (self->ssl)
1480 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001482 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001484}
1485
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001487 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001488 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001489 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001490
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001491static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001492check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001493{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 fd_set fds;
1495 struct timeval tv;
1496 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1499 if (s->sock_timeout < 0.0)
1500 return SOCKET_IS_BLOCKING;
1501 else if (s->sock_timeout == 0.0)
1502 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 /* Guard against closed socket */
1505 if (s->sock_fd < 0)
1506 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 /* Prefer poll, if available, since you can poll() any fd
1509 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001510#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 {
1512 struct pollfd pollfd;
1513 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 pollfd.fd = s->sock_fd;
1516 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 /* s->sock_timeout is in seconds, timeout in ms */
1519 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1520 PySSL_BEGIN_ALLOW_THREADS
1521 rc = poll(&pollfd, 1, timeout);
1522 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 goto normal_return;
1525 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001526#endif
1527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001529 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 /* Construct the arguments to select */
1533 tv.tv_sec = (int)s->sock_timeout;
1534 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1535 FD_ZERO(&fds);
1536 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001537
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 /* See if the socket is ready */
1539 PySSL_BEGIN_ALLOW_THREADS
1540 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001541 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1542 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001544 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1545 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001547
Bill Janssen6e027db2007-11-15 22:23:56 +00001548#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001549normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001550#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1552 (when we are able to write or when there's something to read) */
1553 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001554}
1555
Antoine Pitrou152efa22010-05-16 18:19:27 +00001556static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001557{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 Py_buffer buf;
1559 int len;
1560 int sockstate;
1561 int err;
1562 int nonblocking;
1563 PySocketSockObject *sock
1564 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 if (((PyObject*)sock) == Py_None) {
1567 _setSSLError("Underlying socket connection gone",
1568 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1569 return NULL;
1570 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001571 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001573 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1574 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001576 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577
Victor Stinner6efa9652013-06-25 00:42:31 +02001578 if (buf.len > INT_MAX) {
1579 PyErr_Format(PyExc_OverflowError,
1580 "string longer than %d bytes", INT_MAX);
1581 goto error;
1582 }
1583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 /* just in case the blocking state of the socket has been changed */
1585 nonblocking = (sock->sock_timeout >= 0.0);
1586 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1587 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1588
1589 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1590 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001591 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 "The write operation timed out");
1593 goto error;
1594 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1595 PyErr_SetString(PySSLErrorObject,
1596 "Underlying socket has been closed.");
1597 goto error;
1598 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1599 PyErr_SetString(PySSLErrorObject,
1600 "Underlying socket too large for select().");
1601 goto error;
1602 }
1603 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001605 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 err = SSL_get_error(self->ssl, len);
1607 PySSL_END_ALLOW_THREADS
1608 if (PyErr_CheckSignals()) {
1609 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001610 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001612 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001614 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 } else {
1616 sockstate = SOCKET_OPERATION_OK;
1617 }
1618 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001619 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 "The write operation timed out");
1621 goto error;
1622 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1623 PyErr_SetString(PySSLErrorObject,
1624 "Underlying socket has been closed.");
1625 goto error;
1626 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1627 break;
1628 }
1629 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001630
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001631 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 PyBuffer_Release(&buf);
1633 if (len > 0)
1634 return PyLong_FromLong(len);
1635 else
1636 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001637
1638error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001639 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 PyBuffer_Release(&buf);
1641 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001642}
1643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001645"write(s) -> len\n\
1646\n\
1647Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001649
Antoine Pitrou152efa22010-05-16 18:19:27 +00001650static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001651{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001654 PySSL_BEGIN_ALLOW_THREADS
1655 count = SSL_pending(self->ssl);
1656 PySSL_END_ALLOW_THREADS
1657 if (count < 0)
1658 return PySSL_SetError(self, count, __FILE__, __LINE__);
1659 else
1660 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001661}
1662
1663PyDoc_STRVAR(PySSL_SSLpending_doc,
1664"pending() -> count\n\
1665\n\
1666Returns the number of already decrypted bytes available for read,\n\
1667pending on the connection.\n");
1668
Antoine Pitrou152efa22010-05-16 18:19:27 +00001669static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001670{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 PyObject *dest = NULL;
1672 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001674 int len, count;
1675 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 int sockstate;
1677 int err;
1678 int nonblocking;
1679 PySocketSockObject *sock
1680 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 if (((PyObject*)sock) == Py_None) {
1683 _setSSLError("Underlying socket connection gone",
1684 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1685 return NULL;
1686 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001687 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001689 buf.obj = NULL;
1690 buf.buf = NULL;
1691 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001692 goto error;
1693
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001694 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1695 dest = PyBytes_FromStringAndSize(NULL, len);
1696 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001697 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001698 mem = PyBytes_AS_STRING(dest);
1699 }
1700 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001702 mem = buf.buf;
1703 if (len <= 0 || len > buf.len) {
1704 len = (int) buf.len;
1705 if (buf.len != len) {
1706 PyErr_SetString(PyExc_OverflowError,
1707 "maximum length can't fit in a C 'int'");
1708 goto error;
1709 }
1710 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 }
1712
1713 /* just in case the blocking state of the socket has been changed */
1714 nonblocking = (sock->sock_timeout >= 0.0);
1715 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1716 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1717
1718 /* first check if there are bytes ready to be read */
1719 PySSL_BEGIN_ALLOW_THREADS
1720 count = SSL_pending(self->ssl);
1721 PySSL_END_ALLOW_THREADS
1722
1723 if (!count) {
1724 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1725 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001726 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 "The read operation timed out");
1728 goto error;
1729 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1730 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001731 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 goto error;
1733 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1734 count = 0;
1735 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001736 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 }
1738 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 PySSL_BEGIN_ALLOW_THREADS
1740 count = SSL_read(self->ssl, mem, len);
1741 err = SSL_get_error(self->ssl, count);
1742 PySSL_END_ALLOW_THREADS
1743 if (PyErr_CheckSignals())
1744 goto error;
1745 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001746 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001748 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1750 (SSL_get_shutdown(self->ssl) ==
1751 SSL_RECEIVED_SHUTDOWN))
1752 {
1753 count = 0;
1754 goto done;
1755 } else {
1756 sockstate = SOCKET_OPERATION_OK;
1757 }
1758 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001759 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 "The read operation timed out");
1761 goto error;
1762 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1763 break;
1764 }
1765 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1766 if (count <= 0) {
1767 PySSL_SetError(self, count, __FILE__, __LINE__);
1768 goto error;
1769 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001770
1771done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001772 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001773 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001774 _PyBytes_Resize(&dest, count);
1775 return dest;
1776 }
1777 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 PyBuffer_Release(&buf);
1779 return PyLong_FromLong(count);
1780 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001781
1782error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001783 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001784 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001785 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001786 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001789}
1790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001792"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001795
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001797{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 int err, ssl_err, sockstate, nonblocking;
1799 int zeros = 0;
1800 PySocketSockObject *sock
1801 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 /* Guard against closed socket */
1804 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1805 _setSSLError("Underlying socket connection gone",
1806 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1807 return NULL;
1808 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001809 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810
1811 /* Just in case the blocking state of the socket has been changed */
1812 nonblocking = (sock->sock_timeout >= 0.0);
1813 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1814 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1815
1816 while (1) {
1817 PySSL_BEGIN_ALLOW_THREADS
1818 /* Disable read-ahead so that unwrap can work correctly.
1819 * Otherwise OpenSSL might read in too much data,
1820 * eating clear text data that happens to be
1821 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001822 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 * function is used and the shutdown_seen_zero != 0
1824 * condition is met.
1825 */
1826 if (self->shutdown_seen_zero)
1827 SSL_set_read_ahead(self->ssl, 0);
1828 err = SSL_shutdown(self->ssl);
1829 PySSL_END_ALLOW_THREADS
1830 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1831 if (err > 0)
1832 break;
1833 if (err == 0) {
1834 /* Don't loop endlessly; instead preserve legacy
1835 behaviour of trying SSL_shutdown() only twice.
1836 This looks necessary for OpenSSL < 0.9.8m */
1837 if (++zeros > 1)
1838 break;
1839 /* Shutdown was sent, now try receiving */
1840 self->shutdown_seen_zero = 1;
1841 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001842 }
1843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 /* Possibly retry shutdown until timeout or failure */
1845 ssl_err = SSL_get_error(self->ssl, err);
1846 if (ssl_err == SSL_ERROR_WANT_READ)
1847 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1848 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1849 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1850 else
1851 break;
1852 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1853 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001854 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 "The read operation timed out");
1856 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001857 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001859 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 }
1861 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1862 PyErr_SetString(PySSLErrorObject,
1863 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001864 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 }
1866 else if (sockstate != SOCKET_OPERATION_OK)
1867 /* Retain the SSL error code */
1868 break;
1869 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001870
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001871 if (err < 0) {
1872 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001875 else
1876 /* It's already INCREF'ed */
1877 return (PyObject *) sock;
1878
1879error:
1880 Py_DECREF(sock);
1881 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001882}
1883
1884PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1885"shutdown(s) -> socket\n\
1886\n\
1887Does the SSL shutdown handshake with the remote end, and returns\n\
1888the underlying socket object.");
1889
Antoine Pitroud6494802011-07-21 01:11:30 +02001890#if HAVE_OPENSSL_FINISHED
1891static PyObject *
1892PySSL_tls_unique_cb(PySSLSocket *self)
1893{
1894 PyObject *retval = NULL;
1895 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001896 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001897
1898 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1899 /* if session is resumed XOR we are the client */
1900 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1901 }
1902 else {
1903 /* if a new session XOR we are the server */
1904 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1905 }
1906
1907 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001908 if (len == 0)
1909 Py_RETURN_NONE;
1910
1911 retval = PyBytes_FromStringAndSize(buf, len);
1912
1913 return retval;
1914}
1915
1916PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1917"tls_unique_cb() -> bytes\n\
1918\n\
1919Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1920\n\
1921If the TLS handshake is not yet complete, None is returned");
1922
1923#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001924
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001925static PyGetSetDef ssl_getsetlist[] = {
1926 {"context", (getter) PySSL_get_context,
1927 (setter) PySSL_set_context, PySSL_set_context_doc},
1928 {NULL}, /* sentinel */
1929};
1930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001931static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1933 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1934 PySSL_SSLwrite_doc},
1935 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1936 PySSL_SSLread_doc},
1937 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1938 PySSL_SSLpending_doc},
1939 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1940 PySSL_peercert_doc},
1941 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001942#ifdef OPENSSL_NPN_NEGOTIATED
1943 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1944#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001945 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1947 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001948#if HAVE_OPENSSL_FINISHED
1949 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1950 PySSL_tls_unique_cb_doc},
1951#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001953};
1954
Antoine Pitrou152efa22010-05-16 18:19:27 +00001955static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001957 "_ssl._SSLSocket", /*tp_name*/
1958 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 0, /*tp_itemsize*/
1960 /* methods */
1961 (destructor)PySSL_dealloc, /*tp_dealloc*/
1962 0, /*tp_print*/
1963 0, /*tp_getattr*/
1964 0, /*tp_setattr*/
1965 0, /*tp_reserved*/
1966 0, /*tp_repr*/
1967 0, /*tp_as_number*/
1968 0, /*tp_as_sequence*/
1969 0, /*tp_as_mapping*/
1970 0, /*tp_hash*/
1971 0, /*tp_call*/
1972 0, /*tp_str*/
1973 0, /*tp_getattro*/
1974 0, /*tp_setattro*/
1975 0, /*tp_as_buffer*/
1976 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1977 0, /*tp_doc*/
1978 0, /*tp_traverse*/
1979 0, /*tp_clear*/
1980 0, /*tp_richcompare*/
1981 0, /*tp_weaklistoffset*/
1982 0, /*tp_iter*/
1983 0, /*tp_iternext*/
1984 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001985 0, /*tp_members*/
1986 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001987};
1988
Antoine Pitrou152efa22010-05-16 18:19:27 +00001989
1990/*
1991 * _SSLContext objects
1992 */
1993
1994static PyObject *
1995context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1996{
1997 char *kwlist[] = {"protocol", NULL};
1998 PySSLContext *self;
1999 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002000 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002001 SSL_CTX *ctx = NULL;
2002
2003 if (!PyArg_ParseTupleAndKeywords(
2004 args, kwds, "i:_SSLContext", kwlist,
2005 &proto_version))
2006 return NULL;
2007
2008 PySSL_BEGIN_ALLOW_THREADS
2009 if (proto_version == PY_SSL_VERSION_TLS1)
2010 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002011#if HAVE_TLSv1_2
2012 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2013 ctx = SSL_CTX_new(TLSv1_1_method());
2014 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2015 ctx = SSL_CTX_new(TLSv1_2_method());
2016#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002017 else if (proto_version == PY_SSL_VERSION_SSL3)
2018 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002019#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002020 else if (proto_version == PY_SSL_VERSION_SSL2)
2021 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002022#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002023 else if (proto_version == PY_SSL_VERSION_SSL23)
2024 ctx = SSL_CTX_new(SSLv23_method());
2025 else
2026 proto_version = -1;
2027 PySSL_END_ALLOW_THREADS
2028
2029 if (proto_version == -1) {
2030 PyErr_SetString(PyExc_ValueError,
2031 "invalid protocol version");
2032 return NULL;
2033 }
2034 if (ctx == NULL) {
2035 PyErr_SetString(PySSLErrorObject,
2036 "failed to allocate SSL context");
2037 return NULL;
2038 }
2039
2040 assert(type != NULL && type->tp_alloc != NULL);
2041 self = (PySSLContext *) type->tp_alloc(type, 0);
2042 if (self == NULL) {
2043 SSL_CTX_free(ctx);
2044 return NULL;
2045 }
2046 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002047#ifdef OPENSSL_NPN_NEGOTIATED
2048 self->npn_protocols = NULL;
2049#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002050#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002051 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002052#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002053 /* Don't check host name by default */
2054 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002055 /* Defaults */
2056 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002057 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2058 if (proto_version != PY_SSL_VERSION_SSL2)
2059 options |= SSL_OP_NO_SSLv2;
2060 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002061
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002062#ifndef OPENSSL_NO_ECDH
2063 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2064 prime256v1 by default. This is Apache mod_ssl's initialization
2065 policy, so we should be safe. */
2066#if defined(SSL_CTX_set_ecdh_auto)
2067 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2068#else
2069 {
2070 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2071 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2072 EC_KEY_free(key);
2073 }
2074#endif
2075#endif
2076
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002077#define SID_CTX "Python"
2078 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2079 sizeof(SID_CTX));
2080#undef SID_CTX
2081
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082 return (PyObject *)self;
2083}
2084
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085static int
2086context_traverse(PySSLContext *self, visitproc visit, void *arg)
2087{
2088#ifndef OPENSSL_NO_TLSEXT
2089 Py_VISIT(self->set_hostname);
2090#endif
2091 return 0;
2092}
2093
2094static int
2095context_clear(PySSLContext *self)
2096{
2097#ifndef OPENSSL_NO_TLSEXT
2098 Py_CLEAR(self->set_hostname);
2099#endif
2100 return 0;
2101}
2102
Antoine Pitrou152efa22010-05-16 18:19:27 +00002103static void
2104context_dealloc(PySSLContext *self)
2105{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002106 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002107 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002108#ifdef OPENSSL_NPN_NEGOTIATED
2109 PyMem_Free(self->npn_protocols);
2110#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002111 Py_TYPE(self)->tp_free(self);
2112}
2113
2114static PyObject *
2115set_ciphers(PySSLContext *self, PyObject *args)
2116{
2117 int ret;
2118 const char *cipherlist;
2119
2120 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2121 return NULL;
2122 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2123 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002124 /* Clearing the error queue is necessary on some OpenSSL versions,
2125 otherwise the error will be reported again when another SSL call
2126 is done. */
2127 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002128 PyErr_SetString(PySSLErrorObject,
2129 "No cipher can be selected.");
2130 return NULL;
2131 }
2132 Py_RETURN_NONE;
2133}
2134
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002135#ifdef OPENSSL_NPN_NEGOTIATED
2136/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2137static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002138_advertiseNPN_cb(SSL *s,
2139 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002140 void *args)
2141{
2142 PySSLContext *ssl_ctx = (PySSLContext *) args;
2143
2144 if (ssl_ctx->npn_protocols == NULL) {
2145 *data = (unsigned char *) "";
2146 *len = 0;
2147 } else {
2148 *data = (unsigned char *) ssl_ctx->npn_protocols;
2149 *len = ssl_ctx->npn_protocols_len;
2150 }
2151
2152 return SSL_TLSEXT_ERR_OK;
2153}
2154/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2155static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002156_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002157 unsigned char **out, unsigned char *outlen,
2158 const unsigned char *server, unsigned int server_len,
2159 void *args)
2160{
2161 PySSLContext *ssl_ctx = (PySSLContext *) args;
2162
2163 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2164 int client_len;
2165
2166 if (client == NULL) {
2167 client = (unsigned char *) "";
2168 client_len = 0;
2169 } else {
2170 client_len = ssl_ctx->npn_protocols_len;
2171 }
2172
2173 SSL_select_next_proto(out, outlen,
2174 server, server_len,
2175 client, client_len);
2176
2177 return SSL_TLSEXT_ERR_OK;
2178}
2179#endif
2180
2181static PyObject *
2182_set_npn_protocols(PySSLContext *self, PyObject *args)
2183{
2184#ifdef OPENSSL_NPN_NEGOTIATED
2185 Py_buffer protos;
2186
2187 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2188 return NULL;
2189
Christian Heimes5cb31c92012-09-20 12:42:54 +02002190 if (self->npn_protocols != NULL) {
2191 PyMem_Free(self->npn_protocols);
2192 }
2193
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002194 self->npn_protocols = PyMem_Malloc(protos.len);
2195 if (self->npn_protocols == NULL) {
2196 PyBuffer_Release(&protos);
2197 return PyErr_NoMemory();
2198 }
2199 memcpy(self->npn_protocols, protos.buf, protos.len);
2200 self->npn_protocols_len = (int) protos.len;
2201
2202 /* set both server and client callbacks, because the context can
2203 * be used to create both types of sockets */
2204 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2205 _advertiseNPN_cb,
2206 self);
2207 SSL_CTX_set_next_proto_select_cb(self->ctx,
2208 _selectNPN_cb,
2209 self);
2210
2211 PyBuffer_Release(&protos);
2212 Py_RETURN_NONE;
2213#else
2214 PyErr_SetString(PyExc_NotImplementedError,
2215 "The NPN extension requires OpenSSL 1.0.1 or later.");
2216 return NULL;
2217#endif
2218}
2219
Antoine Pitrou152efa22010-05-16 18:19:27 +00002220static PyObject *
2221get_verify_mode(PySSLContext *self, void *c)
2222{
2223 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2224 case SSL_VERIFY_NONE:
2225 return PyLong_FromLong(PY_SSL_CERT_NONE);
2226 case SSL_VERIFY_PEER:
2227 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2228 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2229 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2230 }
2231 PyErr_SetString(PySSLErrorObject,
2232 "invalid return value from SSL_CTX_get_verify_mode");
2233 return NULL;
2234}
2235
2236static int
2237set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2238{
2239 int n, mode;
2240 if (!PyArg_Parse(arg, "i", &n))
2241 return -1;
2242 if (n == PY_SSL_CERT_NONE)
2243 mode = SSL_VERIFY_NONE;
2244 else if (n == PY_SSL_CERT_OPTIONAL)
2245 mode = SSL_VERIFY_PEER;
2246 else if (n == PY_SSL_CERT_REQUIRED)
2247 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2248 else {
2249 PyErr_SetString(PyExc_ValueError,
2250 "invalid value for verify_mode");
2251 return -1;
2252 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002253 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2254 PyErr_SetString(PyExc_ValueError,
2255 "Cannot set verify_mode to CERT_NONE when "
2256 "check_hostname is enabled.");
2257 return -1;
2258 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002259 SSL_CTX_set_verify(self->ctx, mode, NULL);
2260 return 0;
2261}
2262
Christian Heimes2427b502013-11-23 11:24:32 +01002263#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002264static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002265get_verify_flags(PySSLContext *self, void *c)
2266{
2267 X509_STORE *store;
2268 unsigned long flags;
2269
2270 store = SSL_CTX_get_cert_store(self->ctx);
2271 flags = X509_VERIFY_PARAM_get_flags(store->param);
2272 return PyLong_FromUnsignedLong(flags);
2273}
2274
2275static int
2276set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2277{
2278 X509_STORE *store;
2279 unsigned long new_flags, flags, set, clear;
2280
2281 if (!PyArg_Parse(arg, "k", &new_flags))
2282 return -1;
2283 store = SSL_CTX_get_cert_store(self->ctx);
2284 flags = X509_VERIFY_PARAM_get_flags(store->param);
2285 clear = flags & ~new_flags;
2286 set = ~flags & new_flags;
2287 if (clear) {
2288 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2289 _setSSLError(NULL, 0, __FILE__, __LINE__);
2290 return -1;
2291 }
2292 }
2293 if (set) {
2294 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2295 _setSSLError(NULL, 0, __FILE__, __LINE__);
2296 return -1;
2297 }
2298 }
2299 return 0;
2300}
Christian Heimes2427b502013-11-23 11:24:32 +01002301#endif
Christian Heimes22587792013-11-21 23:56:13 +01002302
2303static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002304get_options(PySSLContext *self, void *c)
2305{
2306 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2307}
2308
2309static int
2310set_options(PySSLContext *self, PyObject *arg, void *c)
2311{
2312 long new_opts, opts, set, clear;
2313 if (!PyArg_Parse(arg, "l", &new_opts))
2314 return -1;
2315 opts = SSL_CTX_get_options(self->ctx);
2316 clear = opts & ~new_opts;
2317 set = ~opts & new_opts;
2318 if (clear) {
2319#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2320 SSL_CTX_clear_options(self->ctx, clear);
2321#else
2322 PyErr_SetString(PyExc_ValueError,
2323 "can't clear options before OpenSSL 0.9.8m");
2324 return -1;
2325#endif
2326 }
2327 if (set)
2328 SSL_CTX_set_options(self->ctx, set);
2329 return 0;
2330}
2331
Christian Heimes1aa9a752013-12-02 02:41:19 +01002332static PyObject *
2333get_check_hostname(PySSLContext *self, void *c)
2334{
2335 return PyBool_FromLong(self->check_hostname);
2336}
2337
2338static int
2339set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2340{
2341 int check_hostname;
2342 if (!PyArg_Parse(arg, "p", &check_hostname))
2343 return -1;
2344 if (check_hostname &&
2345 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2346 PyErr_SetString(PyExc_ValueError,
2347 "check_hostname needs a SSL context with either "
2348 "CERT_OPTIONAL or CERT_REQUIRED");
2349 return -1;
2350 }
2351 self->check_hostname = check_hostname;
2352 return 0;
2353}
2354
2355
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002356typedef struct {
2357 PyThreadState *thread_state;
2358 PyObject *callable;
2359 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002360 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002361 int error;
2362} _PySSLPasswordInfo;
2363
2364static int
2365_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2366 const char *bad_type_error)
2367{
2368 /* Set the password and size fields of a _PySSLPasswordInfo struct
2369 from a unicode, bytes, or byte array object.
2370 The password field will be dynamically allocated and must be freed
2371 by the caller */
2372 PyObject *password_bytes = NULL;
2373 const char *data = NULL;
2374 Py_ssize_t size;
2375
2376 if (PyUnicode_Check(password)) {
2377 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2378 if (!password_bytes) {
2379 goto error;
2380 }
2381 data = PyBytes_AS_STRING(password_bytes);
2382 size = PyBytes_GET_SIZE(password_bytes);
2383 } else if (PyBytes_Check(password)) {
2384 data = PyBytes_AS_STRING(password);
2385 size = PyBytes_GET_SIZE(password);
2386 } else if (PyByteArray_Check(password)) {
2387 data = PyByteArray_AS_STRING(password);
2388 size = PyByteArray_GET_SIZE(password);
2389 } else {
2390 PyErr_SetString(PyExc_TypeError, bad_type_error);
2391 goto error;
2392 }
2393
Victor Stinner9ee02032013-06-23 15:08:23 +02002394 if (size > (Py_ssize_t)INT_MAX) {
2395 PyErr_Format(PyExc_ValueError,
2396 "password cannot be longer than %d bytes", INT_MAX);
2397 goto error;
2398 }
2399
Victor Stinner11ebff22013-07-07 17:07:52 +02002400 PyMem_Free(pw_info->password);
2401 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002402 if (!pw_info->password) {
2403 PyErr_SetString(PyExc_MemoryError,
2404 "unable to allocate password buffer");
2405 goto error;
2406 }
2407 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002408 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002409
2410 Py_XDECREF(password_bytes);
2411 return 1;
2412
2413error:
2414 Py_XDECREF(password_bytes);
2415 return 0;
2416}
2417
2418static int
2419_password_callback(char *buf, int size, int rwflag, void *userdata)
2420{
2421 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2422 PyObject *fn_ret = NULL;
2423
2424 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2425
2426 if (pw_info->callable) {
2427 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2428 if (!fn_ret) {
2429 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2430 core python API, so we could use it to add a frame here */
2431 goto error;
2432 }
2433
2434 if (!_pwinfo_set(pw_info, fn_ret,
2435 "password callback must return a string")) {
2436 goto error;
2437 }
2438 Py_CLEAR(fn_ret);
2439 }
2440
2441 if (pw_info->size > size) {
2442 PyErr_Format(PyExc_ValueError,
2443 "password cannot be longer than %d bytes", size);
2444 goto error;
2445 }
2446
2447 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2448 memcpy(buf, pw_info->password, pw_info->size);
2449 return pw_info->size;
2450
2451error:
2452 Py_XDECREF(fn_ret);
2453 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2454 pw_info->error = 1;
2455 return -1;
2456}
2457
Antoine Pitroub5218772010-05-21 09:56:06 +00002458static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002459load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2460{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002461 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2462 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002463 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002464 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2465 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2466 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002467 int r;
2468
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002469 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002470 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002471 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002472 "O|OO:load_cert_chain", kwlist,
2473 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002474 return NULL;
2475 if (keyfile == Py_None)
2476 keyfile = NULL;
2477 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2478 PyErr_SetString(PyExc_TypeError,
2479 "certfile should be a valid filesystem path");
2480 return NULL;
2481 }
2482 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2483 PyErr_SetString(PyExc_TypeError,
2484 "keyfile should be a valid filesystem path");
2485 goto error;
2486 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002487 if (password && password != Py_None) {
2488 if (PyCallable_Check(password)) {
2489 pw_info.callable = password;
2490 } else if (!_pwinfo_set(&pw_info, password,
2491 "password should be a string or callable")) {
2492 goto error;
2493 }
2494 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2495 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2496 }
2497 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002498 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2499 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002500 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002501 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002502 if (pw_info.error) {
2503 ERR_clear_error();
2504 /* the password callback has already set the error information */
2505 }
2506 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002507 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002508 PyErr_SetFromErrno(PyExc_IOError);
2509 }
2510 else {
2511 _setSSLError(NULL, 0, __FILE__, __LINE__);
2512 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002513 goto error;
2514 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002515 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002516 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002517 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2518 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002519 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2520 Py_CLEAR(keyfile_bytes);
2521 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002522 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002523 if (pw_info.error) {
2524 ERR_clear_error();
2525 /* the password callback has already set the error information */
2526 }
2527 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002528 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002529 PyErr_SetFromErrno(PyExc_IOError);
2530 }
2531 else {
2532 _setSSLError(NULL, 0, __FILE__, __LINE__);
2533 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002534 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002535 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002536 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002537 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002538 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002539 if (r != 1) {
2540 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002541 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002542 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002543 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2544 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002545 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002546 Py_RETURN_NONE;
2547
2548error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002549 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2550 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002551 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002552 Py_XDECREF(keyfile_bytes);
2553 Py_XDECREF(certfile_bytes);
2554 return NULL;
2555}
2556
Christian Heimesefff7062013-11-21 03:35:02 +01002557/* internal helper function, returns -1 on error
2558 */
2559static int
2560_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2561 int filetype)
2562{
2563 BIO *biobuf = NULL;
2564 X509_STORE *store;
2565 int retval = 0, err, loaded = 0;
2566
2567 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2568
2569 if (len <= 0) {
2570 PyErr_SetString(PyExc_ValueError,
2571 "Empty certificate data");
2572 return -1;
2573 } else if (len > INT_MAX) {
2574 PyErr_SetString(PyExc_OverflowError,
2575 "Certificate data is too long.");
2576 return -1;
2577 }
2578
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002579 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002580 if (biobuf == NULL) {
2581 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2582 return -1;
2583 }
2584
2585 store = SSL_CTX_get_cert_store(self->ctx);
2586 assert(store != NULL);
2587
2588 while (1) {
2589 X509 *cert = NULL;
2590 int r;
2591
2592 if (filetype == SSL_FILETYPE_ASN1) {
2593 cert = d2i_X509_bio(biobuf, NULL);
2594 } else {
2595 cert = PEM_read_bio_X509(biobuf, NULL,
2596 self->ctx->default_passwd_callback,
2597 self->ctx->default_passwd_callback_userdata);
2598 }
2599 if (cert == NULL) {
2600 break;
2601 }
2602 r = X509_STORE_add_cert(store, cert);
2603 X509_free(cert);
2604 if (!r) {
2605 err = ERR_peek_last_error();
2606 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2607 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2608 /* cert already in hash table, not an error */
2609 ERR_clear_error();
2610 } else {
2611 break;
2612 }
2613 }
2614 loaded++;
2615 }
2616
2617 err = ERR_peek_last_error();
2618 if ((filetype == SSL_FILETYPE_ASN1) &&
2619 (loaded > 0) &&
2620 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2621 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2622 /* EOF ASN1 file, not an error */
2623 ERR_clear_error();
2624 retval = 0;
2625 } else if ((filetype == SSL_FILETYPE_PEM) &&
2626 (loaded > 0) &&
2627 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2628 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2629 /* EOF PEM file, not an error */
2630 ERR_clear_error();
2631 retval = 0;
2632 } else {
2633 _setSSLError(NULL, 0, __FILE__, __LINE__);
2634 retval = -1;
2635 }
2636
2637 BIO_free(biobuf);
2638 return retval;
2639}
2640
2641
Antoine Pitrou152efa22010-05-16 18:19:27 +00002642static PyObject *
2643load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2644{
Christian Heimesefff7062013-11-21 03:35:02 +01002645 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2646 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002647 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2648 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002649 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002650
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002651 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002652 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002653 "|OOO:load_verify_locations", kwlist,
2654 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002656
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657 if (cafile == Py_None)
2658 cafile = NULL;
2659 if (capath == Py_None)
2660 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002661 if (cadata == Py_None)
2662 cadata = NULL;
2663
2664 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002665 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002666 "cafile, capath and cadata cannot be all omitted");
2667 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668 }
2669 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2670 PyErr_SetString(PyExc_TypeError,
2671 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002672 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673 }
2674 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002675 PyErr_SetString(PyExc_TypeError,
2676 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002677 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002678 }
Christian Heimesefff7062013-11-21 03:35:02 +01002679
2680 /* validata cadata type and load cadata */
2681 if (cadata) {
2682 Py_buffer buf;
2683 PyObject *cadata_ascii = NULL;
2684
2685 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2686 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2687 PyBuffer_Release(&buf);
2688 PyErr_SetString(PyExc_TypeError,
2689 "cadata should be a contiguous buffer with "
2690 "a single dimension");
2691 goto error;
2692 }
2693 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2694 PyBuffer_Release(&buf);
2695 if (r == -1) {
2696 goto error;
2697 }
2698 } else {
2699 PyErr_Clear();
2700 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2701 if (cadata_ascii == NULL) {
2702 PyErr_SetString(PyExc_TypeError,
2703 "cadata should be a ASCII string or a "
2704 "bytes-like object");
2705 goto error;
2706 }
2707 r = _add_ca_certs(self,
2708 PyBytes_AS_STRING(cadata_ascii),
2709 PyBytes_GET_SIZE(cadata_ascii),
2710 SSL_FILETYPE_PEM);
2711 Py_DECREF(cadata_ascii);
2712 if (r == -1) {
2713 goto error;
2714 }
2715 }
2716 }
2717
2718 /* load cafile or capath */
2719 if (cafile || capath) {
2720 if (cafile)
2721 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2722 if (capath)
2723 capath_buf = PyBytes_AS_STRING(capath_bytes);
2724 PySSL_BEGIN_ALLOW_THREADS
2725 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2726 PySSL_END_ALLOW_THREADS
2727 if (r != 1) {
2728 ok = 0;
2729 if (errno != 0) {
2730 ERR_clear_error();
2731 PyErr_SetFromErrno(PyExc_IOError);
2732 }
2733 else {
2734 _setSSLError(NULL, 0, __FILE__, __LINE__);
2735 }
2736 goto error;
2737 }
2738 }
2739 goto end;
2740
2741 error:
2742 ok = 0;
2743 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002744 Py_XDECREF(cafile_bytes);
2745 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002746 if (ok) {
2747 Py_RETURN_NONE;
2748 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002749 return NULL;
2750 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002751}
2752
2753static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002754load_dh_params(PySSLContext *self, PyObject *filepath)
2755{
2756 FILE *f;
2757 DH *dh;
2758
Victor Stinnerdaf45552013-08-28 00:53:59 +02002759 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002760 if (f == NULL) {
2761 if (!PyErr_Occurred())
2762 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2763 return NULL;
2764 }
2765 errno = 0;
2766 PySSL_BEGIN_ALLOW_THREADS
2767 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002768 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002769 PySSL_END_ALLOW_THREADS
2770 if (dh == NULL) {
2771 if (errno != 0) {
2772 ERR_clear_error();
2773 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2774 }
2775 else {
2776 _setSSLError(NULL, 0, __FILE__, __LINE__);
2777 }
2778 return NULL;
2779 }
2780 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2781 _setSSLError(NULL, 0, __FILE__, __LINE__);
2782 DH_free(dh);
2783 Py_RETURN_NONE;
2784}
2785
2786static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002787context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2788{
Antoine Pitroud5323212010-10-22 18:19:07 +00002789 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790 PySocketSockObject *sock;
2791 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002792 char *hostname = NULL;
2793 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002794
Antoine Pitroud5323212010-10-22 18:19:07 +00002795 /* server_hostname is either None (or absent), or to be encoded
2796 using the idna encoding. */
2797 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002799 &sock, &server_side,
2800 Py_TYPE(Py_None), &hostname_obj)) {
2801 PyErr_Clear();
2802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2803 PySocketModule.Sock_Type,
2804 &sock, &server_side,
2805 "idna", &hostname))
2806 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002807#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002808 PyMem_Free(hostname);
2809 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2810 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002811 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002812#endif
2813 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002814
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002815 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002816 hostname);
2817 if (hostname != NULL)
2818 PyMem_Free(hostname);
2819 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820}
2821
Antoine Pitroub0182c82010-10-12 20:09:02 +00002822static PyObject *
2823session_stats(PySSLContext *self, PyObject *unused)
2824{
2825 int r;
2826 PyObject *value, *stats = PyDict_New();
2827 if (!stats)
2828 return NULL;
2829
2830#define ADD_STATS(SSL_NAME, KEY_NAME) \
2831 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2832 if (value == NULL) \
2833 goto error; \
2834 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2835 Py_DECREF(value); \
2836 if (r < 0) \
2837 goto error;
2838
2839 ADD_STATS(number, "number");
2840 ADD_STATS(connect, "connect");
2841 ADD_STATS(connect_good, "connect_good");
2842 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2843 ADD_STATS(accept, "accept");
2844 ADD_STATS(accept_good, "accept_good");
2845 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2846 ADD_STATS(accept, "accept");
2847 ADD_STATS(hits, "hits");
2848 ADD_STATS(misses, "misses");
2849 ADD_STATS(timeouts, "timeouts");
2850 ADD_STATS(cache_full, "cache_full");
2851
2852#undef ADD_STATS
2853
2854 return stats;
2855
2856error:
2857 Py_DECREF(stats);
2858 return NULL;
2859}
2860
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002861static PyObject *
2862set_default_verify_paths(PySSLContext *self, PyObject *unused)
2863{
2864 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2865 _setSSLError(NULL, 0, __FILE__, __LINE__);
2866 return NULL;
2867 }
2868 Py_RETURN_NONE;
2869}
2870
Antoine Pitrou501da612011-12-21 09:27:41 +01002871#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002872static PyObject *
2873set_ecdh_curve(PySSLContext *self, PyObject *name)
2874{
2875 PyObject *name_bytes;
2876 int nid;
2877 EC_KEY *key;
2878
2879 if (!PyUnicode_FSConverter(name, &name_bytes))
2880 return NULL;
2881 assert(PyBytes_Check(name_bytes));
2882 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2883 Py_DECREF(name_bytes);
2884 if (nid == 0) {
2885 PyErr_Format(PyExc_ValueError,
2886 "unknown elliptic curve name %R", name);
2887 return NULL;
2888 }
2889 key = EC_KEY_new_by_curve_name(nid);
2890 if (key == NULL) {
2891 _setSSLError(NULL, 0, __FILE__, __LINE__);
2892 return NULL;
2893 }
2894 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2895 EC_KEY_free(key);
2896 Py_RETURN_NONE;
2897}
Antoine Pitrou501da612011-12-21 09:27:41 +01002898#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002899
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002900#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002901static int
2902_servername_callback(SSL *s, int *al, void *args)
2903{
2904 int ret;
2905 PySSLContext *ssl_ctx = (PySSLContext *) args;
2906 PySSLSocket *ssl;
2907 PyObject *servername_o;
2908 PyObject *servername_idna;
2909 PyObject *result;
2910 /* The high-level ssl.SSLSocket object */
2911 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002912 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002913#ifdef WITH_THREAD
2914 PyGILState_STATE gstate = PyGILState_Ensure();
2915#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002916
2917 if (ssl_ctx->set_hostname == NULL) {
2918 /* remove race condition in this the call back while if removing the
2919 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002920#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002921 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002922#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002923 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002924 }
2925
2926 ssl = SSL_get_app_data(s);
2927 assert(PySSLSocket_Check(ssl));
2928 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2929 Py_INCREF(ssl_socket);
2930 if (ssl_socket == Py_None) {
2931 goto error;
2932 }
Victor Stinner7e001512013-06-25 00:44:31 +02002933
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002934 if (servername == NULL) {
2935 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2936 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002937 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002938 else {
2939 servername_o = PyBytes_FromString(servername);
2940 if (servername_o == NULL) {
2941 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2942 goto error;
2943 }
2944 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2945 if (servername_idna == NULL) {
2946 PyErr_WriteUnraisable(servername_o);
2947 Py_DECREF(servername_o);
2948 goto error;
2949 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002950 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002951 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2952 servername_idna, ssl_ctx, NULL);
2953 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002954 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002955 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002956
2957 if (result == NULL) {
2958 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2959 *al = SSL_AD_HANDSHAKE_FAILURE;
2960 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2961 }
2962 else {
2963 if (result != Py_None) {
2964 *al = (int) PyLong_AsLong(result);
2965 if (PyErr_Occurred()) {
2966 PyErr_WriteUnraisable(result);
2967 *al = SSL_AD_INTERNAL_ERROR;
2968 }
2969 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2970 }
2971 else {
2972 ret = SSL_TLSEXT_ERR_OK;
2973 }
2974 Py_DECREF(result);
2975 }
2976
Stefan Krah20d60802013-01-17 17:07:17 +01002977#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002978 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002979#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002980 return ret;
2981
2982error:
2983 Py_DECREF(ssl_socket);
2984 *al = SSL_AD_INTERNAL_ERROR;
2985 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002986#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002987 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002988#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002989 return ret;
2990}
Antoine Pitroua5963382013-03-30 16:39:00 +01002991#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002992
2993PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2994"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002995\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002996This sets a callback that will be called when a server name is provided by\n\
2997the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002998\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002999If the argument is None then the callback is disabled. The method is called\n\
3000with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003001See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003002
3003static PyObject *
3004set_servername_callback(PySSLContext *self, PyObject *args)
3005{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003006#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003007 PyObject *cb;
3008
3009 if (!PyArg_ParseTuple(args, "O", &cb))
3010 return NULL;
3011
3012 Py_CLEAR(self->set_hostname);
3013 if (cb == Py_None) {
3014 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3015 }
3016 else {
3017 if (!PyCallable_Check(cb)) {
3018 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3019 PyErr_SetString(PyExc_TypeError,
3020 "not a callable object");
3021 return NULL;
3022 }
3023 Py_INCREF(cb);
3024 self->set_hostname = cb;
3025 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3026 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3027 }
3028 Py_RETURN_NONE;
3029#else
3030 PyErr_SetString(PyExc_NotImplementedError,
3031 "The TLS extension servername callback, "
3032 "SSL_CTX_set_tlsext_servername_callback, "
3033 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003034 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003035#endif
3036}
3037
Christian Heimes9a5395a2013-06-17 15:44:12 +02003038PyDoc_STRVAR(PySSL_get_stats_doc,
3039"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3040\n\
3041Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3042CA extension and certificate revocation lists inside the context's cert\n\
3043store.\n\
3044NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3045been used at least once.");
3046
3047static PyObject *
3048cert_store_stats(PySSLContext *self)
3049{
3050 X509_STORE *store;
3051 X509_OBJECT *obj;
3052 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3053
3054 store = SSL_CTX_get_cert_store(self->ctx);
3055 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3056 obj = sk_X509_OBJECT_value(store->objs, i);
3057 switch (obj->type) {
3058 case X509_LU_X509:
3059 x509++;
3060 if (X509_check_ca(obj->data.x509)) {
3061 ca++;
3062 }
3063 break;
3064 case X509_LU_CRL:
3065 crl++;
3066 break;
3067 case X509_LU_PKEY:
3068 pkey++;
3069 break;
3070 default:
3071 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3072 * As far as I can tell they are internal states and never
3073 * stored in a cert store */
3074 break;
3075 }
3076 }
3077 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3078 "x509_ca", ca);
3079}
3080
3081PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003082"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003083\n\
3084Returns a list of dicts with information of loaded CA certs. If the\n\
3085optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3086NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3087been used at least once.");
3088
3089static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003090get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003091{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003092 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003093 X509_STORE *store;
3094 PyObject *ci = NULL, *rlist = NULL;
3095 int i;
3096 int binary_mode = 0;
3097
Christian Heimesf22e8e52013-11-22 02:22:51 +01003098 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3099 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003100 return NULL;
3101 }
3102
3103 if ((rlist = PyList_New(0)) == NULL) {
3104 return NULL;
3105 }
3106
3107 store = SSL_CTX_get_cert_store(self->ctx);
3108 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3109 X509_OBJECT *obj;
3110 X509 *cert;
3111
3112 obj = sk_X509_OBJECT_value(store->objs, i);
3113 if (obj->type != X509_LU_X509) {
3114 /* not a x509 cert */
3115 continue;
3116 }
3117 /* CA for any purpose */
3118 cert = obj->data.x509;
3119 if (!X509_check_ca(cert)) {
3120 continue;
3121 }
3122 if (binary_mode) {
3123 ci = _certificate_to_der(cert);
3124 } else {
3125 ci = _decode_certificate(cert);
3126 }
3127 if (ci == NULL) {
3128 goto error;
3129 }
3130 if (PyList_Append(rlist, ci) == -1) {
3131 goto error;
3132 }
3133 Py_CLEAR(ci);
3134 }
3135 return rlist;
3136
3137 error:
3138 Py_XDECREF(ci);
3139 Py_XDECREF(rlist);
3140 return NULL;
3141}
3142
3143
Antoine Pitrou152efa22010-05-16 18:19:27 +00003144static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003145 {"check_hostname", (getter) get_check_hostname,
3146 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003147 {"options", (getter) get_options,
3148 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003149#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003150 {"verify_flags", (getter) get_verify_flags,
3151 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003152#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003153 {"verify_mode", (getter) get_verify_mode,
3154 (setter) set_verify_mode, NULL},
3155 {NULL}, /* sentinel */
3156};
3157
3158static struct PyMethodDef context_methods[] = {
3159 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3160 METH_VARARGS | METH_KEYWORDS, NULL},
3161 {"set_ciphers", (PyCFunction) set_ciphers,
3162 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003163 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3164 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003165 {"load_cert_chain", (PyCFunction) load_cert_chain,
3166 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003167 {"load_dh_params", (PyCFunction) load_dh_params,
3168 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003169 {"load_verify_locations", (PyCFunction) load_verify_locations,
3170 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003171 {"session_stats", (PyCFunction) session_stats,
3172 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003173 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3174 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003175#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003176 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3177 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003178#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003179 {"set_servername_callback", (PyCFunction) set_servername_callback,
3180 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003181 {"cert_store_stats", (PyCFunction) cert_store_stats,
3182 METH_NOARGS, PySSL_get_stats_doc},
3183 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003184 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003185 {NULL, NULL} /* sentinel */
3186};
3187
3188static PyTypeObject PySSLContext_Type = {
3189 PyVarObject_HEAD_INIT(NULL, 0)
3190 "_ssl._SSLContext", /*tp_name*/
3191 sizeof(PySSLContext), /*tp_basicsize*/
3192 0, /*tp_itemsize*/
3193 (destructor)context_dealloc, /*tp_dealloc*/
3194 0, /*tp_print*/
3195 0, /*tp_getattr*/
3196 0, /*tp_setattr*/
3197 0, /*tp_reserved*/
3198 0, /*tp_repr*/
3199 0, /*tp_as_number*/
3200 0, /*tp_as_sequence*/
3201 0, /*tp_as_mapping*/
3202 0, /*tp_hash*/
3203 0, /*tp_call*/
3204 0, /*tp_str*/
3205 0, /*tp_getattro*/
3206 0, /*tp_setattro*/
3207 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003208 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003209 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003210 (traverseproc) context_traverse, /*tp_traverse*/
3211 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003212 0, /*tp_richcompare*/
3213 0, /*tp_weaklistoffset*/
3214 0, /*tp_iter*/
3215 0, /*tp_iternext*/
3216 context_methods, /*tp_methods*/
3217 0, /*tp_members*/
3218 context_getsetlist, /*tp_getset*/
3219 0, /*tp_base*/
3220 0, /*tp_dict*/
3221 0, /*tp_descr_get*/
3222 0, /*tp_descr_set*/
3223 0, /*tp_dictoffset*/
3224 0, /*tp_init*/
3225 0, /*tp_alloc*/
3226 context_new, /*tp_new*/
3227};
3228
3229
3230
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003231#ifdef HAVE_OPENSSL_RAND
3232
3233/* helper routines for seeding the SSL PRNG */
3234static PyObject *
3235PySSL_RAND_add(PyObject *self, PyObject *args)
3236{
3237 char *buf;
3238 int len;
3239 double entropy;
3240
3241 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003242 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003243 RAND_add(buf, len, entropy);
3244 Py_INCREF(Py_None);
3245 return Py_None;
3246}
3247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003248PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003249"RAND_add(string, entropy)\n\
3250\n\
3251Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003252bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003253
3254static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003255PySSL_RAND(int len, int pseudo)
3256{
3257 int ok;
3258 PyObject *bytes;
3259 unsigned long err;
3260 const char *errstr;
3261 PyObject *v;
3262
Victor Stinner1e81a392013-12-19 16:47:04 +01003263 if (len < 0) {
3264 PyErr_SetString(PyExc_ValueError, "num must be positive");
3265 return NULL;
3266 }
3267
Victor Stinner99c8b162011-05-24 12:05:19 +02003268 bytes = PyBytes_FromStringAndSize(NULL, len);
3269 if (bytes == NULL)
3270 return NULL;
3271 if (pseudo) {
3272 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3273 if (ok == 0 || ok == 1)
3274 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3275 }
3276 else {
3277 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3278 if (ok == 1)
3279 return bytes;
3280 }
3281 Py_DECREF(bytes);
3282
3283 err = ERR_get_error();
3284 errstr = ERR_reason_error_string(err);
3285 v = Py_BuildValue("(ks)", err, errstr);
3286 if (v != NULL) {
3287 PyErr_SetObject(PySSLErrorObject, v);
3288 Py_DECREF(v);
3289 }
3290 return NULL;
3291}
3292
3293static PyObject *
3294PySSL_RAND_bytes(PyObject *self, PyObject *args)
3295{
3296 int len;
3297 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3298 return NULL;
3299 return PySSL_RAND(len, 0);
3300}
3301
3302PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3303"RAND_bytes(n) -> bytes\n\
3304\n\
3305Generate n cryptographically strong pseudo-random bytes.");
3306
3307static PyObject *
3308PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3309{
3310 int len;
3311 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3312 return NULL;
3313 return PySSL_RAND(len, 1);
3314}
3315
3316PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3317"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3318\n\
3319Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3320generated are cryptographically strong.");
3321
3322static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003323PySSL_RAND_status(PyObject *self)
3324{
Christian Heimes217cfd12007-12-02 14:31:20 +00003325 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003326}
3327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003328PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003329"RAND_status() -> 0 or 1\n\
3330\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003331Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3332It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3333using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003334
3335static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003336PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003337{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003338 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003339 int bytes;
3340
Jesus Ceac8754a12012-09-11 02:00:58 +02003341 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003342 PyUnicode_FSConverter, &path))
3343 return NULL;
3344
3345 bytes = RAND_egd(PyBytes_AsString(path));
3346 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003347 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003348 PyErr_SetString(PySSLErrorObject,
3349 "EGD connection failed or EGD did not return "
3350 "enough data to seed the PRNG");
3351 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003352 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003353 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003354}
3355
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003356PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003357"RAND_egd(path) -> bytes\n\
3358\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003359Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3360Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003361fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003362
Christian Heimesf77b4b22013-08-21 13:26:05 +02003363#endif /* HAVE_OPENSSL_RAND */
3364
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003365
Christian Heimes6d7ad132013-06-09 18:02:55 +02003366PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3367"get_default_verify_paths() -> tuple\n\
3368\n\
3369Return search paths and environment vars that are used by SSLContext's\n\
3370set_default_verify_paths() to load default CAs. The values are\n\
3371'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3372
3373static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003374PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003375{
3376 PyObject *ofile_env = NULL;
3377 PyObject *ofile = NULL;
3378 PyObject *odir_env = NULL;
3379 PyObject *odir = NULL;
3380
3381#define convert(info, target) { \
3382 const char *tmp = (info); \
3383 target = NULL; \
3384 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3385 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3386 target = PyBytes_FromString(tmp); } \
3387 if (!target) goto error; \
3388 } while(0)
3389
3390 convert(X509_get_default_cert_file_env(), ofile_env);
3391 convert(X509_get_default_cert_file(), ofile);
3392 convert(X509_get_default_cert_dir_env(), odir_env);
3393 convert(X509_get_default_cert_dir(), odir);
3394#undef convert
3395
Christian Heimes200bb1b2013-06-14 15:14:29 +02003396 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003397
3398 error:
3399 Py_XDECREF(ofile_env);
3400 Py_XDECREF(ofile);
3401 Py_XDECREF(odir_env);
3402 Py_XDECREF(odir);
3403 return NULL;
3404}
3405
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003406static PyObject*
3407asn1obj2py(ASN1_OBJECT *obj)
3408{
3409 int nid;
3410 const char *ln, *sn;
3411 char buf[100];
3412 int buflen;
3413
3414 nid = OBJ_obj2nid(obj);
3415 if (nid == NID_undef) {
3416 PyErr_Format(PyExc_ValueError, "Unknown object");
3417 return NULL;
3418 }
3419 sn = OBJ_nid2sn(nid);
3420 ln = OBJ_nid2ln(nid);
3421 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3422 if (buflen < 0) {
3423 _setSSLError(NULL, 0, __FILE__, __LINE__);
3424 return NULL;
3425 }
3426 if (buflen) {
3427 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3428 } else {
3429 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3430 }
3431}
3432
3433PyDoc_STRVAR(PySSL_txt2obj_doc,
3434"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3435\n\
3436Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3437objects are looked up by OID. With name=True short and long name are also\n\
3438matched.");
3439
3440static PyObject*
3441PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3442{
3443 char *kwlist[] = {"txt", "name", NULL};
3444 PyObject *result = NULL;
3445 char *txt;
3446 int name = 0;
3447 ASN1_OBJECT *obj;
3448
3449 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3450 kwlist, &txt, &name)) {
3451 return NULL;
3452 }
3453 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3454 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003455 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003456 return NULL;
3457 }
3458 result = asn1obj2py(obj);
3459 ASN1_OBJECT_free(obj);
3460 return result;
3461}
3462
3463PyDoc_STRVAR(PySSL_nid2obj_doc,
3464"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3465\n\
3466Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3467
3468static PyObject*
3469PySSL_nid2obj(PyObject *self, PyObject *args)
3470{
3471 PyObject *result = NULL;
3472 int nid;
3473 ASN1_OBJECT *obj;
3474
3475 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3476 return NULL;
3477 }
3478 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003479 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003480 return NULL;
3481 }
3482 obj = OBJ_nid2obj(nid);
3483 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003484 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003485 return NULL;
3486 }
3487 result = asn1obj2py(obj);
3488 ASN1_OBJECT_free(obj);
3489 return result;
3490}
3491
Christian Heimes46bebee2013-06-09 19:03:31 +02003492#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003493
3494static PyObject*
3495certEncodingType(DWORD encodingType)
3496{
3497 static PyObject *x509_asn = NULL;
3498 static PyObject *pkcs_7_asn = NULL;
3499
3500 if (x509_asn == NULL) {
3501 x509_asn = PyUnicode_InternFromString("x509_asn");
3502 if (x509_asn == NULL)
3503 return NULL;
3504 }
3505 if (pkcs_7_asn == NULL) {
3506 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3507 if (pkcs_7_asn == NULL)
3508 return NULL;
3509 }
3510 switch(encodingType) {
3511 case X509_ASN_ENCODING:
3512 Py_INCREF(x509_asn);
3513 return x509_asn;
3514 case PKCS_7_ASN_ENCODING:
3515 Py_INCREF(pkcs_7_asn);
3516 return pkcs_7_asn;
3517 default:
3518 return PyLong_FromLong(encodingType);
3519 }
3520}
3521
3522static PyObject*
3523parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3524{
3525 CERT_ENHKEY_USAGE *usage;
3526 DWORD size, error, i;
3527 PyObject *retval;
3528
3529 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3530 error = GetLastError();
3531 if (error == CRYPT_E_NOT_FOUND) {
3532 Py_RETURN_TRUE;
3533 }
3534 return PyErr_SetFromWindowsErr(error);
3535 }
3536
3537 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3538 if (usage == NULL) {
3539 return PyErr_NoMemory();
3540 }
3541
3542 /* Now get the actual enhanced usage property */
3543 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3544 PyMem_Free(usage);
3545 error = GetLastError();
3546 if (error == CRYPT_E_NOT_FOUND) {
3547 Py_RETURN_TRUE;
3548 }
3549 return PyErr_SetFromWindowsErr(error);
3550 }
3551 retval = PySet_New(NULL);
3552 if (retval == NULL) {
3553 goto error;
3554 }
3555 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3556 if (usage->rgpszUsageIdentifier[i]) {
3557 PyObject *oid;
3558 int err;
3559 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3560 if (oid == NULL) {
3561 Py_CLEAR(retval);
3562 goto error;
3563 }
3564 err = PySet_Add(retval, oid);
3565 Py_DECREF(oid);
3566 if (err == -1) {
3567 Py_CLEAR(retval);
3568 goto error;
3569 }
3570 }
3571 }
3572 error:
3573 PyMem_Free(usage);
3574 return retval;
3575}
3576
3577PyDoc_STRVAR(PySSL_enum_certificates_doc,
3578"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003579\n\
3580Retrieve certificates from Windows' cert store. store_name may be one of\n\
3581'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003582The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003583encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003584PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3585boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003586
Christian Heimes46bebee2013-06-09 19:03:31 +02003587static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003588PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003589{
Christian Heimes44109d72013-11-22 01:51:30 +01003590 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003591 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003592 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003593 PCCERT_CONTEXT pCertCtx = NULL;
3594 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003595 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003596
Christian Heimes44109d72013-11-22 01:51:30 +01003597 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3598 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003599 return NULL;
3600 }
Christian Heimes44109d72013-11-22 01:51:30 +01003601 result = PyList_New(0);
3602 if (result == NULL) {
3603 return NULL;
3604 }
3605 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3606 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003607 Py_DECREF(result);
3608 return PyErr_SetFromWindowsErr(GetLastError());
3609 }
3610
Christian Heimes44109d72013-11-22 01:51:30 +01003611 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3612 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3613 pCertCtx->cbCertEncoded);
3614 if (!cert) {
3615 Py_CLEAR(result);
3616 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003617 }
Christian Heimes44109d72013-11-22 01:51:30 +01003618 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3619 Py_CLEAR(result);
3620 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003621 }
Christian Heimes44109d72013-11-22 01:51:30 +01003622 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3623 if (keyusage == Py_True) {
3624 Py_DECREF(keyusage);
3625 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003626 }
Christian Heimes44109d72013-11-22 01:51:30 +01003627 if (keyusage == NULL) {
3628 Py_CLEAR(result);
3629 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003630 }
Christian Heimes44109d72013-11-22 01:51:30 +01003631 if ((tup = PyTuple_New(3)) == NULL) {
3632 Py_CLEAR(result);
3633 break;
3634 }
3635 PyTuple_SET_ITEM(tup, 0, cert);
3636 cert = NULL;
3637 PyTuple_SET_ITEM(tup, 1, enc);
3638 enc = NULL;
3639 PyTuple_SET_ITEM(tup, 2, keyusage);
3640 keyusage = NULL;
3641 if (PyList_Append(result, tup) < 0) {
3642 Py_CLEAR(result);
3643 break;
3644 }
3645 Py_CLEAR(tup);
3646 }
3647 if (pCertCtx) {
3648 /* loop ended with an error, need to clean up context manually */
3649 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003650 }
3651
3652 /* In error cases cert, enc and tup may not be NULL */
3653 Py_XDECREF(cert);
3654 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003655 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003656 Py_XDECREF(tup);
3657
3658 if (!CertCloseStore(hStore, 0)) {
3659 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003660 Py_XDECREF(result);
3661 return PyErr_SetFromWindowsErr(GetLastError());
3662 }
3663 return result;
3664}
3665
3666PyDoc_STRVAR(PySSL_enum_crls_doc,
3667"enum_crls(store_name) -> []\n\
3668\n\
3669Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3670'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3671The function returns a list of (bytes, encoding_type) tuples. The\n\
3672encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3673PKCS_7_ASN_ENCODING.");
3674
3675static PyObject *
3676PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3677{
3678 char *kwlist[] = {"store_name", NULL};
3679 char *store_name;
3680 HCERTSTORE hStore = NULL;
3681 PCCRL_CONTEXT pCrlCtx = NULL;
3682 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3683 PyObject *result = NULL;
3684
3685 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3686 kwlist, &store_name)) {
3687 return NULL;
3688 }
3689 result = PyList_New(0);
3690 if (result == NULL) {
3691 return NULL;
3692 }
3693 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3694 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003695 Py_DECREF(result);
3696 return PyErr_SetFromWindowsErr(GetLastError());
3697 }
Christian Heimes44109d72013-11-22 01:51:30 +01003698
3699 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3700 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3701 pCrlCtx->cbCrlEncoded);
3702 if (!crl) {
3703 Py_CLEAR(result);
3704 break;
3705 }
3706 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3707 Py_CLEAR(result);
3708 break;
3709 }
3710 if ((tup = PyTuple_New(2)) == NULL) {
3711 Py_CLEAR(result);
3712 break;
3713 }
3714 PyTuple_SET_ITEM(tup, 0, crl);
3715 crl = NULL;
3716 PyTuple_SET_ITEM(tup, 1, enc);
3717 enc = NULL;
3718
3719 if (PyList_Append(result, tup) < 0) {
3720 Py_CLEAR(result);
3721 break;
3722 }
3723 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003724 }
Christian Heimes44109d72013-11-22 01:51:30 +01003725 if (pCrlCtx) {
3726 /* loop ended with an error, need to clean up context manually */
3727 CertFreeCRLContext(pCrlCtx);
3728 }
3729
3730 /* In error cases cert, enc and tup may not be NULL */
3731 Py_XDECREF(crl);
3732 Py_XDECREF(enc);
3733 Py_XDECREF(tup);
3734
3735 if (!CertCloseStore(hStore, 0)) {
3736 /* This error case might shadow another exception.*/
3737 Py_XDECREF(result);
3738 return PyErr_SetFromWindowsErr(GetLastError());
3739 }
3740 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003741}
Christian Heimes44109d72013-11-22 01:51:30 +01003742
3743#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003744
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003745/* List of functions exported by this module. */
3746
3747static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003748 {"_test_decode_cert", PySSL_test_decode_certificate,
3749 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003750#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003751 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3752 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003753 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3754 PySSL_RAND_bytes_doc},
3755 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3756 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003757 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003758 PySSL_RAND_egd_doc},
3759 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3760 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003761#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003762 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003763 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003764#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003765 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3766 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3767 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3768 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003769#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003770 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3771 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3772 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3773 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003774 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003775};
3776
3777
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003778#ifdef WITH_THREAD
3779
3780/* an implementation of OpenSSL threading operations in terms
3781 of the Python C thread library */
3782
3783static PyThread_type_lock *_ssl_locks = NULL;
3784
Christian Heimes4d98ca92013-08-19 17:36:29 +02003785#if OPENSSL_VERSION_NUMBER >= 0x10000000
3786/* use new CRYPTO_THREADID API. */
3787static void
3788_ssl_threadid_callback(CRYPTO_THREADID *id)
3789{
3790 CRYPTO_THREADID_set_numeric(id,
3791 (unsigned long)PyThread_get_thread_ident());
3792}
3793#else
3794/* deprecated CRYPTO_set_id_callback() API. */
3795static unsigned long
3796_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003797 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003798}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003799#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003800
Bill Janssen6e027db2007-11-15 22:23:56 +00003801static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003802 (int mode, int n, const char *file, int line) {
3803 /* this function is needed to perform locking on shared data
3804 structures. (Note that OpenSSL uses a number of global data
3805 structures that will be implicitly shared whenever multiple
3806 threads use OpenSSL.) Multi-threaded applications will
3807 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003809 locking_function() must be able to handle up to
3810 CRYPTO_num_locks() different mutex locks. It sets the n-th
3811 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003813 file and line are the file number of the function setting the
3814 lock. They can be useful for debugging.
3815 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003817 if ((_ssl_locks == NULL) ||
3818 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3819 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003821 if (mode & CRYPTO_LOCK) {
3822 PyThread_acquire_lock(_ssl_locks[n], 1);
3823 } else {
3824 PyThread_release_lock(_ssl_locks[n]);
3825 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003826}
3827
3828static int _setup_ssl_threads(void) {
3829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003830 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003832 if (_ssl_locks == NULL) {
3833 _ssl_locks_count = CRYPTO_num_locks();
3834 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003835 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003836 if (_ssl_locks == NULL)
3837 return 0;
3838 memset(_ssl_locks, 0,
3839 sizeof(PyThread_type_lock) * _ssl_locks_count);
3840 for (i = 0; i < _ssl_locks_count; i++) {
3841 _ssl_locks[i] = PyThread_allocate_lock();
3842 if (_ssl_locks[i] == NULL) {
3843 unsigned int j;
3844 for (j = 0; j < i; j++) {
3845 PyThread_free_lock(_ssl_locks[j]);
3846 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003847 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003848 return 0;
3849 }
3850 }
3851 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003852#if OPENSSL_VERSION_NUMBER >= 0x10000000
3853 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3854#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003855 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003856#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003857 }
3858 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003859}
3860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003861#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003863PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003864"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003865for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003866
Martin v. Löwis1a214512008-06-11 05:26:20 +00003867
3868static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003869 PyModuleDef_HEAD_INIT,
3870 "_ssl",
3871 module_doc,
3872 -1,
3873 PySSL_methods,
3874 NULL,
3875 NULL,
3876 NULL,
3877 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003878};
3879
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003880
3881static void
3882parse_openssl_version(unsigned long libver,
3883 unsigned int *major, unsigned int *minor,
3884 unsigned int *fix, unsigned int *patch,
3885 unsigned int *status)
3886{
3887 *status = libver & 0xF;
3888 libver >>= 4;
3889 *patch = libver & 0xFF;
3890 libver >>= 8;
3891 *fix = libver & 0xFF;
3892 libver >>= 8;
3893 *minor = libver & 0xFF;
3894 libver >>= 8;
3895 *major = libver & 0xFF;
3896}
3897
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003898PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003899PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003900{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003901 PyObject *m, *d, *r;
3902 unsigned long libver;
3903 unsigned int major, minor, fix, patch, status;
3904 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003905 struct py_ssl_error_code *errcode;
3906 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003907
Antoine Pitrou152efa22010-05-16 18:19:27 +00003908 if (PyType_Ready(&PySSLContext_Type) < 0)
3909 return NULL;
3910 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003911 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003913 m = PyModule_Create(&_sslmodule);
3914 if (m == NULL)
3915 return NULL;
3916 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003918 /* Load _socket module and its C API */
3919 socket_api = PySocketModule_ImportModuleAndAPI();
3920 if (!socket_api)
3921 return NULL;
3922 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003924 /* Init OpenSSL */
3925 SSL_load_error_strings();
3926 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003927#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003928 /* note that this will start threading if not already started */
3929 if (!_setup_ssl_threads()) {
3930 return NULL;
3931 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003932#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003933 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003935 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003936 sslerror_type_slots[0].pfunc = PyExc_OSError;
3937 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003938 if (PySSLErrorObject == NULL)
3939 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003940
Antoine Pitrou41032a62011-10-27 23:56:55 +02003941 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3942 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3943 PySSLErrorObject, NULL);
3944 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3945 "ssl.SSLWantReadError", SSLWantReadError_doc,
3946 PySSLErrorObject, NULL);
3947 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3948 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3949 PySSLErrorObject, NULL);
3950 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3951 "ssl.SSLSyscallError", SSLSyscallError_doc,
3952 PySSLErrorObject, NULL);
3953 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3954 "ssl.SSLEOFError", SSLEOFError_doc,
3955 PySSLErrorObject, NULL);
3956 if (PySSLZeroReturnErrorObject == NULL
3957 || PySSLWantReadErrorObject == NULL
3958 || PySSLWantWriteErrorObject == NULL
3959 || PySSLSyscallErrorObject == NULL
3960 || PySSLEOFErrorObject == NULL)
3961 return NULL;
3962 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3963 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3964 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3965 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3966 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3967 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003968 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003969 if (PyDict_SetItemString(d, "_SSLContext",
3970 (PyObject *)&PySSLContext_Type) != 0)
3971 return NULL;
3972 if (PyDict_SetItemString(d, "_SSLSocket",
3973 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003974 return NULL;
3975 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3976 PY_SSL_ERROR_ZERO_RETURN);
3977 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3978 PY_SSL_ERROR_WANT_READ);
3979 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3980 PY_SSL_ERROR_WANT_WRITE);
3981 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3982 PY_SSL_ERROR_WANT_X509_LOOKUP);
3983 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3984 PY_SSL_ERROR_SYSCALL);
3985 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3986 PY_SSL_ERROR_SSL);
3987 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3988 PY_SSL_ERROR_WANT_CONNECT);
3989 /* non ssl.h errorcodes */
3990 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3991 PY_SSL_ERROR_EOF);
3992 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3993 PY_SSL_ERROR_INVALID_ERROR_CODE);
3994 /* cert requirements */
3995 PyModule_AddIntConstant(m, "CERT_NONE",
3996 PY_SSL_CERT_NONE);
3997 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3998 PY_SSL_CERT_OPTIONAL);
3999 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4000 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004001 /* CRL verification for verification_flags */
4002 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4003 0);
4004 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4005 X509_V_FLAG_CRL_CHECK);
4006 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4007 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4008 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4009 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004010
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004011 /* Alert Descriptions from ssl.h */
4012 /* note RESERVED constants no longer intended for use have been removed */
4013 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4014
4015#define ADD_AD_CONSTANT(s) \
4016 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4017 SSL_AD_##s)
4018
4019 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4020 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4021 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4022 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4023 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4024 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4025 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4026 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4027 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4028 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4029 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4030 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4031 ADD_AD_CONSTANT(UNKNOWN_CA);
4032 ADD_AD_CONSTANT(ACCESS_DENIED);
4033 ADD_AD_CONSTANT(DECODE_ERROR);
4034 ADD_AD_CONSTANT(DECRYPT_ERROR);
4035 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4036 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4037 ADD_AD_CONSTANT(INTERNAL_ERROR);
4038 ADD_AD_CONSTANT(USER_CANCELLED);
4039 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004040 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004041#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4042 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4043#endif
4044#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4045 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4046#endif
4047#ifdef SSL_AD_UNRECOGNIZED_NAME
4048 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4049#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004050#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4051 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4052#endif
4053#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4054 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4055#endif
4056#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4057 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4058#endif
4059
4060#undef ADD_AD_CONSTANT
4061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004062 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004063#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004064 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4065 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004066#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004067 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4068 PY_SSL_VERSION_SSL3);
4069 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4070 PY_SSL_VERSION_SSL23);
4071 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4072 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004073#if HAVE_TLSv1_2
4074 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4075 PY_SSL_VERSION_TLS1_1);
4076 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4077 PY_SSL_VERSION_TLS1_2);
4078#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004079
Antoine Pitroub5218772010-05-21 09:56:06 +00004080 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004081 PyModule_AddIntConstant(m, "OP_ALL",
4082 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004083 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4084 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4085 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004086#if HAVE_TLSv1_2
4087 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4088 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4089#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004090 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4091 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004092 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004093#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004094 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004095#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004096#ifdef SSL_OP_NO_COMPRESSION
4097 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4098 SSL_OP_NO_COMPRESSION);
4099#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004100
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004101#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004102 r = Py_True;
4103#else
4104 r = Py_False;
4105#endif
4106 Py_INCREF(r);
4107 PyModule_AddObject(m, "HAS_SNI", r);
4108
Antoine Pitroud6494802011-07-21 01:11:30 +02004109#if HAVE_OPENSSL_FINISHED
4110 r = Py_True;
4111#else
4112 r = Py_False;
4113#endif
4114 Py_INCREF(r);
4115 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4116
Antoine Pitrou501da612011-12-21 09:27:41 +01004117#ifdef OPENSSL_NO_ECDH
4118 r = Py_False;
4119#else
4120 r = Py_True;
4121#endif
4122 Py_INCREF(r);
4123 PyModule_AddObject(m, "HAS_ECDH", r);
4124
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004125#ifdef OPENSSL_NPN_NEGOTIATED
4126 r = Py_True;
4127#else
4128 r = Py_False;
4129#endif
4130 Py_INCREF(r);
4131 PyModule_AddObject(m, "HAS_NPN", r);
4132
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004133 /* Mappings for error codes */
4134 err_codes_to_names = PyDict_New();
4135 err_names_to_codes = PyDict_New();
4136 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4137 return NULL;
4138 errcode = error_codes;
4139 while (errcode->mnemonic != NULL) {
4140 PyObject *mnemo, *key;
4141 mnemo = PyUnicode_FromString(errcode->mnemonic);
4142 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4143 if (mnemo == NULL || key == NULL)
4144 return NULL;
4145 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4146 return NULL;
4147 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4148 return NULL;
4149 Py_DECREF(key);
4150 Py_DECREF(mnemo);
4151 errcode++;
4152 }
4153 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4154 return NULL;
4155 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4156 return NULL;
4157
4158 lib_codes_to_names = PyDict_New();
4159 if (lib_codes_to_names == NULL)
4160 return NULL;
4161 libcode = library_codes;
4162 while (libcode->library != NULL) {
4163 PyObject *mnemo, *key;
4164 key = PyLong_FromLong(libcode->code);
4165 mnemo = PyUnicode_FromString(libcode->library);
4166 if (key == NULL || mnemo == NULL)
4167 return NULL;
4168 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4169 return NULL;
4170 Py_DECREF(key);
4171 Py_DECREF(mnemo);
4172 libcode++;
4173 }
4174 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4175 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004177 /* OpenSSL version */
4178 /* SSLeay() gives us the version of the library linked against,
4179 which could be different from the headers version.
4180 */
4181 libver = SSLeay();
4182 r = PyLong_FromUnsignedLong(libver);
4183 if (r == NULL)
4184 return NULL;
4185 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4186 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004187 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004188 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4189 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4190 return NULL;
4191 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4192 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4193 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004194
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004195 libver = OPENSSL_VERSION_NUMBER;
4196 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4197 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4198 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4199 return NULL;
4200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004201 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004202}