blob: c2553768ca07abd2785c94698d10606e944c4598 [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
Antoine Pitrouce852cb2013-03-30 16:45:04 +0100100/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
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 {
Victor Stinner3de49192011-05-09 00:42:58 +0200137#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000138 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200139#endif
140 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000141 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142#if HAVE_TLSv1_2
143 PY_SSL_VERSION_TLS1,
144 PY_SSL_VERSION_TLS1_1,
145 PY_SSL_VERSION_TLS1_2
146#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100149};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200150
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151#ifdef WITH_THREAD
152
153/* serves as a flag to see whether we've initialized the SSL thread support. */
154/* 0 means no, greater than 0 means yes */
155
156static unsigned int _ssl_locks_count = 0;
157
158#endif /* def WITH_THREAD */
159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160/* SSL socket object */
161
162#define X509_NAME_MAXLEN 256
163
164/* RAND_* APIs got added to OpenSSL in 0.9.5 */
165#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
166# define HAVE_OPENSSL_RAND 1
167#else
168# undef HAVE_OPENSSL_RAND
169#endif
170
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000171/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
172 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
173 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
174#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000175# define HAVE_SSL_CTX_CLEAR_OPTIONS
176#else
177# undef HAVE_SSL_CTX_CLEAR_OPTIONS
178#endif
179
Antoine Pitroud6494802011-07-21 01:11:30 +0200180/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
181 * older SSL, but let's be safe */
182#define PySSL_CB_MAXLEN 128
183
184/* SSL_get_finished got added to OpenSSL in 0.9.5 */
185#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
186# define HAVE_OPENSSL_FINISHED 1
187#else
188# define HAVE_OPENSSL_FINISHED 0
189#endif
190
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100191/* ECDH support got added to OpenSSL in 0.9.8 */
192#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
193# define OPENSSL_NO_ECDH
194#endif
195
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100196/* compression support got added to OpenSSL in 0.9.8 */
197#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
198# define OPENSSL_NO_COMP
199#endif
200
Christian Heimes2427b502013-11-23 11:24:32 +0100201/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
202#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
203# define HAVE_OPENSSL_VERIFY_PARAM
204#endif
205
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100206
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000207typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000208 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100210#ifdef OPENSSL_NPN_NEGOTIATED
211 char *npn_protocols;
212 int npn_protocols_len;
213#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100214#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200215 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100216#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000217} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000218
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219typedef struct {
220 PyObject_HEAD
221 PyObject *Socket; /* weakref to socket on which we're layered */
222 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100223 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000224 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200225 char shutdown_seen_zero;
226 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200227 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000229
Antoine Pitrou152efa22010-05-16 18:19:27 +0000230static PyTypeObject PySSLContext_Type;
231static PyTypeObject PySSLSocket_Type;
232
233static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
234static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000235static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000237static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
238static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000239
Antoine Pitrou152efa22010-05-16 18:19:27 +0000240#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
241#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000242
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000243typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 SOCKET_IS_NONBLOCKING,
245 SOCKET_IS_BLOCKING,
246 SOCKET_HAS_TIMED_OUT,
247 SOCKET_HAS_BEEN_CLOSED,
248 SOCKET_TOO_LARGE_FOR_SELECT,
249 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000250} timeout_state;
251
Thomas Woutersed03b412007-08-28 21:37:11 +0000252/* Wrap error strings with filename and line # */
253#define STRINGIFY1(x) #x
254#define STRINGIFY2(x) STRINGIFY1(x)
255#define ERRSTR1(x,y,z) (x ":" y ": " z)
256#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
257
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200258
259/*
260 * SSL errors.
261 */
262
263PyDoc_STRVAR(SSLError_doc,
264"An error occurred in the SSL implementation.");
265
266PyDoc_STRVAR(SSLZeroReturnError_doc,
267"SSL/TLS session closed cleanly.");
268
269PyDoc_STRVAR(SSLWantReadError_doc,
270"Non-blocking SSL socket needs to read more data\n"
271"before the requested operation can be completed.");
272
273PyDoc_STRVAR(SSLWantWriteError_doc,
274"Non-blocking SSL socket needs to write more data\n"
275"before the requested operation can be completed.");
276
277PyDoc_STRVAR(SSLSyscallError_doc,
278"System error when attempting SSL operation.");
279
280PyDoc_STRVAR(SSLEOFError_doc,
281"SSL/TLS connection terminated abruptly.");
282
283static PyObject *
284SSLError_str(PyOSErrorObject *self)
285{
286 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
287 Py_INCREF(self->strerror);
288 return self->strerror;
289 }
290 else
291 return PyObject_Str(self->args);
292}
293
294static PyType_Slot sslerror_type_slots[] = {
295 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
296 {Py_tp_doc, SSLError_doc},
297 {Py_tp_str, SSLError_str},
298 {0, 0},
299};
300
301static PyType_Spec sslerror_type_spec = {
302 "ssl.SSLError",
303 sizeof(PyOSErrorObject),
304 0,
305 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
306 sslerror_type_slots
307};
308
309static void
310fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
311 int lineno, unsigned long errcode)
312{
313 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
314 PyObject *init_value, *msg, *key;
315 _Py_IDENTIFIER(reason);
316 _Py_IDENTIFIER(library);
317
318 if (errcode != 0) {
319 int lib, reason;
320
321 lib = ERR_GET_LIB(errcode);
322 reason = ERR_GET_REASON(errcode);
323 key = Py_BuildValue("ii", lib, reason);
324 if (key == NULL)
325 goto fail;
326 reason_obj = PyDict_GetItem(err_codes_to_names, key);
327 Py_DECREF(key);
328 if (reason_obj == NULL) {
329 /* XXX if reason < 100, it might reflect a library number (!!) */
330 PyErr_Clear();
331 }
332 key = PyLong_FromLong(lib);
333 if (key == NULL)
334 goto fail;
335 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
336 Py_DECREF(key);
337 if (lib_obj == NULL) {
338 PyErr_Clear();
339 }
340 if (errstr == NULL)
341 errstr = ERR_reason_error_string(errcode);
342 }
343 if (errstr == NULL)
344 errstr = "unknown error";
345
346 if (reason_obj && lib_obj)
347 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
348 lib_obj, reason_obj, errstr, lineno);
349 else if (lib_obj)
350 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
351 lib_obj, errstr, lineno);
352 else
353 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200354 if (msg == NULL)
355 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100356
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200357 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100358 if (init_value == NULL)
359 goto fail;
360
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200361 err_value = PyObject_CallObject(type, init_value);
362 Py_DECREF(init_value);
363 if (err_value == NULL)
364 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100365
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200366 if (reason_obj == NULL)
367 reason_obj = Py_None;
368 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
369 goto fail;
370 if (lib_obj == NULL)
371 lib_obj = Py_None;
372 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
373 goto fail;
374 PyErr_SetObject(type, err_value);
375fail:
376 Py_XDECREF(err_value);
377}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378
379static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000380PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000381{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200382 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200383 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 int err;
385 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200386 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200389 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 if (obj->ssl != NULL) {
392 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 switch (err) {
395 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200396 errstr = "TLS/SSL connection has been closed (EOF)";
397 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000398 p = PY_SSL_ERROR_ZERO_RETURN;
399 break;
400 case SSL_ERROR_WANT_READ:
401 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200402 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 p = PY_SSL_ERROR_WANT_READ;
404 break;
405 case SSL_ERROR_WANT_WRITE:
406 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200407 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 errstr = "The operation did not complete (write)";
409 break;
410 case SSL_ERROR_WANT_X509_LOOKUP:
411 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 break;
414 case SSL_ERROR_WANT_CONNECT:
415 p = PY_SSL_ERROR_WANT_CONNECT;
416 errstr = "The operation did not complete (connect)";
417 break;
418 case SSL_ERROR_SYSCALL:
419 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000420 if (e == 0) {
421 PySocketSockObject *s
422 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
423 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000424 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200425 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000426 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000429 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000430 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200431 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000432 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200436 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000437 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 }
439 } else {
440 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 }
442 break;
443 }
444 case SSL_ERROR_SSL:
445 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447 if (e == 0)
448 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000449 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 break;
451 }
452 default:
453 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
454 errstr = "Invalid error code";
455 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000458 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000460}
461
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462static PyObject *
463_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
464
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467 else
468 errcode = 0;
469 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000470 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472}
473
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474/*
475 * SSL objects
476 */
477
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000480 enum py_ssl_server_or_client socket_type,
481 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000482{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000483 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100484 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200485 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000486
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 if (self == NULL)
489 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 self->peer_cert = NULL;
492 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100494 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200495 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200496 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 /* Make sure the SSL error state is initialized */
500 (void) ERR_get_state();
501 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000504 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100506 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100507 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200508 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000509#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200510 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000511#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200512 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000513
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100514#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000515 if (server_hostname != NULL)
516 SSL_set_tlsext_host_name(self->ssl, server_hostname);
517#endif
518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000519 /* If the socket is in non-blocking mode or timeout mode, set the BIO
520 * to non-blocking mode (blocking is the default)
521 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000522 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
524 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
525 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 PySSL_BEGIN_ALLOW_THREADS
528 if (socket_type == PY_SSL_CLIENT)
529 SSL_set_connect_state(self->ssl);
530 else
531 SSL_set_accept_state(self->ssl);
532 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000533
Antoine Pitroud6494802011-07-21 01:11:30 +0200534 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000535 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100536 if (self->Socket == NULL) {
537 Py_DECREF(self);
538 return NULL;
539 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000541}
542
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000543/* SSL object methods */
544
Antoine Pitrou152efa22010-05-16 18:19:27 +0000545static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000546{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 int ret;
548 int err;
549 int sockstate, nonblocking;
550 PySocketSockObject *sock
551 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000552
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 if (((PyObject*)sock) == Py_None) {
554 _setSSLError("Underlying socket connection gone",
555 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
556 return NULL;
557 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000558 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 /* just in case the blocking state of the socket has been changed */
561 nonblocking = (sock->sock_timeout >= 0.0);
562 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
563 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 /* Actually negotiate SSL connection */
566 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000568 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 ret = SSL_do_handshake(self->ssl);
570 err = SSL_get_error(self->ssl, ret);
571 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000572 if (PyErr_CheckSignals())
573 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 if (err == SSL_ERROR_WANT_READ) {
575 sockstate = check_socket_and_wait_for_timeout(sock, 0);
576 } else if (err == SSL_ERROR_WANT_WRITE) {
577 sockstate = check_socket_and_wait_for_timeout(sock, 1);
578 } else {
579 sockstate = SOCKET_OPERATION_OK;
580 }
581 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000582 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000583 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000584 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
586 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000587 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000588 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
590 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000591 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000592 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
594 break;
595 }
596 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000597 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 if (ret < 1)
599 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000601 if (self->peer_cert)
602 X509_free (self->peer_cert);
603 PySSL_BEGIN_ALLOW_THREADS
604 self->peer_cert = SSL_get_peer_certificate(self->ssl);
605 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200606 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607
608 Py_INCREF(Py_None);
609 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000610
611error:
612 Py_DECREF(sock);
613 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000614}
615
Thomas Woutersed03b412007-08-28 21:37:11 +0000616static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 char namebuf[X509_NAME_MAXLEN];
620 int buflen;
621 PyObject *name_obj;
622 PyObject *value_obj;
623 PyObject *attr;
624 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
627 if (buflen < 0) {
628 _setSSLError(NULL, 0, __FILE__, __LINE__);
629 goto fail;
630 }
631 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
632 if (name_obj == NULL)
633 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
636 if (buflen < 0) {
637 _setSSLError(NULL, 0, __FILE__, __LINE__);
638 Py_DECREF(name_obj);
639 goto fail;
640 }
641 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000642 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 OPENSSL_free(valuebuf);
644 if (value_obj == NULL) {
645 Py_DECREF(name_obj);
646 goto fail;
647 }
648 attr = PyTuple_New(2);
649 if (attr == NULL) {
650 Py_DECREF(name_obj);
651 Py_DECREF(value_obj);
652 goto fail;
653 }
654 PyTuple_SET_ITEM(attr, 0, name_obj);
655 PyTuple_SET_ITEM(attr, 1, value_obj);
656 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000657
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000660}
661
662static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000664{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
666 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
667 PyObject *rdnt;
668 PyObject *attr = NULL; /* tuple to hold an attribute */
669 int entry_count = X509_NAME_entry_count(xname);
670 X509_NAME_ENTRY *entry;
671 ASN1_OBJECT *name;
672 ASN1_STRING *value;
673 int index_counter;
674 int rdn_level = -1;
675 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 dn = PyList_New(0);
678 if (dn == NULL)
679 return NULL;
680 /* now create another tuple to hold the top-level RDN */
681 rdn = PyList_New(0);
682 if (rdn == NULL)
683 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 for (index_counter = 0;
686 index_counter < entry_count;
687 index_counter++)
688 {
689 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 /* check to see if we've gotten to a new RDN */
692 if (rdn_level >= 0) {
693 if (rdn_level != entry->set) {
694 /* yes, new RDN */
695 /* add old RDN to DN */
696 rdnt = PyList_AsTuple(rdn);
697 Py_DECREF(rdn);
698 if (rdnt == NULL)
699 goto fail0;
700 retcode = PyList_Append(dn, rdnt);
701 Py_DECREF(rdnt);
702 if (retcode < 0)
703 goto fail0;
704 /* create new RDN */
705 rdn = PyList_New(0);
706 if (rdn == NULL)
707 goto fail0;
708 }
709 }
710 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 /* now add this attribute to the current RDN */
713 name = X509_NAME_ENTRY_get_object(entry);
714 value = X509_NAME_ENTRY_get_data(entry);
715 attr = _create_tuple_for_attribute(name, value);
716 /*
717 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
718 entry->set,
719 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
720 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
721 */
722 if (attr == NULL)
723 goto fail1;
724 retcode = PyList_Append(rdn, attr);
725 Py_DECREF(attr);
726 if (retcode < 0)
727 goto fail1;
728 }
729 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100730 if (rdn != NULL) {
731 if (PyList_GET_SIZE(rdn) > 0) {
732 rdnt = PyList_AsTuple(rdn);
733 Py_DECREF(rdn);
734 if (rdnt == NULL)
735 goto fail0;
736 retcode = PyList_Append(dn, rdnt);
737 Py_DECREF(rdnt);
738 if (retcode < 0)
739 goto fail0;
740 }
741 else {
742 Py_DECREF(rdn);
743 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 /* convert list to tuple */
747 rdnt = PyList_AsTuple(dn);
748 Py_DECREF(dn);
749 if (rdnt == NULL)
750 return NULL;
751 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752
753 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755
756 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 Py_XDECREF(dn);
758 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759}
760
761static PyObject *
762_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 /* this code follows the procedure outlined in
765 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
766 function to extract the STACK_OF(GENERAL_NAME),
767 then iterates through the stack to add the
768 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 int i, j;
771 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200772 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 X509_EXTENSION *ext = NULL;
774 GENERAL_NAMES *names = NULL;
775 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000776 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 BIO *biobuf = NULL;
778 char buf[2048];
779 char *vptr;
780 int len;
781 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000782#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000784#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000786#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 if (certificate == NULL)
789 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 /* get a memory buffer */
792 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200794 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 while ((i = X509_get_ext_by_NID(
796 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 if (peer_alt_names == Py_None) {
799 peer_alt_names = PyList_New(0);
800 if (peer_alt_names == NULL)
801 goto fail;
802 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 /* now decode the altName */
805 ext = X509_get_ext(certificate, i);
806 if(!(method = X509V3_EXT_get(ext))) {
807 PyErr_SetString
808 (PySSLErrorObject,
809 ERRSTR("No method for internalizing subjectAltName!"));
810 goto fail;
811 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 p = ext->value->data;
814 if (method->it)
815 names = (GENERAL_NAMES*)
816 (ASN1_item_d2i(NULL,
817 &p,
818 ext->value->length,
819 ASN1_ITEM_ptr(method->it)));
820 else
821 names = (GENERAL_NAMES*)
822 (method->d2i(NULL,
823 &p,
824 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200828 int gntype;
829 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200832 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200833 switch (gntype) {
834 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 /* we special-case DirName as a tuple of
836 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 t = PyTuple_New(2);
839 if (t == NULL) {
840 goto fail;
841 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 v = PyUnicode_FromString("DirName");
844 if (v == NULL) {
845 Py_DECREF(t);
846 goto fail;
847 }
848 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 v = _create_tuple_for_X509_NAME (name->d.dirn);
851 if (v == NULL) {
852 Py_DECREF(t);
853 goto fail;
854 }
855 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200856 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000857
Christian Heimes824f7f32013-08-17 00:54:47 +0200858 case GEN_EMAIL:
859 case GEN_DNS:
860 case GEN_URI:
861 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
862 correctly, CVE-2013-4238 */
863 t = PyTuple_New(2);
864 if (t == NULL)
865 goto fail;
866 switch (gntype) {
867 case GEN_EMAIL:
868 v = PyUnicode_FromString("email");
869 as = name->d.rfc822Name;
870 break;
871 case GEN_DNS:
872 v = PyUnicode_FromString("DNS");
873 as = name->d.dNSName;
874 break;
875 case GEN_URI:
876 v = PyUnicode_FromString("URI");
877 as = name->d.uniformResourceIdentifier;
878 break;
879 }
880 if (v == NULL) {
881 Py_DECREF(t);
882 goto fail;
883 }
884 PyTuple_SET_ITEM(t, 0, v);
885 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
886 ASN1_STRING_length(as));
887 if (v == NULL) {
888 Py_DECREF(t);
889 goto fail;
890 }
891 PyTuple_SET_ITEM(t, 1, v);
892 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
Christian Heimes824f7f32013-08-17 00:54:47 +0200894 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200896 switch (gntype) {
897 /* check for new general name type */
898 case GEN_OTHERNAME:
899 case GEN_X400:
900 case GEN_EDIPARTY:
901 case GEN_IPADD:
902 case GEN_RID:
903 break;
904 default:
905 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
906 "Unknown general name type %d",
907 gntype) == -1) {
908 goto fail;
909 }
910 break;
911 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 (void) BIO_reset(biobuf);
913 GENERAL_NAME_print(biobuf, name);
914 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
915 if (len < 0) {
916 _setSSLError(NULL, 0, __FILE__, __LINE__);
917 goto fail;
918 }
919 vptr = strchr(buf, ':');
920 if (vptr == NULL)
921 goto fail;
922 t = PyTuple_New(2);
923 if (t == NULL)
924 goto fail;
925 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
926 if (v == NULL) {
927 Py_DECREF(t);
928 goto fail;
929 }
930 PyTuple_SET_ITEM(t, 0, v);
931 v = PyUnicode_FromStringAndSize((vptr + 1),
932 (len - (vptr - buf + 1)));
933 if (v == NULL) {
934 Py_DECREF(t);
935 goto fail;
936 }
937 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200938 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 if (PyList_Append(peer_alt_names, t) < 0) {
944 Py_DECREF(t);
945 goto fail;
946 }
947 Py_DECREF(t);
948 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100949 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 }
951 BIO_free(biobuf);
952 if (peer_alt_names != Py_None) {
953 v = PyList_AsTuple(peer_alt_names);
954 Py_DECREF(peer_alt_names);
955 return v;
956 } else {
957 return peer_alt_names;
958 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000959
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
961 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 if (biobuf != NULL)
963 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 if (peer_alt_names != Py_None) {
966 Py_XDECREF(peer_alt_names);
967 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970}
971
972static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100973_get_aia_uri(X509 *certificate, int nid) {
974 PyObject *lst = NULL, *ostr = NULL;
975 int i, result;
976 AUTHORITY_INFO_ACCESS *info;
977
978 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
979 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
980 return Py_None;
981 }
982
983 if ((lst = PyList_New(0)) == NULL) {
984 goto fail;
985 }
986
987 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
988 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
989 ASN1_IA5STRING *uri;
990
991 if ((OBJ_obj2nid(ad->method) != nid) ||
992 (ad->location->type != GEN_URI)) {
993 continue;
994 }
995 uri = ad->location->d.uniformResourceIdentifier;
996 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
997 uri->length);
998 if (ostr == NULL) {
999 goto fail;
1000 }
1001 result = PyList_Append(lst, ostr);
1002 Py_DECREF(ostr);
1003 if (result < 0) {
1004 goto fail;
1005 }
1006 }
1007 AUTHORITY_INFO_ACCESS_free(info);
1008
1009 /* convert to tuple or None */
1010 if (PyList_Size(lst) == 0) {
1011 Py_DECREF(lst);
1012 return Py_None;
1013 } else {
1014 PyObject *tup;
1015 tup = PyList_AsTuple(lst);
1016 Py_DECREF(lst);
1017 return tup;
1018 }
1019
1020 fail:
1021 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001022 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001023 return NULL;
1024}
1025
1026static PyObject *
1027_get_crl_dp(X509 *certificate) {
1028 STACK_OF(DIST_POINT) *dps;
1029 int i, j, result;
1030 PyObject *lst;
1031
Christian Heimes949ec142013-11-21 16:26:51 +01001032#if OPENSSL_VERSION_NUMBER < 0x10001000L
1033 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1034 NULL, NULL);
1035#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001036 /* Calls x509v3_cache_extensions and sets up crldp */
1037 X509_check_ca(certificate);
1038 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001039#endif
1040
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001041 if (dps == NULL) {
1042 return Py_None;
1043 }
1044
1045 if ((lst = PyList_New(0)) == NULL) {
1046 return NULL;
1047 }
1048
1049 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1050 DIST_POINT *dp;
1051 STACK_OF(GENERAL_NAME) *gns;
1052
1053 dp = sk_DIST_POINT_value(dps, i);
1054 gns = dp->distpoint->name.fullname;
1055
1056 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1057 GENERAL_NAME *gn;
1058 ASN1_IA5STRING *uri;
1059 PyObject *ouri;
1060
1061 gn = sk_GENERAL_NAME_value(gns, j);
1062 if (gn->type != GEN_URI) {
1063 continue;
1064 }
1065 uri = gn->d.uniformResourceIdentifier;
1066 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1067 uri->length);
1068 if (ouri == NULL) {
1069 Py_DECREF(lst);
1070 return NULL;
1071 }
1072 result = PyList_Append(lst, ouri);
1073 Py_DECREF(ouri);
1074 if (result < 0) {
1075 Py_DECREF(lst);
1076 return NULL;
1077 }
1078 }
1079 }
1080 /* convert to tuple or None */
1081 if (PyList_Size(lst) == 0) {
1082 Py_DECREF(lst);
1083 return Py_None;
1084 } else {
1085 PyObject *tup;
1086 tup = PyList_AsTuple(lst);
1087 Py_DECREF(lst);
1088 return tup;
1089 }
1090}
1091
1092static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001093_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 PyObject *retval = NULL;
1096 BIO *biobuf = NULL;
1097 PyObject *peer;
1098 PyObject *peer_alt_names = NULL;
1099 PyObject *issuer;
1100 PyObject *version;
1101 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001102 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 ASN1_INTEGER *serialNumber;
1104 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001105 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 ASN1_TIME *notBefore, *notAfter;
1107 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 retval = PyDict_New();
1110 if (retval == NULL)
1111 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 peer = _create_tuple_for_X509_NAME(
1114 X509_get_subject_name(certificate));
1115 if (peer == NULL)
1116 goto fail0;
1117 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1118 Py_DECREF(peer);
1119 goto fail0;
1120 }
1121 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001122
Antoine Pitroufb046912010-11-09 20:21:19 +00001123 issuer = _create_tuple_for_X509_NAME(
1124 X509_get_issuer_name(certificate));
1125 if (issuer == NULL)
1126 goto fail0;
1127 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001129 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001131 Py_DECREF(issuer);
1132
1133 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001134 if (version == NULL)
1135 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001136 if (PyDict_SetItemString(retval, "version", version) < 0) {
1137 Py_DECREF(version);
1138 goto fail0;
1139 }
1140 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 /* get a memory buffer */
1143 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001144
Antoine Pitroufb046912010-11-09 20:21:19 +00001145 (void) BIO_reset(biobuf);
1146 serialNumber = X509_get_serialNumber(certificate);
1147 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1148 i2a_ASN1_INTEGER(biobuf, serialNumber);
1149 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1150 if (len < 0) {
1151 _setSSLError(NULL, 0, __FILE__, __LINE__);
1152 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001154 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1155 if (sn_obj == NULL)
1156 goto fail1;
1157 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1158 Py_DECREF(sn_obj);
1159 goto fail1;
1160 }
1161 Py_DECREF(sn_obj);
1162
1163 (void) BIO_reset(biobuf);
1164 notBefore = X509_get_notBefore(certificate);
1165 ASN1_TIME_print(biobuf, notBefore);
1166 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1167 if (len < 0) {
1168 _setSSLError(NULL, 0, __FILE__, __LINE__);
1169 goto fail1;
1170 }
1171 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1172 if (pnotBefore == NULL)
1173 goto fail1;
1174 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1175 Py_DECREF(pnotBefore);
1176 goto fail1;
1177 }
1178 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 (void) BIO_reset(biobuf);
1181 notAfter = X509_get_notAfter(certificate);
1182 ASN1_TIME_print(biobuf, notAfter);
1183 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1184 if (len < 0) {
1185 _setSSLError(NULL, 0, __FILE__, __LINE__);
1186 goto fail1;
1187 }
1188 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1189 if (pnotAfter == NULL)
1190 goto fail1;
1191 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1192 Py_DECREF(pnotAfter);
1193 goto fail1;
1194 }
1195 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 peer_alt_names = _get_peer_alt_names(certificate);
1200 if (peer_alt_names == NULL)
1201 goto fail1;
1202 else if (peer_alt_names != Py_None) {
1203 if (PyDict_SetItemString(retval, "subjectAltName",
1204 peer_alt_names) < 0) {
1205 Py_DECREF(peer_alt_names);
1206 goto fail1;
1207 }
1208 Py_DECREF(peer_alt_names);
1209 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001210
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001211 /* Authority Information Access: OCSP URIs */
1212 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1213 if (obj == NULL) {
1214 goto fail1;
1215 } else if (obj != Py_None) {
1216 result = PyDict_SetItemString(retval, "OCSP", obj);
1217 Py_DECREF(obj);
1218 if (result < 0) {
1219 goto fail1;
1220 }
1221 }
1222
1223 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1224 if (obj == NULL) {
1225 goto fail1;
1226 } else if (obj != Py_None) {
1227 result = PyDict_SetItemString(retval, "caIssuers", obj);
1228 Py_DECREF(obj);
1229 if (result < 0) {
1230 goto fail1;
1231 }
1232 }
1233
1234 /* CDP (CRL distribution points) */
1235 obj = _get_crl_dp(certificate);
1236 if (obj == NULL) {
1237 goto fail1;
1238 } else if (obj != Py_None) {
1239 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1240 Py_DECREF(obj);
1241 if (result < 0) {
1242 goto fail1;
1243 }
1244 }
1245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 BIO_free(biobuf);
1247 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001248
1249 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 if (biobuf != NULL)
1251 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001252 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 Py_XDECREF(retval);
1254 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001255}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001256
Christian Heimes9a5395a2013-06-17 15:44:12 +02001257static PyObject *
1258_certificate_to_der(X509 *certificate)
1259{
1260 unsigned char *bytes_buf = NULL;
1261 int len;
1262 PyObject *retval;
1263
1264 bytes_buf = NULL;
1265 len = i2d_X509(certificate, &bytes_buf);
1266 if (len < 0) {
1267 _setSSLError(NULL, 0, __FILE__, __LINE__);
1268 return NULL;
1269 }
1270 /* this is actually an immutable bytes sequence */
1271 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1272 OPENSSL_free(bytes_buf);
1273 return retval;
1274}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
1276static PyObject *
1277PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001280 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 X509 *x=NULL;
1282 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001283
Antoine Pitroufb046912010-11-09 20:21:19 +00001284 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1285 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1289 PyErr_SetString(PySSLErrorObject,
1290 "Can't malloc memory to read file");
1291 goto fail0;
1292 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001293
Victor Stinner3800e1e2010-05-16 21:23:48 +00001294 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 PyErr_SetString(PySSLErrorObject,
1296 "Can't open file");
1297 goto fail0;
1298 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1301 if (x == NULL) {
1302 PyErr_SetString(PySSLErrorObject,
1303 "Error decoding PEM-encoded file");
1304 goto fail0;
1305 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
Antoine Pitroufb046912010-11-09 20:21:19 +00001307 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001308 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
1310 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001311 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (cert != NULL) BIO_free(cert);
1313 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314}
1315
1316
1317static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001318PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001321 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Antoine Pitrou721738f2012-08-15 23:20:39 +02001323 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325
Antoine Pitrou20b85552013-09-29 19:50:53 +02001326 if (!self->handshake_done) {
1327 PyErr_SetString(PyExc_ValueError,
1328 "handshake not done yet");
1329 return NULL;
1330 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 if (!self->peer_cert)
1332 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001333
Antoine Pitrou721738f2012-08-15 23:20:39 +02001334 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001336 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001338 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 if ((verification & SSL_VERIFY_PEER) == 0)
1340 return PyDict_New();
1341 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001342 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344}
1345
1346PyDoc_STRVAR(PySSL_peercert_doc,
1347"peer_certificate([der=False]) -> certificate\n\
1348\n\
1349Returns the certificate for the peer. If no certificate was provided,\n\
1350returns None. If a certificate was provided, but not validated, returns\n\
1351an empty dictionary. Otherwise returns a dict containing information\n\
1352about the peer certificate.\n\
1353\n\
1354If the optional argument is True, returns a DER-encoded copy of the\n\
1355peer certificate, or None if no certificate was provided. This will\n\
1356return the certificate even if it wasn't validated.");
1357
Antoine Pitrou152efa22010-05-16 18:19:27 +00001358static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001361 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 char *cipher_name;
1363 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001366 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 current = SSL_get_current_cipher(self->ssl);
1368 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001369 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 retval = PyTuple_New(3);
1372 if (retval == NULL)
1373 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 cipher_name = (char *) SSL_CIPHER_get_name(current);
1376 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001377 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 PyTuple_SET_ITEM(retval, 0, Py_None);
1379 } else {
1380 v = PyUnicode_FromString(cipher_name);
1381 if (v == NULL)
1382 goto fail0;
1383 PyTuple_SET_ITEM(retval, 0, v);
1384 }
1385 cipher_protocol = SSL_CIPHER_get_version(current);
1386 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001387 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 PyTuple_SET_ITEM(retval, 1, Py_None);
1389 } else {
1390 v = PyUnicode_FromString(cipher_protocol);
1391 if (v == NULL)
1392 goto fail0;
1393 PyTuple_SET_ITEM(retval, 1, v);
1394 }
1395 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1396 if (v == NULL)
1397 goto fail0;
1398 PyTuple_SET_ITEM(retval, 2, v);
1399 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 Py_DECREF(retval);
1403 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404}
1405
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001406#ifdef OPENSSL_NPN_NEGOTIATED
1407static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1408 const unsigned char *out;
1409 unsigned int outlen;
1410
Victor Stinner4569cd52013-06-23 14:58:43 +02001411 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001412 &out, &outlen);
1413
1414 if (out == NULL)
1415 Py_RETURN_NONE;
1416 return PyUnicode_FromStringAndSize((char *) out, outlen);
1417}
1418#endif
1419
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001420static PyObject *PySSL_compression(PySSLSocket *self) {
1421#ifdef OPENSSL_NO_COMP
1422 Py_RETURN_NONE;
1423#else
1424 const COMP_METHOD *comp_method;
1425 const char *short_name;
1426
1427 if (self->ssl == NULL)
1428 Py_RETURN_NONE;
1429 comp_method = SSL_get_current_compression(self->ssl);
1430 if (comp_method == NULL || comp_method->type == NID_undef)
1431 Py_RETURN_NONE;
1432 short_name = OBJ_nid2sn(comp_method->type);
1433 if (short_name == NULL)
1434 Py_RETURN_NONE;
1435 return PyUnicode_DecodeFSDefault(short_name);
1436#endif
1437}
1438
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001439static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1440 Py_INCREF(self->ctx);
1441 return self->ctx;
1442}
1443
1444static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1445 void *closure) {
1446
1447 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001448#if !HAVE_SNI
1449 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1450 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001451 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001452#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001453 Py_INCREF(value);
1454 Py_DECREF(self->ctx);
1455 self->ctx = (PySSLContext *) value;
1456 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001457#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001458 } else {
1459 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1460 return -1;
1461 }
1462
1463 return 0;
1464}
1465
1466PyDoc_STRVAR(PySSL_set_context_doc,
1467"_setter_context(ctx)\n\
1468\
1469This changes the context associated with the SSLSocket. This is typically\n\
1470used from within a callback function set by the set_servername_callback\n\
1471on the SSLContext to change the certificate information associated with the\n\
1472SSLSocket before the cryptographic exchange handshake messages\n");
1473
1474
1475
Antoine Pitrou152efa22010-05-16 18:19:27 +00001476static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001477{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 if (self->peer_cert) /* Possible not to have one? */
1479 X509_free (self->peer_cert);
1480 if (self->ssl)
1481 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001483 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485}
1486
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001488 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001489 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001490 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001491
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001492static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001493check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001494{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 fd_set fds;
1496 struct timeval tv;
1497 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1500 if (s->sock_timeout < 0.0)
1501 return SOCKET_IS_BLOCKING;
1502 else if (s->sock_timeout == 0.0)
1503 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 /* Guard against closed socket */
1506 if (s->sock_fd < 0)
1507 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 /* Prefer poll, if available, since you can poll() any fd
1510 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001511#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 {
1513 struct pollfd pollfd;
1514 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 pollfd.fd = s->sock_fd;
1517 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 /* s->sock_timeout is in seconds, timeout in ms */
1520 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1521 PySSL_BEGIN_ALLOW_THREADS
1522 rc = poll(&pollfd, 1, timeout);
1523 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 goto normal_return;
1526 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001527#endif
1528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001530 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 /* Construct the arguments to select */
1534 tv.tv_sec = (int)s->sock_timeout;
1535 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1536 FD_ZERO(&fds);
1537 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 /* See if the socket is ready */
1540 PySSL_BEGIN_ALLOW_THREADS
1541 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001542 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1543 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001545 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1546 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001548
Bill Janssen6e027db2007-11-15 22:23:56 +00001549#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001551#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1553 (when we are able to write or when there's something to read) */
1554 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001555}
1556
Antoine Pitrou152efa22010-05-16 18:19:27 +00001557static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001558{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 Py_buffer buf;
1560 int len;
1561 int sockstate;
1562 int err;
1563 int nonblocking;
1564 PySocketSockObject *sock
1565 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 if (((PyObject*)sock) == Py_None) {
1568 _setSSLError("Underlying socket connection gone",
1569 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1570 return NULL;
1571 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001572 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001574 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1575 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578
Victor Stinner6efa9652013-06-25 00:42:31 +02001579 if (buf.len > INT_MAX) {
1580 PyErr_Format(PyExc_OverflowError,
1581 "string longer than %d bytes", INT_MAX);
1582 goto error;
1583 }
1584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 /* just in case the blocking state of the socket has been changed */
1586 nonblocking = (sock->sock_timeout >= 0.0);
1587 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1588 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1589
1590 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1591 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001592 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 "The write operation timed out");
1594 goto error;
1595 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1596 PyErr_SetString(PySSLErrorObject,
1597 "Underlying socket has been closed.");
1598 goto error;
1599 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1600 PyErr_SetString(PySSLErrorObject,
1601 "Underlying socket too large for select().");
1602 goto error;
1603 }
1604 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001606 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 err = SSL_get_error(self->ssl, len);
1608 PySSL_END_ALLOW_THREADS
1609 if (PyErr_CheckSignals()) {
1610 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001611 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001613 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001615 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 } else {
1617 sockstate = SOCKET_OPERATION_OK;
1618 }
1619 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001620 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 "The write operation timed out");
1622 goto error;
1623 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1624 PyErr_SetString(PySSLErrorObject,
1625 "Underlying socket has been closed.");
1626 goto error;
1627 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1628 break;
1629 }
1630 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001632 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 PyBuffer_Release(&buf);
1634 if (len > 0)
1635 return PyLong_FromLong(len);
1636 else
1637 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001638
1639error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001640 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 PyBuffer_Release(&buf);
1642 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001643}
1644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001646"write(s) -> len\n\
1647\n\
1648Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001649of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001650
Antoine Pitrou152efa22010-05-16 18:19:27 +00001651static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001652{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001653 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 PySSL_BEGIN_ALLOW_THREADS
1656 count = SSL_pending(self->ssl);
1657 PySSL_END_ALLOW_THREADS
1658 if (count < 0)
1659 return PySSL_SetError(self, count, __FILE__, __LINE__);
1660 else
1661 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001662}
1663
1664PyDoc_STRVAR(PySSL_SSLpending_doc,
1665"pending() -> count\n\
1666\n\
1667Returns the number of already decrypted bytes available for read,\n\
1668pending on the connection.\n");
1669
Antoine Pitrou152efa22010-05-16 18:19:27 +00001670static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001671{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyObject *dest = NULL;
1673 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001675 int len, count;
1676 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 int sockstate;
1678 int err;
1679 int nonblocking;
1680 PySocketSockObject *sock
1681 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 if (((PyObject*)sock) == Py_None) {
1684 _setSSLError("Underlying socket connection gone",
1685 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1686 return NULL;
1687 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001688 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001690 buf.obj = NULL;
1691 buf.buf = NULL;
1692 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001693 goto error;
1694
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001695 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1696 dest = PyBytes_FromStringAndSize(NULL, len);
1697 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001698 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001699 mem = PyBytes_AS_STRING(dest);
1700 }
1701 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001703 mem = buf.buf;
1704 if (len <= 0 || len > buf.len) {
1705 len = (int) buf.len;
1706 if (buf.len != len) {
1707 PyErr_SetString(PyExc_OverflowError,
1708 "maximum length can't fit in a C 'int'");
1709 goto error;
1710 }
1711 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 }
1713
1714 /* just in case the blocking state of the socket has been changed */
1715 nonblocking = (sock->sock_timeout >= 0.0);
1716 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1717 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1718
1719 /* first check if there are bytes ready to be read */
1720 PySSL_BEGIN_ALLOW_THREADS
1721 count = SSL_pending(self->ssl);
1722 PySSL_END_ALLOW_THREADS
1723
1724 if (!count) {
1725 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1726 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001727 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 "The read operation timed out");
1729 goto error;
1730 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1731 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001732 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 goto error;
1734 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1735 count = 0;
1736 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001737 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 }
1739 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 PySSL_BEGIN_ALLOW_THREADS
1741 count = SSL_read(self->ssl, mem, len);
1742 err = SSL_get_error(self->ssl, count);
1743 PySSL_END_ALLOW_THREADS
1744 if (PyErr_CheckSignals())
1745 goto error;
1746 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001747 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001749 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1751 (SSL_get_shutdown(self->ssl) ==
1752 SSL_RECEIVED_SHUTDOWN))
1753 {
1754 count = 0;
1755 goto done;
1756 } else {
1757 sockstate = SOCKET_OPERATION_OK;
1758 }
1759 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001760 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 "The read operation timed out");
1762 goto error;
1763 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1764 break;
1765 }
1766 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1767 if (count <= 0) {
1768 PySSL_SetError(self, count, __FILE__, __LINE__);
1769 goto error;
1770 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001771
1772done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001773 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001775 _PyBytes_Resize(&dest, count);
1776 return dest;
1777 }
1778 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 PyBuffer_Release(&buf);
1780 return PyLong_FromLong(count);
1781 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001782
1783error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001784 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001785 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001786 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001787 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001790}
1791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001792PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001793"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001795Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001796
Antoine Pitrou152efa22010-05-16 18:19:27 +00001797static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001798{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 int err, ssl_err, sockstate, nonblocking;
1800 int zeros = 0;
1801 PySocketSockObject *sock
1802 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 /* Guard against closed socket */
1805 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1806 _setSSLError("Underlying socket connection gone",
1807 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1808 return NULL;
1809 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001810 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811
1812 /* Just in case the blocking state of the socket has been changed */
1813 nonblocking = (sock->sock_timeout >= 0.0);
1814 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1815 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1816
1817 while (1) {
1818 PySSL_BEGIN_ALLOW_THREADS
1819 /* Disable read-ahead so that unwrap can work correctly.
1820 * Otherwise OpenSSL might read in too much data,
1821 * eating clear text data that happens to be
1822 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001823 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 * function is used and the shutdown_seen_zero != 0
1825 * condition is met.
1826 */
1827 if (self->shutdown_seen_zero)
1828 SSL_set_read_ahead(self->ssl, 0);
1829 err = SSL_shutdown(self->ssl);
1830 PySSL_END_ALLOW_THREADS
1831 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1832 if (err > 0)
1833 break;
1834 if (err == 0) {
1835 /* Don't loop endlessly; instead preserve legacy
1836 behaviour of trying SSL_shutdown() only twice.
1837 This looks necessary for OpenSSL < 0.9.8m */
1838 if (++zeros > 1)
1839 break;
1840 /* Shutdown was sent, now try receiving */
1841 self->shutdown_seen_zero = 1;
1842 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001843 }
1844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 /* Possibly retry shutdown until timeout or failure */
1846 ssl_err = SSL_get_error(self->ssl, err);
1847 if (ssl_err == SSL_ERROR_WANT_READ)
1848 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1849 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1850 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1851 else
1852 break;
1853 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1854 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001855 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 "The read operation timed out");
1857 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001858 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001860 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 }
1862 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1863 PyErr_SetString(PySSLErrorObject,
1864 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001865 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 }
1867 else if (sockstate != SOCKET_OPERATION_OK)
1868 /* Retain the SSL error code */
1869 break;
1870 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001871
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001872 if (err < 0) {
1873 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001876 else
1877 /* It's already INCREF'ed */
1878 return (PyObject *) sock;
1879
1880error:
1881 Py_DECREF(sock);
1882 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001883}
1884
1885PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1886"shutdown(s) -> socket\n\
1887\n\
1888Does the SSL shutdown handshake with the remote end, and returns\n\
1889the underlying socket object.");
1890
Antoine Pitroud6494802011-07-21 01:11:30 +02001891#if HAVE_OPENSSL_FINISHED
1892static PyObject *
1893PySSL_tls_unique_cb(PySSLSocket *self)
1894{
1895 PyObject *retval = NULL;
1896 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001897 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001898
1899 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1900 /* if session is resumed XOR we are the client */
1901 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1902 }
1903 else {
1904 /* if a new session XOR we are the server */
1905 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1906 }
1907
1908 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001909 if (len == 0)
1910 Py_RETURN_NONE;
1911
1912 retval = PyBytes_FromStringAndSize(buf, len);
1913
1914 return retval;
1915}
1916
1917PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1918"tls_unique_cb() -> bytes\n\
1919\n\
1920Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1921\n\
1922If the TLS handshake is not yet complete, None is returned");
1923
1924#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001925
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001926static PyGetSetDef ssl_getsetlist[] = {
1927 {"context", (getter) PySSL_get_context,
1928 (setter) PySSL_set_context, PySSL_set_context_doc},
1929 {NULL}, /* sentinel */
1930};
1931
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001932static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1934 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1935 PySSL_SSLwrite_doc},
1936 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1937 PySSL_SSLread_doc},
1938 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1939 PySSL_SSLpending_doc},
1940 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1941 PySSL_peercert_doc},
1942 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001943#ifdef OPENSSL_NPN_NEGOTIATED
1944 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1945#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001946 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1948 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001949#if HAVE_OPENSSL_FINISHED
1950 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1951 PySSL_tls_unique_cb_doc},
1952#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954};
1955
Antoine Pitrou152efa22010-05-16 18:19:27 +00001956static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001958 "_ssl._SSLSocket", /*tp_name*/
1959 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 0, /*tp_itemsize*/
1961 /* methods */
1962 (destructor)PySSL_dealloc, /*tp_dealloc*/
1963 0, /*tp_print*/
1964 0, /*tp_getattr*/
1965 0, /*tp_setattr*/
1966 0, /*tp_reserved*/
1967 0, /*tp_repr*/
1968 0, /*tp_as_number*/
1969 0, /*tp_as_sequence*/
1970 0, /*tp_as_mapping*/
1971 0, /*tp_hash*/
1972 0, /*tp_call*/
1973 0, /*tp_str*/
1974 0, /*tp_getattro*/
1975 0, /*tp_setattro*/
1976 0, /*tp_as_buffer*/
1977 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1978 0, /*tp_doc*/
1979 0, /*tp_traverse*/
1980 0, /*tp_clear*/
1981 0, /*tp_richcompare*/
1982 0, /*tp_weaklistoffset*/
1983 0, /*tp_iter*/
1984 0, /*tp_iternext*/
1985 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001986 0, /*tp_members*/
1987 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001988};
1989
Antoine Pitrou152efa22010-05-16 18:19:27 +00001990
1991/*
1992 * _SSLContext objects
1993 */
1994
1995static PyObject *
1996context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1997{
1998 char *kwlist[] = {"protocol", NULL};
1999 PySSLContext *self;
2000 int proto_version = PY_SSL_VERSION_SSL23;
2001 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
Antoine Pitrou152efa22010-05-16 18:19:27 +00002053 /* Defaults */
2054 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01002055 SSL_CTX_set_options(self->ctx,
2056 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002057
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002058#define SID_CTX "Python"
2059 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2060 sizeof(SID_CTX));
2061#undef SID_CTX
2062
Antoine Pitrou152efa22010-05-16 18:19:27 +00002063 return (PyObject *)self;
2064}
2065
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002066static int
2067context_traverse(PySSLContext *self, visitproc visit, void *arg)
2068{
2069#ifndef OPENSSL_NO_TLSEXT
2070 Py_VISIT(self->set_hostname);
2071#endif
2072 return 0;
2073}
2074
2075static int
2076context_clear(PySSLContext *self)
2077{
2078#ifndef OPENSSL_NO_TLSEXT
2079 Py_CLEAR(self->set_hostname);
2080#endif
2081 return 0;
2082}
2083
Antoine Pitrou152efa22010-05-16 18:19:27 +00002084static void
2085context_dealloc(PySSLContext *self)
2086{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002087 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002088 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002089#ifdef OPENSSL_NPN_NEGOTIATED
2090 PyMem_Free(self->npn_protocols);
2091#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002092 Py_TYPE(self)->tp_free(self);
2093}
2094
2095static PyObject *
2096set_ciphers(PySSLContext *self, PyObject *args)
2097{
2098 int ret;
2099 const char *cipherlist;
2100
2101 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2102 return NULL;
2103 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2104 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002105 /* Clearing the error queue is necessary on some OpenSSL versions,
2106 otherwise the error will be reported again when another SSL call
2107 is done. */
2108 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002109 PyErr_SetString(PySSLErrorObject,
2110 "No cipher can be selected.");
2111 return NULL;
2112 }
2113 Py_RETURN_NONE;
2114}
2115
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002116#ifdef OPENSSL_NPN_NEGOTIATED
2117/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2118static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002119_advertiseNPN_cb(SSL *s,
2120 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002121 void *args)
2122{
2123 PySSLContext *ssl_ctx = (PySSLContext *) args;
2124
2125 if (ssl_ctx->npn_protocols == NULL) {
2126 *data = (unsigned char *) "";
2127 *len = 0;
2128 } else {
2129 *data = (unsigned char *) ssl_ctx->npn_protocols;
2130 *len = ssl_ctx->npn_protocols_len;
2131 }
2132
2133 return SSL_TLSEXT_ERR_OK;
2134}
2135/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2136static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002137_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002138 unsigned char **out, unsigned char *outlen,
2139 const unsigned char *server, unsigned int server_len,
2140 void *args)
2141{
2142 PySSLContext *ssl_ctx = (PySSLContext *) args;
2143
2144 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2145 int client_len;
2146
2147 if (client == NULL) {
2148 client = (unsigned char *) "";
2149 client_len = 0;
2150 } else {
2151 client_len = ssl_ctx->npn_protocols_len;
2152 }
2153
2154 SSL_select_next_proto(out, outlen,
2155 server, server_len,
2156 client, client_len);
2157
2158 return SSL_TLSEXT_ERR_OK;
2159}
2160#endif
2161
2162static PyObject *
2163_set_npn_protocols(PySSLContext *self, PyObject *args)
2164{
2165#ifdef OPENSSL_NPN_NEGOTIATED
2166 Py_buffer protos;
2167
2168 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2169 return NULL;
2170
Christian Heimes5cb31c92012-09-20 12:42:54 +02002171 if (self->npn_protocols != NULL) {
2172 PyMem_Free(self->npn_protocols);
2173 }
2174
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002175 self->npn_protocols = PyMem_Malloc(protos.len);
2176 if (self->npn_protocols == NULL) {
2177 PyBuffer_Release(&protos);
2178 return PyErr_NoMemory();
2179 }
2180 memcpy(self->npn_protocols, protos.buf, protos.len);
2181 self->npn_protocols_len = (int) protos.len;
2182
2183 /* set both server and client callbacks, because the context can
2184 * be used to create both types of sockets */
2185 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2186 _advertiseNPN_cb,
2187 self);
2188 SSL_CTX_set_next_proto_select_cb(self->ctx,
2189 _selectNPN_cb,
2190 self);
2191
2192 PyBuffer_Release(&protos);
2193 Py_RETURN_NONE;
2194#else
2195 PyErr_SetString(PyExc_NotImplementedError,
2196 "The NPN extension requires OpenSSL 1.0.1 or later.");
2197 return NULL;
2198#endif
2199}
2200
Antoine Pitrou152efa22010-05-16 18:19:27 +00002201static PyObject *
2202get_verify_mode(PySSLContext *self, void *c)
2203{
2204 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2205 case SSL_VERIFY_NONE:
2206 return PyLong_FromLong(PY_SSL_CERT_NONE);
2207 case SSL_VERIFY_PEER:
2208 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2209 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2210 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2211 }
2212 PyErr_SetString(PySSLErrorObject,
2213 "invalid return value from SSL_CTX_get_verify_mode");
2214 return NULL;
2215}
2216
2217static int
2218set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2219{
2220 int n, mode;
2221 if (!PyArg_Parse(arg, "i", &n))
2222 return -1;
2223 if (n == PY_SSL_CERT_NONE)
2224 mode = SSL_VERIFY_NONE;
2225 else if (n == PY_SSL_CERT_OPTIONAL)
2226 mode = SSL_VERIFY_PEER;
2227 else if (n == PY_SSL_CERT_REQUIRED)
2228 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2229 else {
2230 PyErr_SetString(PyExc_ValueError,
2231 "invalid value for verify_mode");
2232 return -1;
2233 }
2234 SSL_CTX_set_verify(self->ctx, mode, NULL);
2235 return 0;
2236}
2237
Christian Heimes2427b502013-11-23 11:24:32 +01002238#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002239static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002240get_verify_flags(PySSLContext *self, void *c)
2241{
2242 X509_STORE *store;
2243 unsigned long flags;
2244
2245 store = SSL_CTX_get_cert_store(self->ctx);
2246 flags = X509_VERIFY_PARAM_get_flags(store->param);
2247 return PyLong_FromUnsignedLong(flags);
2248}
2249
2250static int
2251set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2252{
2253 X509_STORE *store;
2254 unsigned long new_flags, flags, set, clear;
2255
2256 if (!PyArg_Parse(arg, "k", &new_flags))
2257 return -1;
2258 store = SSL_CTX_get_cert_store(self->ctx);
2259 flags = X509_VERIFY_PARAM_get_flags(store->param);
2260 clear = flags & ~new_flags;
2261 set = ~flags & new_flags;
2262 if (clear) {
2263 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2264 _setSSLError(NULL, 0, __FILE__, __LINE__);
2265 return -1;
2266 }
2267 }
2268 if (set) {
2269 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2270 _setSSLError(NULL, 0, __FILE__, __LINE__);
2271 return -1;
2272 }
2273 }
2274 return 0;
2275}
Christian Heimes2427b502013-11-23 11:24:32 +01002276#endif
Christian Heimes22587792013-11-21 23:56:13 +01002277
2278static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002279get_options(PySSLContext *self, void *c)
2280{
2281 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2282}
2283
2284static int
2285set_options(PySSLContext *self, PyObject *arg, void *c)
2286{
2287 long new_opts, opts, set, clear;
2288 if (!PyArg_Parse(arg, "l", &new_opts))
2289 return -1;
2290 opts = SSL_CTX_get_options(self->ctx);
2291 clear = opts & ~new_opts;
2292 set = ~opts & new_opts;
2293 if (clear) {
2294#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2295 SSL_CTX_clear_options(self->ctx, clear);
2296#else
2297 PyErr_SetString(PyExc_ValueError,
2298 "can't clear options before OpenSSL 0.9.8m");
2299 return -1;
2300#endif
2301 }
2302 if (set)
2303 SSL_CTX_set_options(self->ctx, set);
2304 return 0;
2305}
2306
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002307typedef struct {
2308 PyThreadState *thread_state;
2309 PyObject *callable;
2310 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002311 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002312 int error;
2313} _PySSLPasswordInfo;
2314
2315static int
2316_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2317 const char *bad_type_error)
2318{
2319 /* Set the password and size fields of a _PySSLPasswordInfo struct
2320 from a unicode, bytes, or byte array object.
2321 The password field will be dynamically allocated and must be freed
2322 by the caller */
2323 PyObject *password_bytes = NULL;
2324 const char *data = NULL;
2325 Py_ssize_t size;
2326
2327 if (PyUnicode_Check(password)) {
2328 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2329 if (!password_bytes) {
2330 goto error;
2331 }
2332 data = PyBytes_AS_STRING(password_bytes);
2333 size = PyBytes_GET_SIZE(password_bytes);
2334 } else if (PyBytes_Check(password)) {
2335 data = PyBytes_AS_STRING(password);
2336 size = PyBytes_GET_SIZE(password);
2337 } else if (PyByteArray_Check(password)) {
2338 data = PyByteArray_AS_STRING(password);
2339 size = PyByteArray_GET_SIZE(password);
2340 } else {
2341 PyErr_SetString(PyExc_TypeError, bad_type_error);
2342 goto error;
2343 }
2344
Victor Stinner9ee02032013-06-23 15:08:23 +02002345 if (size > (Py_ssize_t)INT_MAX) {
2346 PyErr_Format(PyExc_ValueError,
2347 "password cannot be longer than %d bytes", INT_MAX);
2348 goto error;
2349 }
2350
Victor Stinner11ebff22013-07-07 17:07:52 +02002351 PyMem_Free(pw_info->password);
2352 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002353 if (!pw_info->password) {
2354 PyErr_SetString(PyExc_MemoryError,
2355 "unable to allocate password buffer");
2356 goto error;
2357 }
2358 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002359 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002360
2361 Py_XDECREF(password_bytes);
2362 return 1;
2363
2364error:
2365 Py_XDECREF(password_bytes);
2366 return 0;
2367}
2368
2369static int
2370_password_callback(char *buf, int size, int rwflag, void *userdata)
2371{
2372 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2373 PyObject *fn_ret = NULL;
2374
2375 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2376
2377 if (pw_info->callable) {
2378 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2379 if (!fn_ret) {
2380 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2381 core python API, so we could use it to add a frame here */
2382 goto error;
2383 }
2384
2385 if (!_pwinfo_set(pw_info, fn_ret,
2386 "password callback must return a string")) {
2387 goto error;
2388 }
2389 Py_CLEAR(fn_ret);
2390 }
2391
2392 if (pw_info->size > size) {
2393 PyErr_Format(PyExc_ValueError,
2394 "password cannot be longer than %d bytes", size);
2395 goto error;
2396 }
2397
2398 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2399 memcpy(buf, pw_info->password, pw_info->size);
2400 return pw_info->size;
2401
2402error:
2403 Py_XDECREF(fn_ret);
2404 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2405 pw_info->error = 1;
2406 return -1;
2407}
2408
Antoine Pitroub5218772010-05-21 09:56:06 +00002409static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002410load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2411{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002412 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2413 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002415 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2416 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2417 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002418 int r;
2419
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002420 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002421 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002422 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002423 "O|OO:load_cert_chain", kwlist,
2424 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002425 return NULL;
2426 if (keyfile == Py_None)
2427 keyfile = NULL;
2428 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2429 PyErr_SetString(PyExc_TypeError,
2430 "certfile should be a valid filesystem path");
2431 return NULL;
2432 }
2433 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2434 PyErr_SetString(PyExc_TypeError,
2435 "keyfile should be a valid filesystem path");
2436 goto error;
2437 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002438 if (password && password != Py_None) {
2439 if (PyCallable_Check(password)) {
2440 pw_info.callable = password;
2441 } else if (!_pwinfo_set(&pw_info, password,
2442 "password should be a string or callable")) {
2443 goto error;
2444 }
2445 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2446 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2447 }
2448 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002449 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2450 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002451 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002452 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002453 if (pw_info.error) {
2454 ERR_clear_error();
2455 /* the password callback has already set the error information */
2456 }
2457 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002458 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002459 PyErr_SetFromErrno(PyExc_IOError);
2460 }
2461 else {
2462 _setSSLError(NULL, 0, __FILE__, __LINE__);
2463 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002464 goto error;
2465 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002466 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002467 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002468 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2469 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002470 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2471 Py_CLEAR(keyfile_bytes);
2472 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002473 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002474 if (pw_info.error) {
2475 ERR_clear_error();
2476 /* the password callback has already set the error information */
2477 }
2478 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002479 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002480 PyErr_SetFromErrno(PyExc_IOError);
2481 }
2482 else {
2483 _setSSLError(NULL, 0, __FILE__, __LINE__);
2484 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002485 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002486 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002487 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002488 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002489 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002490 if (r != 1) {
2491 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002492 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002493 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002494 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2495 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002496 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002497 Py_RETURN_NONE;
2498
2499error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002500 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2501 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002502 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002503 Py_XDECREF(keyfile_bytes);
2504 Py_XDECREF(certfile_bytes);
2505 return NULL;
2506}
2507
Christian Heimesefff7062013-11-21 03:35:02 +01002508/* internal helper function, returns -1 on error
2509 */
2510static int
2511_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2512 int filetype)
2513{
2514 BIO *biobuf = NULL;
2515 X509_STORE *store;
2516 int retval = 0, err, loaded = 0;
2517
2518 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2519
2520 if (len <= 0) {
2521 PyErr_SetString(PyExc_ValueError,
2522 "Empty certificate data");
2523 return -1;
2524 } else if (len > INT_MAX) {
2525 PyErr_SetString(PyExc_OverflowError,
2526 "Certificate data is too long.");
2527 return -1;
2528 }
2529
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002530 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002531 if (biobuf == NULL) {
2532 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2533 return -1;
2534 }
2535
2536 store = SSL_CTX_get_cert_store(self->ctx);
2537 assert(store != NULL);
2538
2539 while (1) {
2540 X509 *cert = NULL;
2541 int r;
2542
2543 if (filetype == SSL_FILETYPE_ASN1) {
2544 cert = d2i_X509_bio(biobuf, NULL);
2545 } else {
2546 cert = PEM_read_bio_X509(biobuf, NULL,
2547 self->ctx->default_passwd_callback,
2548 self->ctx->default_passwd_callback_userdata);
2549 }
2550 if (cert == NULL) {
2551 break;
2552 }
2553 r = X509_STORE_add_cert(store, cert);
2554 X509_free(cert);
2555 if (!r) {
2556 err = ERR_peek_last_error();
2557 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2558 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2559 /* cert already in hash table, not an error */
2560 ERR_clear_error();
2561 } else {
2562 break;
2563 }
2564 }
2565 loaded++;
2566 }
2567
2568 err = ERR_peek_last_error();
2569 if ((filetype == SSL_FILETYPE_ASN1) &&
2570 (loaded > 0) &&
2571 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2572 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2573 /* EOF ASN1 file, not an error */
2574 ERR_clear_error();
2575 retval = 0;
2576 } else if ((filetype == SSL_FILETYPE_PEM) &&
2577 (loaded > 0) &&
2578 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2579 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2580 /* EOF PEM file, not an error */
2581 ERR_clear_error();
2582 retval = 0;
2583 } else {
2584 _setSSLError(NULL, 0, __FILE__, __LINE__);
2585 retval = -1;
2586 }
2587
2588 BIO_free(biobuf);
2589 return retval;
2590}
2591
2592
Antoine Pitrou152efa22010-05-16 18:19:27 +00002593static PyObject *
2594load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2595{
Christian Heimesefff7062013-11-21 03:35:02 +01002596 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2597 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002598 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2599 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002600 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002601
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002602 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002603 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002604 "|OOO:load_verify_locations", kwlist,
2605 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002606 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002607
Antoine Pitrou152efa22010-05-16 18:19:27 +00002608 if (cafile == Py_None)
2609 cafile = NULL;
2610 if (capath == Py_None)
2611 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002612 if (cadata == Py_None)
2613 cadata = NULL;
2614
2615 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002616 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002617 "cafile, capath and cadata cannot be all omitted");
2618 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619 }
2620 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2621 PyErr_SetString(PyExc_TypeError,
2622 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002623 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002624 }
2625 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002626 PyErr_SetString(PyExc_TypeError,
2627 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002628 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002629 }
Christian Heimesefff7062013-11-21 03:35:02 +01002630
2631 /* validata cadata type and load cadata */
2632 if (cadata) {
2633 Py_buffer buf;
2634 PyObject *cadata_ascii = NULL;
2635
2636 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2637 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2638 PyBuffer_Release(&buf);
2639 PyErr_SetString(PyExc_TypeError,
2640 "cadata should be a contiguous buffer with "
2641 "a single dimension");
2642 goto error;
2643 }
2644 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2645 PyBuffer_Release(&buf);
2646 if (r == -1) {
2647 goto error;
2648 }
2649 } else {
2650 PyErr_Clear();
2651 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2652 if (cadata_ascii == NULL) {
2653 PyErr_SetString(PyExc_TypeError,
2654 "cadata should be a ASCII string or a "
2655 "bytes-like object");
2656 goto error;
2657 }
2658 r = _add_ca_certs(self,
2659 PyBytes_AS_STRING(cadata_ascii),
2660 PyBytes_GET_SIZE(cadata_ascii),
2661 SSL_FILETYPE_PEM);
2662 Py_DECREF(cadata_ascii);
2663 if (r == -1) {
2664 goto error;
2665 }
2666 }
2667 }
2668
2669 /* load cafile or capath */
2670 if (cafile || capath) {
2671 if (cafile)
2672 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2673 if (capath)
2674 capath_buf = PyBytes_AS_STRING(capath_bytes);
2675 PySSL_BEGIN_ALLOW_THREADS
2676 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2677 PySSL_END_ALLOW_THREADS
2678 if (r != 1) {
2679 ok = 0;
2680 if (errno != 0) {
2681 ERR_clear_error();
2682 PyErr_SetFromErrno(PyExc_IOError);
2683 }
2684 else {
2685 _setSSLError(NULL, 0, __FILE__, __LINE__);
2686 }
2687 goto error;
2688 }
2689 }
2690 goto end;
2691
2692 error:
2693 ok = 0;
2694 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002695 Py_XDECREF(cafile_bytes);
2696 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002697 if (ok) {
2698 Py_RETURN_NONE;
2699 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002700 return NULL;
2701 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002702}
2703
2704static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002705load_dh_params(PySSLContext *self, PyObject *filepath)
2706{
2707 FILE *f;
2708 DH *dh;
2709
Victor Stinnerdaf45552013-08-28 00:53:59 +02002710 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002711 if (f == NULL) {
2712 if (!PyErr_Occurred())
2713 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2714 return NULL;
2715 }
2716 errno = 0;
2717 PySSL_BEGIN_ALLOW_THREADS
2718 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002719 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002720 PySSL_END_ALLOW_THREADS
2721 if (dh == NULL) {
2722 if (errno != 0) {
2723 ERR_clear_error();
2724 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2725 }
2726 else {
2727 _setSSLError(NULL, 0, __FILE__, __LINE__);
2728 }
2729 return NULL;
2730 }
2731 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2732 _setSSLError(NULL, 0, __FILE__, __LINE__);
2733 DH_free(dh);
2734 Py_RETURN_NONE;
2735}
2736
2737static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002738context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2739{
Antoine Pitroud5323212010-10-22 18:19:07 +00002740 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002741 PySocketSockObject *sock;
2742 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002743 char *hostname = NULL;
2744 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745
Antoine Pitroud5323212010-10-22 18:19:07 +00002746 /* server_hostname is either None (or absent), or to be encoded
2747 using the idna encoding. */
2748 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002749 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002750 &sock, &server_side,
2751 Py_TYPE(Py_None), &hostname_obj)) {
2752 PyErr_Clear();
2753 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2754 PySocketModule.Sock_Type,
2755 &sock, &server_side,
2756 "idna", &hostname))
2757 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002758#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002759 PyMem_Free(hostname);
2760 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2761 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002763#endif
2764 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002766 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002767 hostname);
2768 if (hostname != NULL)
2769 PyMem_Free(hostname);
2770 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002771}
2772
Antoine Pitroub0182c82010-10-12 20:09:02 +00002773static PyObject *
2774session_stats(PySSLContext *self, PyObject *unused)
2775{
2776 int r;
2777 PyObject *value, *stats = PyDict_New();
2778 if (!stats)
2779 return NULL;
2780
2781#define ADD_STATS(SSL_NAME, KEY_NAME) \
2782 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2783 if (value == NULL) \
2784 goto error; \
2785 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2786 Py_DECREF(value); \
2787 if (r < 0) \
2788 goto error;
2789
2790 ADD_STATS(number, "number");
2791 ADD_STATS(connect, "connect");
2792 ADD_STATS(connect_good, "connect_good");
2793 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2794 ADD_STATS(accept, "accept");
2795 ADD_STATS(accept_good, "accept_good");
2796 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2797 ADD_STATS(accept, "accept");
2798 ADD_STATS(hits, "hits");
2799 ADD_STATS(misses, "misses");
2800 ADD_STATS(timeouts, "timeouts");
2801 ADD_STATS(cache_full, "cache_full");
2802
2803#undef ADD_STATS
2804
2805 return stats;
2806
2807error:
2808 Py_DECREF(stats);
2809 return NULL;
2810}
2811
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002812static PyObject *
2813set_default_verify_paths(PySSLContext *self, PyObject *unused)
2814{
2815 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2816 _setSSLError(NULL, 0, __FILE__, __LINE__);
2817 return NULL;
2818 }
2819 Py_RETURN_NONE;
2820}
2821
Antoine Pitrou501da612011-12-21 09:27:41 +01002822#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002823static PyObject *
2824set_ecdh_curve(PySSLContext *self, PyObject *name)
2825{
2826 PyObject *name_bytes;
2827 int nid;
2828 EC_KEY *key;
2829
2830 if (!PyUnicode_FSConverter(name, &name_bytes))
2831 return NULL;
2832 assert(PyBytes_Check(name_bytes));
2833 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2834 Py_DECREF(name_bytes);
2835 if (nid == 0) {
2836 PyErr_Format(PyExc_ValueError,
2837 "unknown elliptic curve name %R", name);
2838 return NULL;
2839 }
2840 key = EC_KEY_new_by_curve_name(nid);
2841 if (key == NULL) {
2842 _setSSLError(NULL, 0, __FILE__, __LINE__);
2843 return NULL;
2844 }
2845 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2846 EC_KEY_free(key);
2847 Py_RETURN_NONE;
2848}
Antoine Pitrou501da612011-12-21 09:27:41 +01002849#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002850
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002851#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002852static int
2853_servername_callback(SSL *s, int *al, void *args)
2854{
2855 int ret;
2856 PySSLContext *ssl_ctx = (PySSLContext *) args;
2857 PySSLSocket *ssl;
2858 PyObject *servername_o;
2859 PyObject *servername_idna;
2860 PyObject *result;
2861 /* The high-level ssl.SSLSocket object */
2862 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002863 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002864#ifdef WITH_THREAD
2865 PyGILState_STATE gstate = PyGILState_Ensure();
2866#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002867
2868 if (ssl_ctx->set_hostname == NULL) {
2869 /* remove race condition in this the call back while if removing the
2870 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002871#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002872 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002873#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002874 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002875 }
2876
2877 ssl = SSL_get_app_data(s);
2878 assert(PySSLSocket_Check(ssl));
2879 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2880 Py_INCREF(ssl_socket);
2881 if (ssl_socket == Py_None) {
2882 goto error;
2883 }
Victor Stinner7e001512013-06-25 00:44:31 +02002884
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002885 if (servername == NULL) {
2886 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2887 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002888 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002889 else {
2890 servername_o = PyBytes_FromString(servername);
2891 if (servername_o == NULL) {
2892 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2893 goto error;
2894 }
2895 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2896 if (servername_idna == NULL) {
2897 PyErr_WriteUnraisable(servername_o);
2898 Py_DECREF(servername_o);
2899 goto error;
2900 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002901 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002902 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2903 servername_idna, ssl_ctx, NULL);
2904 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002905 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002906 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002907
2908 if (result == NULL) {
2909 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2910 *al = SSL_AD_HANDSHAKE_FAILURE;
2911 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2912 }
2913 else {
2914 if (result != Py_None) {
2915 *al = (int) PyLong_AsLong(result);
2916 if (PyErr_Occurred()) {
2917 PyErr_WriteUnraisable(result);
2918 *al = SSL_AD_INTERNAL_ERROR;
2919 }
2920 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2921 }
2922 else {
2923 ret = SSL_TLSEXT_ERR_OK;
2924 }
2925 Py_DECREF(result);
2926 }
2927
Stefan Krah20d60802013-01-17 17:07:17 +01002928#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002929 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002930#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002931 return ret;
2932
2933error:
2934 Py_DECREF(ssl_socket);
2935 *al = SSL_AD_INTERNAL_ERROR;
2936 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002937#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002938 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002939#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002940 return ret;
2941}
Antoine Pitroua5963382013-03-30 16:39:00 +01002942#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002943
2944PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2945"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002946\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002947This sets a callback that will be called when a server name is provided by\n\
2948the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002949\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002950If the argument is None then the callback is disabled. The method is called\n\
2951with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002952See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002953
2954static PyObject *
2955set_servername_callback(PySSLContext *self, PyObject *args)
2956{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002957#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002958 PyObject *cb;
2959
2960 if (!PyArg_ParseTuple(args, "O", &cb))
2961 return NULL;
2962
2963 Py_CLEAR(self->set_hostname);
2964 if (cb == Py_None) {
2965 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2966 }
2967 else {
2968 if (!PyCallable_Check(cb)) {
2969 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2970 PyErr_SetString(PyExc_TypeError,
2971 "not a callable object");
2972 return NULL;
2973 }
2974 Py_INCREF(cb);
2975 self->set_hostname = cb;
2976 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2977 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2978 }
2979 Py_RETURN_NONE;
2980#else
2981 PyErr_SetString(PyExc_NotImplementedError,
2982 "The TLS extension servername callback, "
2983 "SSL_CTX_set_tlsext_servername_callback, "
2984 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002985 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002986#endif
2987}
2988
Christian Heimes9a5395a2013-06-17 15:44:12 +02002989PyDoc_STRVAR(PySSL_get_stats_doc,
2990"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2991\n\
2992Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2993CA extension and certificate revocation lists inside the context's cert\n\
2994store.\n\
2995NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2996been used at least once.");
2997
2998static PyObject *
2999cert_store_stats(PySSLContext *self)
3000{
3001 X509_STORE *store;
3002 X509_OBJECT *obj;
3003 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3004
3005 store = SSL_CTX_get_cert_store(self->ctx);
3006 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3007 obj = sk_X509_OBJECT_value(store->objs, i);
3008 switch (obj->type) {
3009 case X509_LU_X509:
3010 x509++;
3011 if (X509_check_ca(obj->data.x509)) {
3012 ca++;
3013 }
3014 break;
3015 case X509_LU_CRL:
3016 crl++;
3017 break;
3018 case X509_LU_PKEY:
3019 pkey++;
3020 break;
3021 default:
3022 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3023 * As far as I can tell they are internal states and never
3024 * stored in a cert store */
3025 break;
3026 }
3027 }
3028 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3029 "x509_ca", ca);
3030}
3031
3032PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003033"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003034\n\
3035Returns a list of dicts with information of loaded CA certs. If the\n\
3036optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3037NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3038been used at least once.");
3039
3040static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003041get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003042{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003043 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003044 X509_STORE *store;
3045 PyObject *ci = NULL, *rlist = NULL;
3046 int i;
3047 int binary_mode = 0;
3048
Christian Heimesf22e8e52013-11-22 02:22:51 +01003049 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3050 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003051 return NULL;
3052 }
3053
3054 if ((rlist = PyList_New(0)) == NULL) {
3055 return NULL;
3056 }
3057
3058 store = SSL_CTX_get_cert_store(self->ctx);
3059 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3060 X509_OBJECT *obj;
3061 X509 *cert;
3062
3063 obj = sk_X509_OBJECT_value(store->objs, i);
3064 if (obj->type != X509_LU_X509) {
3065 /* not a x509 cert */
3066 continue;
3067 }
3068 /* CA for any purpose */
3069 cert = obj->data.x509;
3070 if (!X509_check_ca(cert)) {
3071 continue;
3072 }
3073 if (binary_mode) {
3074 ci = _certificate_to_der(cert);
3075 } else {
3076 ci = _decode_certificate(cert);
3077 }
3078 if (ci == NULL) {
3079 goto error;
3080 }
3081 if (PyList_Append(rlist, ci) == -1) {
3082 goto error;
3083 }
3084 Py_CLEAR(ci);
3085 }
3086 return rlist;
3087
3088 error:
3089 Py_XDECREF(ci);
3090 Py_XDECREF(rlist);
3091 return NULL;
3092}
3093
3094
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00003096 {"options", (getter) get_options,
3097 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003098#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003099 {"verify_flags", (getter) get_verify_flags,
3100 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003101#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003102 {"verify_mode", (getter) get_verify_mode,
3103 (setter) set_verify_mode, NULL},
3104 {NULL}, /* sentinel */
3105};
3106
3107static struct PyMethodDef context_methods[] = {
3108 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3109 METH_VARARGS | METH_KEYWORDS, NULL},
3110 {"set_ciphers", (PyCFunction) set_ciphers,
3111 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003112 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3113 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003114 {"load_cert_chain", (PyCFunction) load_cert_chain,
3115 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003116 {"load_dh_params", (PyCFunction) load_dh_params,
3117 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003118 {"load_verify_locations", (PyCFunction) load_verify_locations,
3119 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003120 {"session_stats", (PyCFunction) session_stats,
3121 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003122 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3123 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003124#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003125 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3126 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003127#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003128 {"set_servername_callback", (PyCFunction) set_servername_callback,
3129 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003130 {"cert_store_stats", (PyCFunction) cert_store_stats,
3131 METH_NOARGS, PySSL_get_stats_doc},
3132 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003133 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003134 {NULL, NULL} /* sentinel */
3135};
3136
3137static PyTypeObject PySSLContext_Type = {
3138 PyVarObject_HEAD_INIT(NULL, 0)
3139 "_ssl._SSLContext", /*tp_name*/
3140 sizeof(PySSLContext), /*tp_basicsize*/
3141 0, /*tp_itemsize*/
3142 (destructor)context_dealloc, /*tp_dealloc*/
3143 0, /*tp_print*/
3144 0, /*tp_getattr*/
3145 0, /*tp_setattr*/
3146 0, /*tp_reserved*/
3147 0, /*tp_repr*/
3148 0, /*tp_as_number*/
3149 0, /*tp_as_sequence*/
3150 0, /*tp_as_mapping*/
3151 0, /*tp_hash*/
3152 0, /*tp_call*/
3153 0, /*tp_str*/
3154 0, /*tp_getattro*/
3155 0, /*tp_setattro*/
3156 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003157 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003158 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003159 (traverseproc) context_traverse, /*tp_traverse*/
3160 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003161 0, /*tp_richcompare*/
3162 0, /*tp_weaklistoffset*/
3163 0, /*tp_iter*/
3164 0, /*tp_iternext*/
3165 context_methods, /*tp_methods*/
3166 0, /*tp_members*/
3167 context_getsetlist, /*tp_getset*/
3168 0, /*tp_base*/
3169 0, /*tp_dict*/
3170 0, /*tp_descr_get*/
3171 0, /*tp_descr_set*/
3172 0, /*tp_dictoffset*/
3173 0, /*tp_init*/
3174 0, /*tp_alloc*/
3175 context_new, /*tp_new*/
3176};
3177
3178
3179
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003180#ifdef HAVE_OPENSSL_RAND
3181
3182/* helper routines for seeding the SSL PRNG */
3183static PyObject *
3184PySSL_RAND_add(PyObject *self, PyObject *args)
3185{
3186 char *buf;
3187 int len;
3188 double entropy;
3189
3190 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003191 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003192 RAND_add(buf, len, entropy);
3193 Py_INCREF(Py_None);
3194 return Py_None;
3195}
3196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003197PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003198"RAND_add(string, entropy)\n\
3199\n\
3200Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003201bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003202
3203static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003204PySSL_RAND(int len, int pseudo)
3205{
3206 int ok;
3207 PyObject *bytes;
3208 unsigned long err;
3209 const char *errstr;
3210 PyObject *v;
3211
3212 bytes = PyBytes_FromStringAndSize(NULL, len);
3213 if (bytes == NULL)
3214 return NULL;
3215 if (pseudo) {
3216 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3217 if (ok == 0 || ok == 1)
3218 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3219 }
3220 else {
3221 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3222 if (ok == 1)
3223 return bytes;
3224 }
3225 Py_DECREF(bytes);
3226
3227 err = ERR_get_error();
3228 errstr = ERR_reason_error_string(err);
3229 v = Py_BuildValue("(ks)", err, errstr);
3230 if (v != NULL) {
3231 PyErr_SetObject(PySSLErrorObject, v);
3232 Py_DECREF(v);
3233 }
3234 return NULL;
3235}
3236
3237static PyObject *
3238PySSL_RAND_bytes(PyObject *self, PyObject *args)
3239{
3240 int len;
3241 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3242 return NULL;
3243 return PySSL_RAND(len, 0);
3244}
3245
3246PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3247"RAND_bytes(n) -> bytes\n\
3248\n\
3249Generate n cryptographically strong pseudo-random bytes.");
3250
3251static PyObject *
3252PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3253{
3254 int len;
3255 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3256 return NULL;
3257 return PySSL_RAND(len, 1);
3258}
3259
3260PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3261"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3262\n\
3263Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3264generated are cryptographically strong.");
3265
3266static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003267PySSL_RAND_status(PyObject *self)
3268{
Christian Heimes217cfd12007-12-02 14:31:20 +00003269 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003270}
3271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003272PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003273"RAND_status() -> 0 or 1\n\
3274\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003275Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3276It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3277using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003278
3279static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003280PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003281{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003282 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003283 int bytes;
3284
Jesus Ceac8754a12012-09-11 02:00:58 +02003285 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003286 PyUnicode_FSConverter, &path))
3287 return NULL;
3288
3289 bytes = RAND_egd(PyBytes_AsString(path));
3290 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003291 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003292 PyErr_SetString(PySSLErrorObject,
3293 "EGD connection failed or EGD did not return "
3294 "enough data to seed the PRNG");
3295 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003296 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003297 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003298}
3299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003300PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003301"RAND_egd(path) -> bytes\n\
3302\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003303Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3304Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003305fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003306
Christian Heimesf77b4b22013-08-21 13:26:05 +02003307#endif /* HAVE_OPENSSL_RAND */
3308
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003309
Christian Heimes6d7ad132013-06-09 18:02:55 +02003310PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3311"get_default_verify_paths() -> tuple\n\
3312\n\
3313Return search paths and environment vars that are used by SSLContext's\n\
3314set_default_verify_paths() to load default CAs. The values are\n\
3315'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3316
3317static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003318PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003319{
3320 PyObject *ofile_env = NULL;
3321 PyObject *ofile = NULL;
3322 PyObject *odir_env = NULL;
3323 PyObject *odir = NULL;
3324
3325#define convert(info, target) { \
3326 const char *tmp = (info); \
3327 target = NULL; \
3328 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3329 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3330 target = PyBytes_FromString(tmp); } \
3331 if (!target) goto error; \
3332 } while(0)
3333
3334 convert(X509_get_default_cert_file_env(), ofile_env);
3335 convert(X509_get_default_cert_file(), ofile);
3336 convert(X509_get_default_cert_dir_env(), odir_env);
3337 convert(X509_get_default_cert_dir(), odir);
3338#undef convert
3339
Christian Heimes200bb1b2013-06-14 15:14:29 +02003340 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003341
3342 error:
3343 Py_XDECREF(ofile_env);
3344 Py_XDECREF(ofile);
3345 Py_XDECREF(odir_env);
3346 Py_XDECREF(odir);
3347 return NULL;
3348}
3349
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003350static PyObject*
3351asn1obj2py(ASN1_OBJECT *obj)
3352{
3353 int nid;
3354 const char *ln, *sn;
3355 char buf[100];
3356 int buflen;
3357
3358 nid = OBJ_obj2nid(obj);
3359 if (nid == NID_undef) {
3360 PyErr_Format(PyExc_ValueError, "Unknown object");
3361 return NULL;
3362 }
3363 sn = OBJ_nid2sn(nid);
3364 ln = OBJ_nid2ln(nid);
3365 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3366 if (buflen < 0) {
3367 _setSSLError(NULL, 0, __FILE__, __LINE__);
3368 return NULL;
3369 }
3370 if (buflen) {
3371 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3372 } else {
3373 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3374 }
3375}
3376
3377PyDoc_STRVAR(PySSL_txt2obj_doc,
3378"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3379\n\
3380Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3381objects are looked up by OID. With name=True short and long name are also\n\
3382matched.");
3383
3384static PyObject*
3385PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3386{
3387 char *kwlist[] = {"txt", "name", NULL};
3388 PyObject *result = NULL;
3389 char *txt;
3390 int name = 0;
3391 ASN1_OBJECT *obj;
3392
3393 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3394 kwlist, &txt, &name)) {
3395 return NULL;
3396 }
3397 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3398 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003399 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003400 return NULL;
3401 }
3402 result = asn1obj2py(obj);
3403 ASN1_OBJECT_free(obj);
3404 return result;
3405}
3406
3407PyDoc_STRVAR(PySSL_nid2obj_doc,
3408"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3409\n\
3410Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3411
3412static PyObject*
3413PySSL_nid2obj(PyObject *self, PyObject *args)
3414{
3415 PyObject *result = NULL;
3416 int nid;
3417 ASN1_OBJECT *obj;
3418
3419 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3420 return NULL;
3421 }
3422 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003423 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003424 return NULL;
3425 }
3426 obj = OBJ_nid2obj(nid);
3427 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003428 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003429 return NULL;
3430 }
3431 result = asn1obj2py(obj);
3432 ASN1_OBJECT_free(obj);
3433 return result;
3434}
3435
Christian Heimes46bebee2013-06-09 19:03:31 +02003436#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003437
3438static PyObject*
3439certEncodingType(DWORD encodingType)
3440{
3441 static PyObject *x509_asn = NULL;
3442 static PyObject *pkcs_7_asn = NULL;
3443
3444 if (x509_asn == NULL) {
3445 x509_asn = PyUnicode_InternFromString("x509_asn");
3446 if (x509_asn == NULL)
3447 return NULL;
3448 }
3449 if (pkcs_7_asn == NULL) {
3450 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3451 if (pkcs_7_asn == NULL)
3452 return NULL;
3453 }
3454 switch(encodingType) {
3455 case X509_ASN_ENCODING:
3456 Py_INCREF(x509_asn);
3457 return x509_asn;
3458 case PKCS_7_ASN_ENCODING:
3459 Py_INCREF(pkcs_7_asn);
3460 return pkcs_7_asn;
3461 default:
3462 return PyLong_FromLong(encodingType);
3463 }
3464}
3465
3466static PyObject*
3467parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3468{
3469 CERT_ENHKEY_USAGE *usage;
3470 DWORD size, error, i;
3471 PyObject *retval;
3472
3473 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3474 error = GetLastError();
3475 if (error == CRYPT_E_NOT_FOUND) {
3476 Py_RETURN_TRUE;
3477 }
3478 return PyErr_SetFromWindowsErr(error);
3479 }
3480
3481 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3482 if (usage == NULL) {
3483 return PyErr_NoMemory();
3484 }
3485
3486 /* Now get the actual enhanced usage property */
3487 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3488 PyMem_Free(usage);
3489 error = GetLastError();
3490 if (error == CRYPT_E_NOT_FOUND) {
3491 Py_RETURN_TRUE;
3492 }
3493 return PyErr_SetFromWindowsErr(error);
3494 }
3495 retval = PySet_New(NULL);
3496 if (retval == NULL) {
3497 goto error;
3498 }
3499 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3500 if (usage->rgpszUsageIdentifier[i]) {
3501 PyObject *oid;
3502 int err;
3503 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3504 if (oid == NULL) {
3505 Py_CLEAR(retval);
3506 goto error;
3507 }
3508 err = PySet_Add(retval, oid);
3509 Py_DECREF(oid);
3510 if (err == -1) {
3511 Py_CLEAR(retval);
3512 goto error;
3513 }
3514 }
3515 }
3516 error:
3517 PyMem_Free(usage);
3518 return retval;
3519}
3520
3521PyDoc_STRVAR(PySSL_enum_certificates_doc,
3522"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003523\n\
3524Retrieve certificates from Windows' cert store. store_name may be one of\n\
3525'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003526The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003527encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003528PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3529boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003530
Christian Heimes46bebee2013-06-09 19:03:31 +02003531static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003532PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003533{
Christian Heimes44109d72013-11-22 01:51:30 +01003534 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003535 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003536 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003537 PCCERT_CONTEXT pCertCtx = NULL;
3538 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003539 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003540
Christian Heimes44109d72013-11-22 01:51:30 +01003541 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3542 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003543 return NULL;
3544 }
Christian Heimes44109d72013-11-22 01:51:30 +01003545 result = PyList_New(0);
3546 if (result == NULL) {
3547 return NULL;
3548 }
3549 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3550 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003551 Py_DECREF(result);
3552 return PyErr_SetFromWindowsErr(GetLastError());
3553 }
3554
Christian Heimes44109d72013-11-22 01:51:30 +01003555 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3556 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3557 pCertCtx->cbCertEncoded);
3558 if (!cert) {
3559 Py_CLEAR(result);
3560 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003561 }
Christian Heimes44109d72013-11-22 01:51:30 +01003562 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3563 Py_CLEAR(result);
3564 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003565 }
Christian Heimes44109d72013-11-22 01:51:30 +01003566 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3567 if (keyusage == Py_True) {
3568 Py_DECREF(keyusage);
3569 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003570 }
Christian Heimes44109d72013-11-22 01:51:30 +01003571 if (keyusage == NULL) {
3572 Py_CLEAR(result);
3573 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003574 }
Christian Heimes44109d72013-11-22 01:51:30 +01003575 if ((tup = PyTuple_New(3)) == NULL) {
3576 Py_CLEAR(result);
3577 break;
3578 }
3579 PyTuple_SET_ITEM(tup, 0, cert);
3580 cert = NULL;
3581 PyTuple_SET_ITEM(tup, 1, enc);
3582 enc = NULL;
3583 PyTuple_SET_ITEM(tup, 2, keyusage);
3584 keyusage = NULL;
3585 if (PyList_Append(result, tup) < 0) {
3586 Py_CLEAR(result);
3587 break;
3588 }
3589 Py_CLEAR(tup);
3590 }
3591 if (pCertCtx) {
3592 /* loop ended with an error, need to clean up context manually */
3593 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003594 }
3595
3596 /* In error cases cert, enc and tup may not be NULL */
3597 Py_XDECREF(cert);
3598 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003599 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003600 Py_XDECREF(tup);
3601
3602 if (!CertCloseStore(hStore, 0)) {
3603 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003604 Py_XDECREF(result);
3605 return PyErr_SetFromWindowsErr(GetLastError());
3606 }
3607 return result;
3608}
3609
3610PyDoc_STRVAR(PySSL_enum_crls_doc,
3611"enum_crls(store_name) -> []\n\
3612\n\
3613Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3614'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3615The function returns a list of (bytes, encoding_type) tuples. The\n\
3616encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3617PKCS_7_ASN_ENCODING.");
3618
3619static PyObject *
3620PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3621{
3622 char *kwlist[] = {"store_name", NULL};
3623 char *store_name;
3624 HCERTSTORE hStore = NULL;
3625 PCCRL_CONTEXT pCrlCtx = NULL;
3626 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3627 PyObject *result = NULL;
3628
3629 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3630 kwlist, &store_name)) {
3631 return NULL;
3632 }
3633 result = PyList_New(0);
3634 if (result == NULL) {
3635 return NULL;
3636 }
3637 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3638 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003639 Py_DECREF(result);
3640 return PyErr_SetFromWindowsErr(GetLastError());
3641 }
Christian Heimes44109d72013-11-22 01:51:30 +01003642
3643 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3644 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3645 pCrlCtx->cbCrlEncoded);
3646 if (!crl) {
3647 Py_CLEAR(result);
3648 break;
3649 }
3650 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3651 Py_CLEAR(result);
3652 break;
3653 }
3654 if ((tup = PyTuple_New(2)) == NULL) {
3655 Py_CLEAR(result);
3656 break;
3657 }
3658 PyTuple_SET_ITEM(tup, 0, crl);
3659 crl = NULL;
3660 PyTuple_SET_ITEM(tup, 1, enc);
3661 enc = NULL;
3662
3663 if (PyList_Append(result, tup) < 0) {
3664 Py_CLEAR(result);
3665 break;
3666 }
3667 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003668 }
Christian Heimes44109d72013-11-22 01:51:30 +01003669 if (pCrlCtx) {
3670 /* loop ended with an error, need to clean up context manually */
3671 CertFreeCRLContext(pCrlCtx);
3672 }
3673
3674 /* In error cases cert, enc and tup may not be NULL */
3675 Py_XDECREF(crl);
3676 Py_XDECREF(enc);
3677 Py_XDECREF(tup);
3678
3679 if (!CertCloseStore(hStore, 0)) {
3680 /* This error case might shadow another exception.*/
3681 Py_XDECREF(result);
3682 return PyErr_SetFromWindowsErr(GetLastError());
3683 }
3684 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003685}
Christian Heimes44109d72013-11-22 01:51:30 +01003686
3687#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003688
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003689/* List of functions exported by this module. */
3690
3691static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003692 {"_test_decode_cert", PySSL_test_decode_certificate,
3693 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003694#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003695 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3696 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003697 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3698 PySSL_RAND_bytes_doc},
3699 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3700 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003701 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003702 PySSL_RAND_egd_doc},
3703 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3704 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003705#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003706 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003707 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003708#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003709 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3710 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3711 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3712 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003713#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003714 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3715 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3716 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3717 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003718 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003719};
3720
3721
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003722#ifdef WITH_THREAD
3723
3724/* an implementation of OpenSSL threading operations in terms
3725 of the Python C thread library */
3726
3727static PyThread_type_lock *_ssl_locks = NULL;
3728
Christian Heimes4d98ca92013-08-19 17:36:29 +02003729#if OPENSSL_VERSION_NUMBER >= 0x10000000
3730/* use new CRYPTO_THREADID API. */
3731static void
3732_ssl_threadid_callback(CRYPTO_THREADID *id)
3733{
3734 CRYPTO_THREADID_set_numeric(id,
3735 (unsigned long)PyThread_get_thread_ident());
3736}
3737#else
3738/* deprecated CRYPTO_set_id_callback() API. */
3739static unsigned long
3740_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003741 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003742}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003743#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003744
Bill Janssen6e027db2007-11-15 22:23:56 +00003745static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003746 (int mode, int n, const char *file, int line) {
3747 /* this function is needed to perform locking on shared data
3748 structures. (Note that OpenSSL uses a number of global data
3749 structures that will be implicitly shared whenever multiple
3750 threads use OpenSSL.) Multi-threaded applications will
3751 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003753 locking_function() must be able to handle up to
3754 CRYPTO_num_locks() different mutex locks. It sets the n-th
3755 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003757 file and line are the file number of the function setting the
3758 lock. They can be useful for debugging.
3759 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003761 if ((_ssl_locks == NULL) ||
3762 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3763 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003765 if (mode & CRYPTO_LOCK) {
3766 PyThread_acquire_lock(_ssl_locks[n], 1);
3767 } else {
3768 PyThread_release_lock(_ssl_locks[n]);
3769 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003770}
3771
3772static int _setup_ssl_threads(void) {
3773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003774 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003776 if (_ssl_locks == NULL) {
3777 _ssl_locks_count = CRYPTO_num_locks();
3778 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003779 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003780 if (_ssl_locks == NULL)
3781 return 0;
3782 memset(_ssl_locks, 0,
3783 sizeof(PyThread_type_lock) * _ssl_locks_count);
3784 for (i = 0; i < _ssl_locks_count; i++) {
3785 _ssl_locks[i] = PyThread_allocate_lock();
3786 if (_ssl_locks[i] == NULL) {
3787 unsigned int j;
3788 for (j = 0; j < i; j++) {
3789 PyThread_free_lock(_ssl_locks[j]);
3790 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003791 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003792 return 0;
3793 }
3794 }
3795 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003796#if OPENSSL_VERSION_NUMBER >= 0x10000000
3797 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3798#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003799 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003800#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003801 }
3802 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003803}
3804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003805#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003806
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003807PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003808"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003809for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003810
Martin v. Löwis1a214512008-06-11 05:26:20 +00003811
3812static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003813 PyModuleDef_HEAD_INIT,
3814 "_ssl",
3815 module_doc,
3816 -1,
3817 PySSL_methods,
3818 NULL,
3819 NULL,
3820 NULL,
3821 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003822};
3823
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003824
3825static void
3826parse_openssl_version(unsigned long libver,
3827 unsigned int *major, unsigned int *minor,
3828 unsigned int *fix, unsigned int *patch,
3829 unsigned int *status)
3830{
3831 *status = libver & 0xF;
3832 libver >>= 4;
3833 *patch = libver & 0xFF;
3834 libver >>= 8;
3835 *fix = libver & 0xFF;
3836 libver >>= 8;
3837 *minor = libver & 0xFF;
3838 libver >>= 8;
3839 *major = libver & 0xFF;
3840}
3841
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003842PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003843PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003844{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003845 PyObject *m, *d, *r;
3846 unsigned long libver;
3847 unsigned int major, minor, fix, patch, status;
3848 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003849 struct py_ssl_error_code *errcode;
3850 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003851
Antoine Pitrou152efa22010-05-16 18:19:27 +00003852 if (PyType_Ready(&PySSLContext_Type) < 0)
3853 return NULL;
3854 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003855 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003857 m = PyModule_Create(&_sslmodule);
3858 if (m == NULL)
3859 return NULL;
3860 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003862 /* Load _socket module and its C API */
3863 socket_api = PySocketModule_ImportModuleAndAPI();
3864 if (!socket_api)
3865 return NULL;
3866 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003868 /* Init OpenSSL */
3869 SSL_load_error_strings();
3870 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003871#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003872 /* note that this will start threading if not already started */
3873 if (!_setup_ssl_threads()) {
3874 return NULL;
3875 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003876#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003877 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003879 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003880 sslerror_type_slots[0].pfunc = PyExc_OSError;
3881 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003882 if (PySSLErrorObject == NULL)
3883 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003884
Antoine Pitrou41032a62011-10-27 23:56:55 +02003885 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3886 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3887 PySSLErrorObject, NULL);
3888 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3889 "ssl.SSLWantReadError", SSLWantReadError_doc,
3890 PySSLErrorObject, NULL);
3891 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3892 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3893 PySSLErrorObject, NULL);
3894 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3895 "ssl.SSLSyscallError", SSLSyscallError_doc,
3896 PySSLErrorObject, NULL);
3897 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3898 "ssl.SSLEOFError", SSLEOFError_doc,
3899 PySSLErrorObject, NULL);
3900 if (PySSLZeroReturnErrorObject == NULL
3901 || PySSLWantReadErrorObject == NULL
3902 || PySSLWantWriteErrorObject == NULL
3903 || PySSLSyscallErrorObject == NULL
3904 || PySSLEOFErrorObject == NULL)
3905 return NULL;
3906 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3907 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3908 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3909 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3910 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3911 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003912 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003913 if (PyDict_SetItemString(d, "_SSLContext",
3914 (PyObject *)&PySSLContext_Type) != 0)
3915 return NULL;
3916 if (PyDict_SetItemString(d, "_SSLSocket",
3917 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003918 return NULL;
3919 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3920 PY_SSL_ERROR_ZERO_RETURN);
3921 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3922 PY_SSL_ERROR_WANT_READ);
3923 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3924 PY_SSL_ERROR_WANT_WRITE);
3925 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3926 PY_SSL_ERROR_WANT_X509_LOOKUP);
3927 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3928 PY_SSL_ERROR_SYSCALL);
3929 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3930 PY_SSL_ERROR_SSL);
3931 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3932 PY_SSL_ERROR_WANT_CONNECT);
3933 /* non ssl.h errorcodes */
3934 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3935 PY_SSL_ERROR_EOF);
3936 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3937 PY_SSL_ERROR_INVALID_ERROR_CODE);
3938 /* cert requirements */
3939 PyModule_AddIntConstant(m, "CERT_NONE",
3940 PY_SSL_CERT_NONE);
3941 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3942 PY_SSL_CERT_OPTIONAL);
3943 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3944 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01003945 /* CRL verification for verification_flags */
3946 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
3947 0);
3948 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
3949 X509_V_FLAG_CRL_CHECK);
3950 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
3951 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3952 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
3953 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003954
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003955 /* Alert Descriptions from ssl.h */
3956 /* note RESERVED constants no longer intended for use have been removed */
3957 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3958
3959#define ADD_AD_CONSTANT(s) \
3960 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3961 SSL_AD_##s)
3962
3963 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3964 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3965 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3966 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3967 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3968 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3969 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3970 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3971 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3972 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3973 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3974 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3975 ADD_AD_CONSTANT(UNKNOWN_CA);
3976 ADD_AD_CONSTANT(ACCESS_DENIED);
3977 ADD_AD_CONSTANT(DECODE_ERROR);
3978 ADD_AD_CONSTANT(DECRYPT_ERROR);
3979 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3980 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3981 ADD_AD_CONSTANT(INTERNAL_ERROR);
3982 ADD_AD_CONSTANT(USER_CANCELLED);
3983 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003984 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003985#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3986 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3987#endif
3988#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3989 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3990#endif
3991#ifdef SSL_AD_UNRECOGNIZED_NAME
3992 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3993#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003994#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3995 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3996#endif
3997#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3998 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3999#endif
4000#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4001 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4002#endif
4003
4004#undef ADD_AD_CONSTANT
4005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004006 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004007#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004008 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4009 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004010#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004011 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4012 PY_SSL_VERSION_SSL3);
4013 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4014 PY_SSL_VERSION_SSL23);
4015 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4016 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004017#if HAVE_TLSv1_2
4018 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4019 PY_SSL_VERSION_TLS1_1);
4020 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4021 PY_SSL_VERSION_TLS1_2);
4022#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004023
Antoine Pitroub5218772010-05-21 09:56:06 +00004024 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004025 PyModule_AddIntConstant(m, "OP_ALL",
4026 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004027 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4028 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4029 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004030#if HAVE_TLSv1_2
4031 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4032 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4033#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004034 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4035 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004036 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004037#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004038 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004039#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004040#ifdef SSL_OP_NO_COMPRESSION
4041 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4042 SSL_OP_NO_COMPRESSION);
4043#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004044
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004045#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004046 r = Py_True;
4047#else
4048 r = Py_False;
4049#endif
4050 Py_INCREF(r);
4051 PyModule_AddObject(m, "HAS_SNI", r);
4052
Antoine Pitroud6494802011-07-21 01:11:30 +02004053#if HAVE_OPENSSL_FINISHED
4054 r = Py_True;
4055#else
4056 r = Py_False;
4057#endif
4058 Py_INCREF(r);
4059 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4060
Antoine Pitrou501da612011-12-21 09:27:41 +01004061#ifdef OPENSSL_NO_ECDH
4062 r = Py_False;
4063#else
4064 r = Py_True;
4065#endif
4066 Py_INCREF(r);
4067 PyModule_AddObject(m, "HAS_ECDH", r);
4068
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004069#ifdef OPENSSL_NPN_NEGOTIATED
4070 r = Py_True;
4071#else
4072 r = Py_False;
4073#endif
4074 Py_INCREF(r);
4075 PyModule_AddObject(m, "HAS_NPN", r);
4076
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004077 /* Mappings for error codes */
4078 err_codes_to_names = PyDict_New();
4079 err_names_to_codes = PyDict_New();
4080 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4081 return NULL;
4082 errcode = error_codes;
4083 while (errcode->mnemonic != NULL) {
4084 PyObject *mnemo, *key;
4085 mnemo = PyUnicode_FromString(errcode->mnemonic);
4086 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4087 if (mnemo == NULL || key == NULL)
4088 return NULL;
4089 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4090 return NULL;
4091 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4092 return NULL;
4093 Py_DECREF(key);
4094 Py_DECREF(mnemo);
4095 errcode++;
4096 }
4097 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4098 return NULL;
4099 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4100 return NULL;
4101
4102 lib_codes_to_names = PyDict_New();
4103 if (lib_codes_to_names == NULL)
4104 return NULL;
4105 libcode = library_codes;
4106 while (libcode->library != NULL) {
4107 PyObject *mnemo, *key;
4108 key = PyLong_FromLong(libcode->code);
4109 mnemo = PyUnicode_FromString(libcode->library);
4110 if (key == NULL || mnemo == NULL)
4111 return NULL;
4112 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4113 return NULL;
4114 Py_DECREF(key);
4115 Py_DECREF(mnemo);
4116 libcode++;
4117 }
4118 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4119 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004121 /* OpenSSL version */
4122 /* SSLeay() gives us the version of the library linked against,
4123 which could be different from the headers version.
4124 */
4125 libver = SSLeay();
4126 r = PyLong_FromUnsignedLong(libver);
4127 if (r == NULL)
4128 return NULL;
4129 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4130 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004131 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004132 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4133 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4134 return NULL;
4135 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4136 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4137 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004138
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004139 libver = OPENSSL_VERSION_NUMBER;
4140 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4141 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4142 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4143 return NULL;
4144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004145 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004146}