blob: 2e3c5b1187ee802ab128d9cf420573946b178183 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020021
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020023#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
25#define PySSL_END_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000028 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020029 PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
31#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000034#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save)
37#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038#define PySSL_BEGIN_ALLOW_THREADS
39#define PySSL_BLOCK_THREADS
40#define PySSL_UNBLOCK_THREADS
41#define PySSL_END_ALLOW_THREADS
42
43#endif
44
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010045/* Include symbols from _socket module */
46#include "socketmodule.h"
47
48static PySocketModule_APIObject PySocketModule;
49
50#if defined(HAVE_POLL_H)
51#include <poll.h>
52#elif defined(HAVE_SYS_POLL_H)
53#include <sys/poll.h>
54#endif
55
56/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
65
66/* SSL error object */
67static PyObject *PySSLErrorObject;
68static PyObject *PySSLZeroReturnErrorObject;
69static PyObject *PySSLWantReadErrorObject;
70static PyObject *PySSLWantWriteErrorObject;
71static PyObject *PySSLSyscallErrorObject;
72static PyObject *PySSLEOFErrorObject;
73
74/* Error mappings */
75static PyObject *err_codes_to_names;
76static PyObject *err_names_to_codes;
77static PyObject *lib_codes_to_names;
78
79struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83struct py_ssl_library_code {
84 const char *library;
85 int code;
86};
87
88/* Include generated data (error codes) */
89#include "_ssl_data.h"
90
91/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
92 http://www.openssl.org/news/changelog.html
93 */
94#if OPENSSL_VERSION_NUMBER >= 0x10001000L
95# define HAVE_TLSv1_2 1
96#else
97# define HAVE_TLSv1_2 0
98#endif
99
Christian Heimes470fba12013-11-28 15:12:15 +0100100/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100101 * This includes the SSL_set_SSL_CTX() function.
102 */
103#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
104# define HAVE_SNI 1
105#else
106# define HAVE_SNI 0
107#endif
108
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000109enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000110 /* these mirror ssl.h */
111 PY_SSL_ERROR_NONE,
112 PY_SSL_ERROR_SSL,
113 PY_SSL_ERROR_WANT_READ,
114 PY_SSL_ERROR_WANT_WRITE,
115 PY_SSL_ERROR_WANT_X509_LOOKUP,
116 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
117 PY_SSL_ERROR_ZERO_RETURN,
118 PY_SSL_ERROR_WANT_CONNECT,
119 /* start of non ssl.h errorcodes */
120 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
121 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
122 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000123};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000124
Thomas Woutersed03b412007-08-28 21:37:11 +0000125enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PY_SSL_CLIENT,
127 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000128};
129
130enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000131 PY_SSL_CERT_NONE,
132 PY_SSL_CERT_OPTIONAL,
133 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000134};
135
136enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000137 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200138 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140#if HAVE_TLSv1_2
141 PY_SSL_VERSION_TLS1,
142 PY_SSL_VERSION_TLS1_1,
143 PY_SSL_VERSION_TLS1_2
144#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200148
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000149#ifdef WITH_THREAD
150
151/* serves as a flag to see whether we've initialized the SSL thread support. */
152/* 0 means no, greater than 0 means yes */
153
154static unsigned int _ssl_locks_count = 0;
155
156#endif /* def WITH_THREAD */
157
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158/* SSL socket object */
159
160#define X509_NAME_MAXLEN 256
161
162/* RAND_* APIs got added to OpenSSL in 0.9.5 */
163#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
164# define HAVE_OPENSSL_RAND 1
165#else
166# undef HAVE_OPENSSL_RAND
167#endif
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
182/* SSL_get_finished got added to OpenSSL in 0.9.5 */
183#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
184# define HAVE_OPENSSL_FINISHED 1
185#else
186# define HAVE_OPENSSL_FINISHED 0
187#endif
188
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100189/* ECDH support got added to OpenSSL in 0.9.8 */
190#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
191# define OPENSSL_NO_ECDH
192#endif
193
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100194/* compression support got added to OpenSSL in 0.9.8 */
195#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
196# define OPENSSL_NO_COMP
197#endif
198
Christian Heimes2427b502013-11-23 11:24:32 +0100199/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
200#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
201# define HAVE_OPENSSL_VERIFY_PARAM
202#endif
203
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100204
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000205typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100208#ifdef OPENSSL_NPN_NEGOTIATED
209 char *npn_protocols;
210 int npn_protocols_len;
211#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100212#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200213 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100214#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100215 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000216} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000217
Antoine Pitrou152efa22010-05-16 18:19:27 +0000218typedef struct {
219 PyObject_HEAD
220 PyObject *Socket; /* weakref to socket on which we're layered */
221 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100222 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200224 char shutdown_seen_zero;
225 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200226 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000227} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000228
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229static PyTypeObject PySSLContext_Type;
230static PyTypeObject PySSLSocket_Type;
231
232static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
233static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000234static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000235 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000236static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
237static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Antoine Pitrou152efa22010-05-16 18:19:27 +0000239#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
240#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000241
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000243 SOCKET_IS_NONBLOCKING,
244 SOCKET_IS_BLOCKING,
245 SOCKET_HAS_TIMED_OUT,
246 SOCKET_HAS_BEEN_CLOSED,
247 SOCKET_TOO_LARGE_FOR_SELECT,
248 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000249} timeout_state;
250
Thomas Woutersed03b412007-08-28 21:37:11 +0000251/* Wrap error strings with filename and line # */
252#define STRINGIFY1(x) #x
253#define STRINGIFY2(x) STRINGIFY1(x)
254#define ERRSTR1(x,y,z) (x ":" y ": " z)
255#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
256
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200257
258/*
259 * SSL errors.
260 */
261
262PyDoc_STRVAR(SSLError_doc,
263"An error occurred in the SSL implementation.");
264
265PyDoc_STRVAR(SSLZeroReturnError_doc,
266"SSL/TLS session closed cleanly.");
267
268PyDoc_STRVAR(SSLWantReadError_doc,
269"Non-blocking SSL socket needs to read more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLWantWriteError_doc,
273"Non-blocking SSL socket needs to write more data\n"
274"before the requested operation can be completed.");
275
276PyDoc_STRVAR(SSLSyscallError_doc,
277"System error when attempting SSL operation.");
278
279PyDoc_STRVAR(SSLEOFError_doc,
280"SSL/TLS connection terminated abruptly.");
281
282static PyObject *
283SSLError_str(PyOSErrorObject *self)
284{
285 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
286 Py_INCREF(self->strerror);
287 return self->strerror;
288 }
289 else
290 return PyObject_Str(self->args);
291}
292
293static PyType_Slot sslerror_type_slots[] = {
294 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
295 {Py_tp_doc, SSLError_doc},
296 {Py_tp_str, SSLError_str},
297 {0, 0},
298};
299
300static PyType_Spec sslerror_type_spec = {
301 "ssl.SSLError",
302 sizeof(PyOSErrorObject),
303 0,
304 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
305 sslerror_type_slots
306};
307
308static void
309fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
310 int lineno, unsigned long errcode)
311{
312 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
313 PyObject *init_value, *msg, *key;
314 _Py_IDENTIFIER(reason);
315 _Py_IDENTIFIER(library);
316
317 if (errcode != 0) {
318 int lib, reason;
319
320 lib = ERR_GET_LIB(errcode);
321 reason = ERR_GET_REASON(errcode);
322 key = Py_BuildValue("ii", lib, reason);
323 if (key == NULL)
324 goto fail;
325 reason_obj = PyDict_GetItem(err_codes_to_names, key);
326 Py_DECREF(key);
327 if (reason_obj == NULL) {
328 /* XXX if reason < 100, it might reflect a library number (!!) */
329 PyErr_Clear();
330 }
331 key = PyLong_FromLong(lib);
332 if (key == NULL)
333 goto fail;
334 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
335 Py_DECREF(key);
336 if (lib_obj == NULL) {
337 PyErr_Clear();
338 }
339 if (errstr == NULL)
340 errstr = ERR_reason_error_string(errcode);
341 }
342 if (errstr == NULL)
343 errstr = "unknown error";
344
345 if (reason_obj && lib_obj)
346 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
347 lib_obj, reason_obj, errstr, lineno);
348 else if (lib_obj)
349 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
350 lib_obj, errstr, lineno);
351 else
352 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200353 if (msg == NULL)
354 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100355
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100357 if (init_value == NULL)
358 goto fail;
359
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200360 err_value = PyObject_CallObject(type, init_value);
361 Py_DECREF(init_value);
362 if (err_value == NULL)
363 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100364
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200365 if (reason_obj == NULL)
366 reason_obj = Py_None;
367 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
368 goto fail;
369 if (lib_obj == NULL)
370 lib_obj = Py_None;
371 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
372 goto fail;
373 PyErr_SetObject(type, err_value);
374fail:
375 Py_XDECREF(err_value);
376}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377
378static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000379PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200381 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 int err;
384 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200388 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 if (obj->ssl != NULL) {
391 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 switch (err) {
394 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 errstr = "TLS/SSL connection has been closed (EOF)";
396 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 p = PY_SSL_ERROR_ZERO_RETURN;
398 break;
399 case SSL_ERROR_WANT_READ:
400 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000402 p = PY_SSL_ERROR_WANT_READ;
403 break;
404 case SSL_ERROR_WANT_WRITE:
405 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200406 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 errstr = "The operation did not complete (write)";
408 break;
409 case SSL_ERROR_WANT_X509_LOOKUP:
410 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000411 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000412 break;
413 case SSL_ERROR_WANT_CONNECT:
414 p = PY_SSL_ERROR_WANT_CONNECT;
415 errstr = "The operation did not complete (connect)";
416 break;
417 case SSL_ERROR_SYSCALL:
418 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 if (e == 0) {
420 PySocketSockObject *s
421 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
422 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200424 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000428 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000429 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000431 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000434 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200435 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 }
438 } else {
439 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000440 }
441 break;
442 }
443 case SSL_ERROR_SSL:
444 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200446 if (e == 0)
447 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000448 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 break;
450 }
451 default:
452 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
453 errstr = "Invalid error code";
454 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000457 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459}
460
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461static PyObject *
462_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
463
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 else
467 errcode = 0;
468 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000469 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471}
472
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473/*
474 * SSL objects
475 */
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100478newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000479 enum py_ssl_server_or_client socket_type,
480 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100483 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200484 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
Antoine Pitrou152efa22010-05-16 18:19:27 +0000486 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 if (self == NULL)
488 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 self->peer_cert = NULL;
491 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100493 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200494 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200495 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100496 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 /* Make sure the SSL error state is initialized */
499 (void) ERR_get_state();
500 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000503 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100505 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100506 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000508#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000510#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200511 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000512
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100513#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000514 if (server_hostname != NULL)
515 SSL_set_tlsext_host_name(self->ssl, server_hostname);
516#endif
517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 /* If the socket is in non-blocking mode or timeout mode, set the BIO
519 * to non-blocking mode (blocking is the default)
520 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
523 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
524 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 PySSL_BEGIN_ALLOW_THREADS
527 if (socket_type == PY_SSL_CLIENT)
528 SSL_set_connect_state(self->ssl);
529 else
530 SSL_set_accept_state(self->ssl);
531 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000532
Antoine Pitroud6494802011-07-21 01:11:30 +0200533 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000534 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100535 if (self->Socket == NULL) {
536 Py_DECREF(self);
537 return NULL;
538 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000540}
541
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542/* SSL object methods */
543
Antoine Pitrou152efa22010-05-16 18:19:27 +0000544static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000545{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 int ret;
547 int err;
548 int sockstate, nonblocking;
549 PySocketSockObject *sock
550 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 if (((PyObject*)sock) == Py_None) {
553 _setSSLError("Underlying socket connection gone",
554 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
555 return NULL;
556 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000557 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000559 /* just in case the blocking state of the socket has been changed */
560 nonblocking = (sock->sock_timeout >= 0.0);
561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 /* Actually negotiate SSL connection */
565 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000567 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 ret = SSL_do_handshake(self->ssl);
569 err = SSL_get_error(self->ssl, ret);
570 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 if (PyErr_CheckSignals())
572 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 if (err == SSL_ERROR_WANT_READ) {
574 sockstate = check_socket_and_wait_for_timeout(sock, 0);
575 } else if (err == SSL_ERROR_WANT_WRITE) {
576 sockstate = check_socket_and_wait_for_timeout(sock, 1);
577 } else {
578 sockstate = SOCKET_OPERATION_OK;
579 }
580 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000581 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
585 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000586 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
589 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000590 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
593 break;
594 }
595 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000596 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 if (ret < 1)
598 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 if (self->peer_cert)
601 X509_free (self->peer_cert);
602 PySSL_BEGIN_ALLOW_THREADS
603 self->peer_cert = SSL_get_peer_certificate(self->ssl);
604 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200605 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606
607 Py_INCREF(Py_None);
608 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000609
610error:
611 Py_DECREF(sock);
612 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613}
614
Thomas Woutersed03b412007-08-28 21:37:11 +0000615static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 char namebuf[X509_NAME_MAXLEN];
619 int buflen;
620 PyObject *name_obj;
621 PyObject *value_obj;
622 PyObject *attr;
623 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
626 if (buflen < 0) {
627 _setSSLError(NULL, 0, __FILE__, __LINE__);
628 goto fail;
629 }
630 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
631 if (name_obj == NULL)
632 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
635 if (buflen < 0) {
636 _setSSLError(NULL, 0, __FILE__, __LINE__);
637 Py_DECREF(name_obj);
638 goto fail;
639 }
640 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000641 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 OPENSSL_free(valuebuf);
643 if (value_obj == NULL) {
644 Py_DECREF(name_obj);
645 goto fail;
646 }
647 attr = PyTuple_New(2);
648 if (attr == NULL) {
649 Py_DECREF(name_obj);
650 Py_DECREF(value_obj);
651 goto fail;
652 }
653 PyTuple_SET_ITEM(attr, 0, name_obj);
654 PyTuple_SET_ITEM(attr, 1, value_obj);
655 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000659}
660
661static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
665 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
666 PyObject *rdnt;
667 PyObject *attr = NULL; /* tuple to hold an attribute */
668 int entry_count = X509_NAME_entry_count(xname);
669 X509_NAME_ENTRY *entry;
670 ASN1_OBJECT *name;
671 ASN1_STRING *value;
672 int index_counter;
673 int rdn_level = -1;
674 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 dn = PyList_New(0);
677 if (dn == NULL)
678 return NULL;
679 /* now create another tuple to hold the top-level RDN */
680 rdn = PyList_New(0);
681 if (rdn == NULL)
682 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 for (index_counter = 0;
685 index_counter < entry_count;
686 index_counter++)
687 {
688 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 /* check to see if we've gotten to a new RDN */
691 if (rdn_level >= 0) {
692 if (rdn_level != entry->set) {
693 /* yes, new RDN */
694 /* add old RDN to DN */
695 rdnt = PyList_AsTuple(rdn);
696 Py_DECREF(rdn);
697 if (rdnt == NULL)
698 goto fail0;
699 retcode = PyList_Append(dn, rdnt);
700 Py_DECREF(rdnt);
701 if (retcode < 0)
702 goto fail0;
703 /* create new RDN */
704 rdn = PyList_New(0);
705 if (rdn == NULL)
706 goto fail0;
707 }
708 }
709 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 /* now add this attribute to the current RDN */
712 name = X509_NAME_ENTRY_get_object(entry);
713 value = X509_NAME_ENTRY_get_data(entry);
714 attr = _create_tuple_for_attribute(name, value);
715 /*
716 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
717 entry->set,
718 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
719 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
720 */
721 if (attr == NULL)
722 goto fail1;
723 retcode = PyList_Append(rdn, attr);
724 Py_DECREF(attr);
725 if (retcode < 0)
726 goto fail1;
727 }
728 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100729 if (rdn != NULL) {
730 if (PyList_GET_SIZE(rdn) > 0) {
731 rdnt = PyList_AsTuple(rdn);
732 Py_DECREF(rdn);
733 if (rdnt == NULL)
734 goto fail0;
735 retcode = PyList_Append(dn, rdnt);
736 Py_DECREF(rdnt);
737 if (retcode < 0)
738 goto fail0;
739 }
740 else {
741 Py_DECREF(rdn);
742 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* convert list to tuple */
746 rdnt = PyList_AsTuple(dn);
747 Py_DECREF(dn);
748 if (rdnt == NULL)
749 return NULL;
750 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
752 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754
755 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 Py_XDECREF(dn);
757 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758}
759
760static PyObject *
761_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 /* this code follows the procedure outlined in
764 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
765 function to extract the STACK_OF(GENERAL_NAME),
766 then iterates through the stack to add the
767 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 int i, j;
770 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200771 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 X509_EXTENSION *ext = NULL;
773 GENERAL_NAMES *names = NULL;
774 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000775 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 BIO *biobuf = NULL;
777 char buf[2048];
778 char *vptr;
779 int len;
780 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000781#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000783#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000785#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 if (certificate == NULL)
788 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 /* get a memory buffer */
791 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200793 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 while ((i = X509_get_ext_by_NID(
795 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 if (peer_alt_names == Py_None) {
798 peer_alt_names = PyList_New(0);
799 if (peer_alt_names == NULL)
800 goto fail;
801 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* now decode the altName */
804 ext = X509_get_ext(certificate, i);
805 if(!(method = X509V3_EXT_get(ext))) {
806 PyErr_SetString
807 (PySSLErrorObject,
808 ERRSTR("No method for internalizing subjectAltName!"));
809 goto fail;
810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 p = ext->value->data;
813 if (method->it)
814 names = (GENERAL_NAMES*)
815 (ASN1_item_d2i(NULL,
816 &p,
817 ext->value->length,
818 ASN1_ITEM_ptr(method->it)));
819 else
820 names = (GENERAL_NAMES*)
821 (method->d2i(NULL,
822 &p,
823 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200827 int gntype;
828 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200831 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200832 switch (gntype) {
833 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* we special-case DirName as a tuple of
835 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 t = PyTuple_New(2);
838 if (t == NULL) {
839 goto fail;
840 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 v = PyUnicode_FromString("DirName");
843 if (v == NULL) {
844 Py_DECREF(t);
845 goto fail;
846 }
847 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 v = _create_tuple_for_X509_NAME (name->d.dirn);
850 if (v == NULL) {
851 Py_DECREF(t);
852 goto fail;
853 }
854 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200855 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000856
Christian Heimes824f7f32013-08-17 00:54:47 +0200857 case GEN_EMAIL:
858 case GEN_DNS:
859 case GEN_URI:
860 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
861 correctly, CVE-2013-4238 */
862 t = PyTuple_New(2);
863 if (t == NULL)
864 goto fail;
865 switch (gntype) {
866 case GEN_EMAIL:
867 v = PyUnicode_FromString("email");
868 as = name->d.rfc822Name;
869 break;
870 case GEN_DNS:
871 v = PyUnicode_FromString("DNS");
872 as = name->d.dNSName;
873 break;
874 case GEN_URI:
875 v = PyUnicode_FromString("URI");
876 as = name->d.uniformResourceIdentifier;
877 break;
878 }
879 if (v == NULL) {
880 Py_DECREF(t);
881 goto fail;
882 }
883 PyTuple_SET_ITEM(t, 0, v);
884 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
885 ASN1_STRING_length(as));
886 if (v == NULL) {
887 Py_DECREF(t);
888 goto fail;
889 }
890 PyTuple_SET_ITEM(t, 1, v);
891 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Christian Heimes824f7f32013-08-17 00:54:47 +0200893 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 switch (gntype) {
896 /* check for new general name type */
897 case GEN_OTHERNAME:
898 case GEN_X400:
899 case GEN_EDIPARTY:
900 case GEN_IPADD:
901 case GEN_RID:
902 break;
903 default:
904 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
905 "Unknown general name type %d",
906 gntype) == -1) {
907 goto fail;
908 }
909 break;
910 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 (void) BIO_reset(biobuf);
912 GENERAL_NAME_print(biobuf, name);
913 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
914 if (len < 0) {
915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 goto fail;
917 }
918 vptr = strchr(buf, ':');
919 if (vptr == NULL)
920 goto fail;
921 t = PyTuple_New(2);
922 if (t == NULL)
923 goto fail;
924 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
925 if (v == NULL) {
926 Py_DECREF(t);
927 goto fail;
928 }
929 PyTuple_SET_ITEM(t, 0, v);
930 v = PyUnicode_FromStringAndSize((vptr + 1),
931 (len - (vptr - buf + 1)));
932 if (v == NULL) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 if (PyList_Append(peer_alt_names, t) < 0) {
943 Py_DECREF(t);
944 goto fail;
945 }
946 Py_DECREF(t);
947 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100948 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 }
950 BIO_free(biobuf);
951 if (peer_alt_names != Py_None) {
952 v = PyList_AsTuple(peer_alt_names);
953 Py_DECREF(peer_alt_names);
954 return v;
955 } else {
956 return peer_alt_names;
957 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000958
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
960 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 if (biobuf != NULL)
962 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 if (peer_alt_names != Py_None) {
965 Py_XDECREF(peer_alt_names);
966 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969}
970
971static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100972_get_aia_uri(X509 *certificate, int nid) {
973 PyObject *lst = NULL, *ostr = NULL;
974 int i, result;
975 AUTHORITY_INFO_ACCESS *info;
976
977 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
978 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
979 return Py_None;
980 }
981
982 if ((lst = PyList_New(0)) == NULL) {
983 goto fail;
984 }
985
986 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
987 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
988 ASN1_IA5STRING *uri;
989
990 if ((OBJ_obj2nid(ad->method) != nid) ||
991 (ad->location->type != GEN_URI)) {
992 continue;
993 }
994 uri = ad->location->d.uniformResourceIdentifier;
995 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
996 uri->length);
997 if (ostr == NULL) {
998 goto fail;
999 }
1000 result = PyList_Append(lst, ostr);
1001 Py_DECREF(ostr);
1002 if (result < 0) {
1003 goto fail;
1004 }
1005 }
1006 AUTHORITY_INFO_ACCESS_free(info);
1007
1008 /* convert to tuple or None */
1009 if (PyList_Size(lst) == 0) {
1010 Py_DECREF(lst);
1011 return Py_None;
1012 } else {
1013 PyObject *tup;
1014 tup = PyList_AsTuple(lst);
1015 Py_DECREF(lst);
1016 return tup;
1017 }
1018
1019 fail:
1020 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001021 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001022 return NULL;
1023}
1024
1025static PyObject *
1026_get_crl_dp(X509 *certificate) {
1027 STACK_OF(DIST_POINT) *dps;
1028 int i, j, result;
1029 PyObject *lst;
1030
Christian Heimes949ec142013-11-21 16:26:51 +01001031#if OPENSSL_VERSION_NUMBER < 0x10001000L
1032 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1033 NULL, NULL);
1034#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001035 /* Calls x509v3_cache_extensions and sets up crldp */
1036 X509_check_ca(certificate);
1037 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001038#endif
1039
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001040 if (dps == NULL) {
1041 return Py_None;
1042 }
1043
1044 if ((lst = PyList_New(0)) == NULL) {
1045 return NULL;
1046 }
1047
1048 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1049 DIST_POINT *dp;
1050 STACK_OF(GENERAL_NAME) *gns;
1051
1052 dp = sk_DIST_POINT_value(dps, i);
1053 gns = dp->distpoint->name.fullname;
1054
1055 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1056 GENERAL_NAME *gn;
1057 ASN1_IA5STRING *uri;
1058 PyObject *ouri;
1059
1060 gn = sk_GENERAL_NAME_value(gns, j);
1061 if (gn->type != GEN_URI) {
1062 continue;
1063 }
1064 uri = gn->d.uniformResourceIdentifier;
1065 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1066 uri->length);
1067 if (ouri == NULL) {
1068 Py_DECREF(lst);
1069 return NULL;
1070 }
1071 result = PyList_Append(lst, ouri);
1072 Py_DECREF(ouri);
1073 if (result < 0) {
1074 Py_DECREF(lst);
1075 return NULL;
1076 }
1077 }
1078 }
1079 /* convert to tuple or None */
1080 if (PyList_Size(lst) == 0) {
1081 Py_DECREF(lst);
1082 return Py_None;
1083 } else {
1084 PyObject *tup;
1085 tup = PyList_AsTuple(lst);
1086 Py_DECREF(lst);
1087 return tup;
1088 }
1089}
1090
1091static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001092_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 PyObject *retval = NULL;
1095 BIO *biobuf = NULL;
1096 PyObject *peer;
1097 PyObject *peer_alt_names = NULL;
1098 PyObject *issuer;
1099 PyObject *version;
1100 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001101 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 ASN1_INTEGER *serialNumber;
1103 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001104 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 ASN1_TIME *notBefore, *notAfter;
1106 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 retval = PyDict_New();
1109 if (retval == NULL)
1110 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 peer = _create_tuple_for_X509_NAME(
1113 X509_get_subject_name(certificate));
1114 if (peer == NULL)
1115 goto fail0;
1116 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1117 Py_DECREF(peer);
1118 goto fail0;
1119 }
1120 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001121
Antoine Pitroufb046912010-11-09 20:21:19 +00001122 issuer = _create_tuple_for_X509_NAME(
1123 X509_get_issuer_name(certificate));
1124 if (issuer == NULL)
1125 goto fail0;
1126 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001128 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001130 Py_DECREF(issuer);
1131
1132 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001133 if (version == NULL)
1134 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001135 if (PyDict_SetItemString(retval, "version", version) < 0) {
1136 Py_DECREF(version);
1137 goto fail0;
1138 }
1139 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 /* get a memory buffer */
1142 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001143
Antoine Pitroufb046912010-11-09 20:21:19 +00001144 (void) BIO_reset(biobuf);
1145 serialNumber = X509_get_serialNumber(certificate);
1146 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1147 i2a_ASN1_INTEGER(biobuf, serialNumber);
1148 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1149 if (len < 0) {
1150 _setSSLError(NULL, 0, __FILE__, __LINE__);
1151 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001153 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1154 if (sn_obj == NULL)
1155 goto fail1;
1156 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1157 Py_DECREF(sn_obj);
1158 goto fail1;
1159 }
1160 Py_DECREF(sn_obj);
1161
1162 (void) BIO_reset(biobuf);
1163 notBefore = X509_get_notBefore(certificate);
1164 ASN1_TIME_print(biobuf, notBefore);
1165 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1166 if (len < 0) {
1167 _setSSLError(NULL, 0, __FILE__, __LINE__);
1168 goto fail1;
1169 }
1170 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1171 if (pnotBefore == NULL)
1172 goto fail1;
1173 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1174 Py_DECREF(pnotBefore);
1175 goto fail1;
1176 }
1177 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 (void) BIO_reset(biobuf);
1180 notAfter = X509_get_notAfter(certificate);
1181 ASN1_TIME_print(biobuf, notAfter);
1182 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1183 if (len < 0) {
1184 _setSSLError(NULL, 0, __FILE__, __LINE__);
1185 goto fail1;
1186 }
1187 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1188 if (pnotAfter == NULL)
1189 goto fail1;
1190 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1191 Py_DECREF(pnotAfter);
1192 goto fail1;
1193 }
1194 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 peer_alt_names = _get_peer_alt_names(certificate);
1199 if (peer_alt_names == NULL)
1200 goto fail1;
1201 else if (peer_alt_names != Py_None) {
1202 if (PyDict_SetItemString(retval, "subjectAltName",
1203 peer_alt_names) < 0) {
1204 Py_DECREF(peer_alt_names);
1205 goto fail1;
1206 }
1207 Py_DECREF(peer_alt_names);
1208 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001209
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 /* Authority Information Access: OCSP URIs */
1211 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1212 if (obj == NULL) {
1213 goto fail1;
1214 } else if (obj != Py_None) {
1215 result = PyDict_SetItemString(retval, "OCSP", obj);
1216 Py_DECREF(obj);
1217 if (result < 0) {
1218 goto fail1;
1219 }
1220 }
1221
1222 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1223 if (obj == NULL) {
1224 goto fail1;
1225 } else if (obj != Py_None) {
1226 result = PyDict_SetItemString(retval, "caIssuers", obj);
1227 Py_DECREF(obj);
1228 if (result < 0) {
1229 goto fail1;
1230 }
1231 }
1232
1233 /* CDP (CRL distribution points) */
1234 obj = _get_crl_dp(certificate);
1235 if (obj == NULL) {
1236 goto fail1;
1237 } else if (obj != Py_None) {
1238 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1239 Py_DECREF(obj);
1240 if (result < 0) {
1241 goto fail1;
1242 }
1243 }
1244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 BIO_free(biobuf);
1246 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001247
1248 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 if (biobuf != NULL)
1250 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001251 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 Py_XDECREF(retval);
1253 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001254}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255
Christian Heimes9a5395a2013-06-17 15:44:12 +02001256static PyObject *
1257_certificate_to_der(X509 *certificate)
1258{
1259 unsigned char *bytes_buf = NULL;
1260 int len;
1261 PyObject *retval;
1262
1263 bytes_buf = NULL;
1264 len = i2d_X509(certificate, &bytes_buf);
1265 if (len < 0) {
1266 _setSSLError(NULL, 0, __FILE__, __LINE__);
1267 return NULL;
1268 }
1269 /* this is actually an immutable bytes sequence */
1270 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1271 OPENSSL_free(bytes_buf);
1272 return retval;
1273}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
1275static PyObject *
1276PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001279 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 X509 *x=NULL;
1281 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
Antoine Pitroufb046912010-11-09 20:21:19 +00001283 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1284 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1288 PyErr_SetString(PySSLErrorObject,
1289 "Can't malloc memory to read file");
1290 goto fail0;
1291 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292
Victor Stinner3800e1e2010-05-16 21:23:48 +00001293 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 PyErr_SetString(PySSLErrorObject,
1295 "Can't open file");
1296 goto fail0;
1297 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1300 if (x == NULL) {
1301 PyErr_SetString(PySSLErrorObject,
1302 "Error decoding PEM-encoded file");
1303 goto fail0;
1304 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001305
Antoine Pitroufb046912010-11-09 20:21:19 +00001306 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001307 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
1309 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001310 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 if (cert != NULL) BIO_free(cert);
1312 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313}
1314
1315
1316static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001317PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001320 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Antoine Pitrou721738f2012-08-15 23:20:39 +02001322 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324
Antoine Pitrou20b85552013-09-29 19:50:53 +02001325 if (!self->handshake_done) {
1326 PyErr_SetString(PyExc_ValueError,
1327 "handshake not done yet");
1328 return NULL;
1329 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 if (!self->peer_cert)
1331 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitrou721738f2012-08-15 23:20:39 +02001333 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001335 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001337 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 if ((verification & SSL_VERIFY_PEER) == 0)
1339 return PyDict_New();
1340 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001341 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343}
1344
1345PyDoc_STRVAR(PySSL_peercert_doc,
1346"peer_certificate([der=False]) -> certificate\n\
1347\n\
1348Returns the certificate for the peer. If no certificate was provided,\n\
1349returns None. If a certificate was provided, but not validated, returns\n\
1350an empty dictionary. Otherwise returns a dict containing information\n\
1351about the peer certificate.\n\
1352\n\
1353If the optional argument is True, returns a DER-encoded copy of the\n\
1354peer certificate, or None if no certificate was provided. This will\n\
1355return the certificate even if it wasn't validated.");
1356
Antoine Pitrou152efa22010-05-16 18:19:27 +00001357static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001360 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 char *cipher_name;
1362 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001365 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 current = SSL_get_current_cipher(self->ssl);
1367 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001368 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 retval = PyTuple_New(3);
1371 if (retval == NULL)
1372 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 cipher_name = (char *) SSL_CIPHER_get_name(current);
1375 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001376 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 PyTuple_SET_ITEM(retval, 0, Py_None);
1378 } else {
1379 v = PyUnicode_FromString(cipher_name);
1380 if (v == NULL)
1381 goto fail0;
1382 PyTuple_SET_ITEM(retval, 0, v);
1383 }
1384 cipher_protocol = SSL_CIPHER_get_version(current);
1385 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001386 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 PyTuple_SET_ITEM(retval, 1, Py_None);
1388 } else {
1389 v = PyUnicode_FromString(cipher_protocol);
1390 if (v == NULL)
1391 goto fail0;
1392 PyTuple_SET_ITEM(retval, 1, v);
1393 }
1394 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1395 if (v == NULL)
1396 goto fail0;
1397 PyTuple_SET_ITEM(retval, 2, v);
1398 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 Py_DECREF(retval);
1402 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403}
1404
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001405#ifdef OPENSSL_NPN_NEGOTIATED
1406static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1407 const unsigned char *out;
1408 unsigned int outlen;
1409
Victor Stinner4569cd52013-06-23 14:58:43 +02001410 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001411 &out, &outlen);
1412
1413 if (out == NULL)
1414 Py_RETURN_NONE;
1415 return PyUnicode_FromStringAndSize((char *) out, outlen);
1416}
1417#endif
1418
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001419static PyObject *PySSL_compression(PySSLSocket *self) {
1420#ifdef OPENSSL_NO_COMP
1421 Py_RETURN_NONE;
1422#else
1423 const COMP_METHOD *comp_method;
1424 const char *short_name;
1425
1426 if (self->ssl == NULL)
1427 Py_RETURN_NONE;
1428 comp_method = SSL_get_current_compression(self->ssl);
1429 if (comp_method == NULL || comp_method->type == NID_undef)
1430 Py_RETURN_NONE;
1431 short_name = OBJ_nid2sn(comp_method->type);
1432 if (short_name == NULL)
1433 Py_RETURN_NONE;
1434 return PyUnicode_DecodeFSDefault(short_name);
1435#endif
1436}
1437
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001438static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1439 Py_INCREF(self->ctx);
1440 return self->ctx;
1441}
1442
1443static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1444 void *closure) {
1445
1446 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001447#if !HAVE_SNI
1448 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1449 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001450 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001451#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001452 Py_INCREF(value);
1453 Py_DECREF(self->ctx);
1454 self->ctx = (PySSLContext *) value;
1455 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001456#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001457 } else {
1458 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1459 return -1;
1460 }
1461
1462 return 0;
1463}
1464
1465PyDoc_STRVAR(PySSL_set_context_doc,
1466"_setter_context(ctx)\n\
1467\
1468This changes the context associated with the SSLSocket. This is typically\n\
1469used from within a callback function set by the set_servername_callback\n\
1470on the SSLContext to change the certificate information associated with the\n\
1471SSLSocket before the cryptographic exchange handshake messages\n");
1472
1473
1474
Antoine Pitrou152efa22010-05-16 18:19:27 +00001475static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001476{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 if (self->peer_cert) /* Possible not to have one? */
1478 X509_free (self->peer_cert);
1479 if (self->ssl)
1480 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001482 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001484}
1485
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001487 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001488 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001489 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001490
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001491static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001492check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001493{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 fd_set fds;
1495 struct timeval tv;
1496 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1499 if (s->sock_timeout < 0.0)
1500 return SOCKET_IS_BLOCKING;
1501 else if (s->sock_timeout == 0.0)
1502 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 /* Guard against closed socket */
1505 if (s->sock_fd < 0)
1506 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 /* Prefer poll, if available, since you can poll() any fd
1509 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001510#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 {
1512 struct pollfd pollfd;
1513 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 pollfd.fd = s->sock_fd;
1516 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 /* s->sock_timeout is in seconds, timeout in ms */
1519 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1520 PySSL_BEGIN_ALLOW_THREADS
1521 rc = poll(&pollfd, 1, timeout);
1522 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 goto normal_return;
1525 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001526#endif
1527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001529 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 /* Construct the arguments to select */
1533 tv.tv_sec = (int)s->sock_timeout;
1534 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1535 FD_ZERO(&fds);
1536 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001537
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 /* See if the socket is ready */
1539 PySSL_BEGIN_ALLOW_THREADS
1540 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001541 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1542 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001544 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1545 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001547
Bill Janssen6e027db2007-11-15 22:23:56 +00001548#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001549normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001550#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1552 (when we are able to write or when there's something to read) */
1553 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001554}
1555
Antoine Pitrou152efa22010-05-16 18:19:27 +00001556static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001557{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 Py_buffer buf;
1559 int len;
1560 int sockstate;
1561 int err;
1562 int nonblocking;
1563 PySocketSockObject *sock
1564 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 if (((PyObject*)sock) == Py_None) {
1567 _setSSLError("Underlying socket connection gone",
1568 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1569 return NULL;
1570 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001571 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001573 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1574 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001576 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577
Victor Stinner6efa9652013-06-25 00:42:31 +02001578 if (buf.len > INT_MAX) {
1579 PyErr_Format(PyExc_OverflowError,
1580 "string longer than %d bytes", INT_MAX);
1581 goto error;
1582 }
1583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 /* just in case the blocking state of the socket has been changed */
1585 nonblocking = (sock->sock_timeout >= 0.0);
1586 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1587 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1588
1589 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1590 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001591 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 "The write operation timed out");
1593 goto error;
1594 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1595 PyErr_SetString(PySSLErrorObject,
1596 "Underlying socket has been closed.");
1597 goto error;
1598 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1599 PyErr_SetString(PySSLErrorObject,
1600 "Underlying socket too large for select().");
1601 goto error;
1602 }
1603 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001605 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 err = SSL_get_error(self->ssl, len);
1607 PySSL_END_ALLOW_THREADS
1608 if (PyErr_CheckSignals()) {
1609 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001610 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001612 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001614 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 } else {
1616 sockstate = SOCKET_OPERATION_OK;
1617 }
1618 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001619 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 "The write operation timed out");
1621 goto error;
1622 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1623 PyErr_SetString(PySSLErrorObject,
1624 "Underlying socket has been closed.");
1625 goto error;
1626 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1627 break;
1628 }
1629 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001630
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001631 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 PyBuffer_Release(&buf);
1633 if (len > 0)
1634 return PyLong_FromLong(len);
1635 else
1636 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001637
1638error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001639 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 PyBuffer_Release(&buf);
1641 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001642}
1643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001645"write(s) -> len\n\
1646\n\
1647Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001648of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001649
Antoine Pitrou152efa22010-05-16 18:19:27 +00001650static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001651{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001654 PySSL_BEGIN_ALLOW_THREADS
1655 count = SSL_pending(self->ssl);
1656 PySSL_END_ALLOW_THREADS
1657 if (count < 0)
1658 return PySSL_SetError(self, count, __FILE__, __LINE__);
1659 else
1660 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001661}
1662
1663PyDoc_STRVAR(PySSL_SSLpending_doc,
1664"pending() -> count\n\
1665\n\
1666Returns the number of already decrypted bytes available for read,\n\
1667pending on the connection.\n");
1668
Antoine Pitrou152efa22010-05-16 18:19:27 +00001669static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001670{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 PyObject *dest = NULL;
1672 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001674 int len, count;
1675 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 int sockstate;
1677 int err;
1678 int nonblocking;
1679 PySocketSockObject *sock
1680 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 if (((PyObject*)sock) == Py_None) {
1683 _setSSLError("Underlying socket connection gone",
1684 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1685 return NULL;
1686 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001687 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001689 buf.obj = NULL;
1690 buf.buf = NULL;
1691 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001692 goto error;
1693
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001694 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1695 dest = PyBytes_FromStringAndSize(NULL, len);
1696 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001697 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001698 mem = PyBytes_AS_STRING(dest);
1699 }
1700 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001702 mem = buf.buf;
1703 if (len <= 0 || len > buf.len) {
1704 len = (int) buf.len;
1705 if (buf.len != len) {
1706 PyErr_SetString(PyExc_OverflowError,
1707 "maximum length can't fit in a C 'int'");
1708 goto error;
1709 }
1710 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 }
1712
1713 /* just in case the blocking state of the socket has been changed */
1714 nonblocking = (sock->sock_timeout >= 0.0);
1715 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1716 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1717
1718 /* first check if there are bytes ready to be read */
1719 PySSL_BEGIN_ALLOW_THREADS
1720 count = SSL_pending(self->ssl);
1721 PySSL_END_ALLOW_THREADS
1722
1723 if (!count) {
1724 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1725 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001726 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 "The read operation timed out");
1728 goto error;
1729 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1730 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001731 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 goto error;
1733 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1734 count = 0;
1735 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001736 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 }
1738 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 PySSL_BEGIN_ALLOW_THREADS
1740 count = SSL_read(self->ssl, mem, len);
1741 err = SSL_get_error(self->ssl, count);
1742 PySSL_END_ALLOW_THREADS
1743 if (PyErr_CheckSignals())
1744 goto error;
1745 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001746 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001748 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1750 (SSL_get_shutdown(self->ssl) ==
1751 SSL_RECEIVED_SHUTDOWN))
1752 {
1753 count = 0;
1754 goto done;
1755 } else {
1756 sockstate = SOCKET_OPERATION_OK;
1757 }
1758 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001759 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 "The read operation timed out");
1761 goto error;
1762 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1763 break;
1764 }
1765 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1766 if (count <= 0) {
1767 PySSL_SetError(self, count, __FILE__, __LINE__);
1768 goto error;
1769 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001770
1771done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001772 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001773 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001774 _PyBytes_Resize(&dest, count);
1775 return dest;
1776 }
1777 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 PyBuffer_Release(&buf);
1779 return PyLong_FromLong(count);
1780 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001781
1782error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001783 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001784 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001785 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001786 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001789}
1790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001791PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001792"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001795
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001797{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 int err, ssl_err, sockstate, nonblocking;
1799 int zeros = 0;
1800 PySocketSockObject *sock
1801 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 /* Guard against closed socket */
1804 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1805 _setSSLError("Underlying socket connection gone",
1806 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1807 return NULL;
1808 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001809 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810
1811 /* Just in case the blocking state of the socket has been changed */
1812 nonblocking = (sock->sock_timeout >= 0.0);
1813 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1814 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1815
1816 while (1) {
1817 PySSL_BEGIN_ALLOW_THREADS
1818 /* Disable read-ahead so that unwrap can work correctly.
1819 * Otherwise OpenSSL might read in too much data,
1820 * eating clear text data that happens to be
1821 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001822 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 * function is used and the shutdown_seen_zero != 0
1824 * condition is met.
1825 */
1826 if (self->shutdown_seen_zero)
1827 SSL_set_read_ahead(self->ssl, 0);
1828 err = SSL_shutdown(self->ssl);
1829 PySSL_END_ALLOW_THREADS
1830 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1831 if (err > 0)
1832 break;
1833 if (err == 0) {
1834 /* Don't loop endlessly; instead preserve legacy
1835 behaviour of trying SSL_shutdown() only twice.
1836 This looks necessary for OpenSSL < 0.9.8m */
1837 if (++zeros > 1)
1838 break;
1839 /* Shutdown was sent, now try receiving */
1840 self->shutdown_seen_zero = 1;
1841 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001842 }
1843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 /* Possibly retry shutdown until timeout or failure */
1845 ssl_err = SSL_get_error(self->ssl, err);
1846 if (ssl_err == SSL_ERROR_WANT_READ)
1847 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1848 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1849 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1850 else
1851 break;
1852 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1853 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001854 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 "The read operation timed out");
1856 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001857 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001859 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 }
1861 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1862 PyErr_SetString(PySSLErrorObject,
1863 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001864 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 }
1866 else if (sockstate != SOCKET_OPERATION_OK)
1867 /* Retain the SSL error code */
1868 break;
1869 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001870
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001871 if (err < 0) {
1872 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001875 else
1876 /* It's already INCREF'ed */
1877 return (PyObject *) sock;
1878
1879error:
1880 Py_DECREF(sock);
1881 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001882}
1883
1884PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1885"shutdown(s) -> socket\n\
1886\n\
1887Does the SSL shutdown handshake with the remote end, and returns\n\
1888the underlying socket object.");
1889
Antoine Pitroud6494802011-07-21 01:11:30 +02001890#if HAVE_OPENSSL_FINISHED
1891static PyObject *
1892PySSL_tls_unique_cb(PySSLSocket *self)
1893{
1894 PyObject *retval = NULL;
1895 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001896 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001897
1898 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1899 /* if session is resumed XOR we are the client */
1900 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1901 }
1902 else {
1903 /* if a new session XOR we are the server */
1904 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1905 }
1906
1907 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001908 if (len == 0)
1909 Py_RETURN_NONE;
1910
1911 retval = PyBytes_FromStringAndSize(buf, len);
1912
1913 return retval;
1914}
1915
1916PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1917"tls_unique_cb() -> bytes\n\
1918\n\
1919Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1920\n\
1921If the TLS handshake is not yet complete, None is returned");
1922
1923#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001924
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001925static PyGetSetDef ssl_getsetlist[] = {
1926 {"context", (getter) PySSL_get_context,
1927 (setter) PySSL_set_context, PySSL_set_context_doc},
1928 {NULL}, /* sentinel */
1929};
1930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001931static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1933 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1934 PySSL_SSLwrite_doc},
1935 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1936 PySSL_SSLread_doc},
1937 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1938 PySSL_SSLpending_doc},
1939 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1940 PySSL_peercert_doc},
1941 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001942#ifdef OPENSSL_NPN_NEGOTIATED
1943 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1944#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001945 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1947 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001948#if HAVE_OPENSSL_FINISHED
1949 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1950 PySSL_tls_unique_cb_doc},
1951#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001953};
1954
Antoine Pitrou152efa22010-05-16 18:19:27 +00001955static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001957 "_ssl._SSLSocket", /*tp_name*/
1958 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 0, /*tp_itemsize*/
1960 /* methods */
1961 (destructor)PySSL_dealloc, /*tp_dealloc*/
1962 0, /*tp_print*/
1963 0, /*tp_getattr*/
1964 0, /*tp_setattr*/
1965 0, /*tp_reserved*/
1966 0, /*tp_repr*/
1967 0, /*tp_as_number*/
1968 0, /*tp_as_sequence*/
1969 0, /*tp_as_mapping*/
1970 0, /*tp_hash*/
1971 0, /*tp_call*/
1972 0, /*tp_str*/
1973 0, /*tp_getattro*/
1974 0, /*tp_setattro*/
1975 0, /*tp_as_buffer*/
1976 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1977 0, /*tp_doc*/
1978 0, /*tp_traverse*/
1979 0, /*tp_clear*/
1980 0, /*tp_richcompare*/
1981 0, /*tp_weaklistoffset*/
1982 0, /*tp_iter*/
1983 0, /*tp_iternext*/
1984 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001985 0, /*tp_members*/
1986 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001987};
1988
Antoine Pitrou152efa22010-05-16 18:19:27 +00001989
1990/*
1991 * _SSLContext objects
1992 */
1993
1994static PyObject *
1995context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1996{
1997 char *kwlist[] = {"protocol", NULL};
1998 PySSLContext *self;
1999 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002000 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002001 SSL_CTX *ctx = NULL;
2002
2003 if (!PyArg_ParseTupleAndKeywords(
2004 args, kwds, "i:_SSLContext", kwlist,
2005 &proto_version))
2006 return NULL;
2007
2008 PySSL_BEGIN_ALLOW_THREADS
2009 if (proto_version == PY_SSL_VERSION_TLS1)
2010 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002011#if HAVE_TLSv1_2
2012 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2013 ctx = SSL_CTX_new(TLSv1_1_method());
2014 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2015 ctx = SSL_CTX_new(TLSv1_2_method());
2016#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002017 else if (proto_version == PY_SSL_VERSION_SSL3)
2018 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002019#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002020 else if (proto_version == PY_SSL_VERSION_SSL2)
2021 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002022#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002023 else if (proto_version == PY_SSL_VERSION_SSL23)
2024 ctx = SSL_CTX_new(SSLv23_method());
2025 else
2026 proto_version = -1;
2027 PySSL_END_ALLOW_THREADS
2028
2029 if (proto_version == -1) {
2030 PyErr_SetString(PyExc_ValueError,
2031 "invalid protocol version");
2032 return NULL;
2033 }
2034 if (ctx == NULL) {
2035 PyErr_SetString(PySSLErrorObject,
2036 "failed to allocate SSL context");
2037 return NULL;
2038 }
2039
2040 assert(type != NULL && type->tp_alloc != NULL);
2041 self = (PySSLContext *) type->tp_alloc(type, 0);
2042 if (self == NULL) {
2043 SSL_CTX_free(ctx);
2044 return NULL;
2045 }
2046 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002047#ifdef OPENSSL_NPN_NEGOTIATED
2048 self->npn_protocols = NULL;
2049#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002050#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002051 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002052#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002053 /* Don't check host name by default */
2054 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002055 /* Defaults */
2056 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002057 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2058 if (proto_version != PY_SSL_VERSION_SSL2)
2059 options |= SSL_OP_NO_SSLv2;
2060 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002061
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002062#define SID_CTX "Python"
2063 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2064 sizeof(SID_CTX));
2065#undef SID_CTX
2066
Antoine Pitrou152efa22010-05-16 18:19:27 +00002067 return (PyObject *)self;
2068}
2069
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070static int
2071context_traverse(PySSLContext *self, visitproc visit, void *arg)
2072{
2073#ifndef OPENSSL_NO_TLSEXT
2074 Py_VISIT(self->set_hostname);
2075#endif
2076 return 0;
2077}
2078
2079static int
2080context_clear(PySSLContext *self)
2081{
2082#ifndef OPENSSL_NO_TLSEXT
2083 Py_CLEAR(self->set_hostname);
2084#endif
2085 return 0;
2086}
2087
Antoine Pitrou152efa22010-05-16 18:19:27 +00002088static void
2089context_dealloc(PySSLContext *self)
2090{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002091 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002092 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002093#ifdef OPENSSL_NPN_NEGOTIATED
2094 PyMem_Free(self->npn_protocols);
2095#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002096 Py_TYPE(self)->tp_free(self);
2097}
2098
2099static PyObject *
2100set_ciphers(PySSLContext *self, PyObject *args)
2101{
2102 int ret;
2103 const char *cipherlist;
2104
2105 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2106 return NULL;
2107 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2108 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002109 /* Clearing the error queue is necessary on some OpenSSL versions,
2110 otherwise the error will be reported again when another SSL call
2111 is done. */
2112 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002113 PyErr_SetString(PySSLErrorObject,
2114 "No cipher can be selected.");
2115 return NULL;
2116 }
2117 Py_RETURN_NONE;
2118}
2119
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002120#ifdef OPENSSL_NPN_NEGOTIATED
2121/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2122static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002123_advertiseNPN_cb(SSL *s,
2124 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002125 void *args)
2126{
2127 PySSLContext *ssl_ctx = (PySSLContext *) args;
2128
2129 if (ssl_ctx->npn_protocols == NULL) {
2130 *data = (unsigned char *) "";
2131 *len = 0;
2132 } else {
2133 *data = (unsigned char *) ssl_ctx->npn_protocols;
2134 *len = ssl_ctx->npn_protocols_len;
2135 }
2136
2137 return SSL_TLSEXT_ERR_OK;
2138}
2139/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2140static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002141_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002142 unsigned char **out, unsigned char *outlen,
2143 const unsigned char *server, unsigned int server_len,
2144 void *args)
2145{
2146 PySSLContext *ssl_ctx = (PySSLContext *) args;
2147
2148 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2149 int client_len;
2150
2151 if (client == NULL) {
2152 client = (unsigned char *) "";
2153 client_len = 0;
2154 } else {
2155 client_len = ssl_ctx->npn_protocols_len;
2156 }
2157
2158 SSL_select_next_proto(out, outlen,
2159 server, server_len,
2160 client, client_len);
2161
2162 return SSL_TLSEXT_ERR_OK;
2163}
2164#endif
2165
2166static PyObject *
2167_set_npn_protocols(PySSLContext *self, PyObject *args)
2168{
2169#ifdef OPENSSL_NPN_NEGOTIATED
2170 Py_buffer protos;
2171
2172 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2173 return NULL;
2174
Christian Heimes5cb31c92012-09-20 12:42:54 +02002175 if (self->npn_protocols != NULL) {
2176 PyMem_Free(self->npn_protocols);
2177 }
2178
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002179 self->npn_protocols = PyMem_Malloc(protos.len);
2180 if (self->npn_protocols == NULL) {
2181 PyBuffer_Release(&protos);
2182 return PyErr_NoMemory();
2183 }
2184 memcpy(self->npn_protocols, protos.buf, protos.len);
2185 self->npn_protocols_len = (int) protos.len;
2186
2187 /* set both server and client callbacks, because the context can
2188 * be used to create both types of sockets */
2189 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2190 _advertiseNPN_cb,
2191 self);
2192 SSL_CTX_set_next_proto_select_cb(self->ctx,
2193 _selectNPN_cb,
2194 self);
2195
2196 PyBuffer_Release(&protos);
2197 Py_RETURN_NONE;
2198#else
2199 PyErr_SetString(PyExc_NotImplementedError,
2200 "The NPN extension requires OpenSSL 1.0.1 or later.");
2201 return NULL;
2202#endif
2203}
2204
Antoine Pitrou152efa22010-05-16 18:19:27 +00002205static PyObject *
2206get_verify_mode(PySSLContext *self, void *c)
2207{
2208 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2209 case SSL_VERIFY_NONE:
2210 return PyLong_FromLong(PY_SSL_CERT_NONE);
2211 case SSL_VERIFY_PEER:
2212 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2213 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2214 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2215 }
2216 PyErr_SetString(PySSLErrorObject,
2217 "invalid return value from SSL_CTX_get_verify_mode");
2218 return NULL;
2219}
2220
2221static int
2222set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2223{
2224 int n, mode;
2225 if (!PyArg_Parse(arg, "i", &n))
2226 return -1;
2227 if (n == PY_SSL_CERT_NONE)
2228 mode = SSL_VERIFY_NONE;
2229 else if (n == PY_SSL_CERT_OPTIONAL)
2230 mode = SSL_VERIFY_PEER;
2231 else if (n == PY_SSL_CERT_REQUIRED)
2232 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2233 else {
2234 PyErr_SetString(PyExc_ValueError,
2235 "invalid value for verify_mode");
2236 return -1;
2237 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002238 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2239 PyErr_SetString(PyExc_ValueError,
2240 "Cannot set verify_mode to CERT_NONE when "
2241 "check_hostname is enabled.");
2242 return -1;
2243 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002244 SSL_CTX_set_verify(self->ctx, mode, NULL);
2245 return 0;
2246}
2247
Christian Heimes2427b502013-11-23 11:24:32 +01002248#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002249static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002250get_verify_flags(PySSLContext *self, void *c)
2251{
2252 X509_STORE *store;
2253 unsigned long flags;
2254
2255 store = SSL_CTX_get_cert_store(self->ctx);
2256 flags = X509_VERIFY_PARAM_get_flags(store->param);
2257 return PyLong_FromUnsignedLong(flags);
2258}
2259
2260static int
2261set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2262{
2263 X509_STORE *store;
2264 unsigned long new_flags, flags, set, clear;
2265
2266 if (!PyArg_Parse(arg, "k", &new_flags))
2267 return -1;
2268 store = SSL_CTX_get_cert_store(self->ctx);
2269 flags = X509_VERIFY_PARAM_get_flags(store->param);
2270 clear = flags & ~new_flags;
2271 set = ~flags & new_flags;
2272 if (clear) {
2273 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2274 _setSSLError(NULL, 0, __FILE__, __LINE__);
2275 return -1;
2276 }
2277 }
2278 if (set) {
2279 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2280 _setSSLError(NULL, 0, __FILE__, __LINE__);
2281 return -1;
2282 }
2283 }
2284 return 0;
2285}
Christian Heimes2427b502013-11-23 11:24:32 +01002286#endif
Christian Heimes22587792013-11-21 23:56:13 +01002287
2288static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002289get_options(PySSLContext *self, void *c)
2290{
2291 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2292}
2293
2294static int
2295set_options(PySSLContext *self, PyObject *arg, void *c)
2296{
2297 long new_opts, opts, set, clear;
2298 if (!PyArg_Parse(arg, "l", &new_opts))
2299 return -1;
2300 opts = SSL_CTX_get_options(self->ctx);
2301 clear = opts & ~new_opts;
2302 set = ~opts & new_opts;
2303 if (clear) {
2304#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2305 SSL_CTX_clear_options(self->ctx, clear);
2306#else
2307 PyErr_SetString(PyExc_ValueError,
2308 "can't clear options before OpenSSL 0.9.8m");
2309 return -1;
2310#endif
2311 }
2312 if (set)
2313 SSL_CTX_set_options(self->ctx, set);
2314 return 0;
2315}
2316
Christian Heimes1aa9a752013-12-02 02:41:19 +01002317static PyObject *
2318get_check_hostname(PySSLContext *self, void *c)
2319{
2320 return PyBool_FromLong(self->check_hostname);
2321}
2322
2323static int
2324set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2325{
2326 int check_hostname;
2327 if (!PyArg_Parse(arg, "p", &check_hostname))
2328 return -1;
2329 if (check_hostname &&
2330 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2331 PyErr_SetString(PyExc_ValueError,
2332 "check_hostname needs a SSL context with either "
2333 "CERT_OPTIONAL or CERT_REQUIRED");
2334 return -1;
2335 }
2336 self->check_hostname = check_hostname;
2337 return 0;
2338}
2339
2340
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002341typedef struct {
2342 PyThreadState *thread_state;
2343 PyObject *callable;
2344 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002345 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002346 int error;
2347} _PySSLPasswordInfo;
2348
2349static int
2350_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2351 const char *bad_type_error)
2352{
2353 /* Set the password and size fields of a _PySSLPasswordInfo struct
2354 from a unicode, bytes, or byte array object.
2355 The password field will be dynamically allocated and must be freed
2356 by the caller */
2357 PyObject *password_bytes = NULL;
2358 const char *data = NULL;
2359 Py_ssize_t size;
2360
2361 if (PyUnicode_Check(password)) {
2362 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2363 if (!password_bytes) {
2364 goto error;
2365 }
2366 data = PyBytes_AS_STRING(password_bytes);
2367 size = PyBytes_GET_SIZE(password_bytes);
2368 } else if (PyBytes_Check(password)) {
2369 data = PyBytes_AS_STRING(password);
2370 size = PyBytes_GET_SIZE(password);
2371 } else if (PyByteArray_Check(password)) {
2372 data = PyByteArray_AS_STRING(password);
2373 size = PyByteArray_GET_SIZE(password);
2374 } else {
2375 PyErr_SetString(PyExc_TypeError, bad_type_error);
2376 goto error;
2377 }
2378
Victor Stinner9ee02032013-06-23 15:08:23 +02002379 if (size > (Py_ssize_t)INT_MAX) {
2380 PyErr_Format(PyExc_ValueError,
2381 "password cannot be longer than %d bytes", INT_MAX);
2382 goto error;
2383 }
2384
Victor Stinner11ebff22013-07-07 17:07:52 +02002385 PyMem_Free(pw_info->password);
2386 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002387 if (!pw_info->password) {
2388 PyErr_SetString(PyExc_MemoryError,
2389 "unable to allocate password buffer");
2390 goto error;
2391 }
2392 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002393 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002394
2395 Py_XDECREF(password_bytes);
2396 return 1;
2397
2398error:
2399 Py_XDECREF(password_bytes);
2400 return 0;
2401}
2402
2403static int
2404_password_callback(char *buf, int size, int rwflag, void *userdata)
2405{
2406 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2407 PyObject *fn_ret = NULL;
2408
2409 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2410
2411 if (pw_info->callable) {
2412 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2413 if (!fn_ret) {
2414 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2415 core python API, so we could use it to add a frame here */
2416 goto error;
2417 }
2418
2419 if (!_pwinfo_set(pw_info, fn_ret,
2420 "password callback must return a string")) {
2421 goto error;
2422 }
2423 Py_CLEAR(fn_ret);
2424 }
2425
2426 if (pw_info->size > size) {
2427 PyErr_Format(PyExc_ValueError,
2428 "password cannot be longer than %d bytes", size);
2429 goto error;
2430 }
2431
2432 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2433 memcpy(buf, pw_info->password, pw_info->size);
2434 return pw_info->size;
2435
2436error:
2437 Py_XDECREF(fn_ret);
2438 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2439 pw_info->error = 1;
2440 return -1;
2441}
2442
Antoine Pitroub5218772010-05-21 09:56:06 +00002443static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002444load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2445{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002446 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2447 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002448 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002449 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2450 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2451 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002452 int r;
2453
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002454 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002455 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002456 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002457 "O|OO:load_cert_chain", kwlist,
2458 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002459 return NULL;
2460 if (keyfile == Py_None)
2461 keyfile = NULL;
2462 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2463 PyErr_SetString(PyExc_TypeError,
2464 "certfile should be a valid filesystem path");
2465 return NULL;
2466 }
2467 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2468 PyErr_SetString(PyExc_TypeError,
2469 "keyfile should be a valid filesystem path");
2470 goto error;
2471 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002472 if (password && password != Py_None) {
2473 if (PyCallable_Check(password)) {
2474 pw_info.callable = password;
2475 } else if (!_pwinfo_set(&pw_info, password,
2476 "password should be a string or callable")) {
2477 goto error;
2478 }
2479 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2480 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2481 }
2482 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002483 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2484 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002485 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002486 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002487 if (pw_info.error) {
2488 ERR_clear_error();
2489 /* the password callback has already set the error information */
2490 }
2491 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002492 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002493 PyErr_SetFromErrno(PyExc_IOError);
2494 }
2495 else {
2496 _setSSLError(NULL, 0, __FILE__, __LINE__);
2497 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002498 goto error;
2499 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002500 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002501 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002502 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2503 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002504 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2505 Py_CLEAR(keyfile_bytes);
2506 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002507 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002508 if (pw_info.error) {
2509 ERR_clear_error();
2510 /* the password callback has already set the error information */
2511 }
2512 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002513 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002514 PyErr_SetFromErrno(PyExc_IOError);
2515 }
2516 else {
2517 _setSSLError(NULL, 0, __FILE__, __LINE__);
2518 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002519 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002520 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002521 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002522 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002523 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002524 if (r != 1) {
2525 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002526 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002527 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002528 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2529 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002530 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002531 Py_RETURN_NONE;
2532
2533error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002534 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2535 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002536 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002537 Py_XDECREF(keyfile_bytes);
2538 Py_XDECREF(certfile_bytes);
2539 return NULL;
2540}
2541
Christian Heimesefff7062013-11-21 03:35:02 +01002542/* internal helper function, returns -1 on error
2543 */
2544static int
2545_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2546 int filetype)
2547{
2548 BIO *biobuf = NULL;
2549 X509_STORE *store;
2550 int retval = 0, err, loaded = 0;
2551
2552 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2553
2554 if (len <= 0) {
2555 PyErr_SetString(PyExc_ValueError,
2556 "Empty certificate data");
2557 return -1;
2558 } else if (len > INT_MAX) {
2559 PyErr_SetString(PyExc_OverflowError,
2560 "Certificate data is too long.");
2561 return -1;
2562 }
2563
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002564 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002565 if (biobuf == NULL) {
2566 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2567 return -1;
2568 }
2569
2570 store = SSL_CTX_get_cert_store(self->ctx);
2571 assert(store != NULL);
2572
2573 while (1) {
2574 X509 *cert = NULL;
2575 int r;
2576
2577 if (filetype == SSL_FILETYPE_ASN1) {
2578 cert = d2i_X509_bio(biobuf, NULL);
2579 } else {
2580 cert = PEM_read_bio_X509(biobuf, NULL,
2581 self->ctx->default_passwd_callback,
2582 self->ctx->default_passwd_callback_userdata);
2583 }
2584 if (cert == NULL) {
2585 break;
2586 }
2587 r = X509_STORE_add_cert(store, cert);
2588 X509_free(cert);
2589 if (!r) {
2590 err = ERR_peek_last_error();
2591 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2592 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2593 /* cert already in hash table, not an error */
2594 ERR_clear_error();
2595 } else {
2596 break;
2597 }
2598 }
2599 loaded++;
2600 }
2601
2602 err = ERR_peek_last_error();
2603 if ((filetype == SSL_FILETYPE_ASN1) &&
2604 (loaded > 0) &&
2605 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2606 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2607 /* EOF ASN1 file, not an error */
2608 ERR_clear_error();
2609 retval = 0;
2610 } else if ((filetype == SSL_FILETYPE_PEM) &&
2611 (loaded > 0) &&
2612 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2613 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2614 /* EOF PEM file, not an error */
2615 ERR_clear_error();
2616 retval = 0;
2617 } else {
2618 _setSSLError(NULL, 0, __FILE__, __LINE__);
2619 retval = -1;
2620 }
2621
2622 BIO_free(biobuf);
2623 return retval;
2624}
2625
2626
Antoine Pitrou152efa22010-05-16 18:19:27 +00002627static PyObject *
2628load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2629{
Christian Heimesefff7062013-11-21 03:35:02 +01002630 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2631 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002632 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2633 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002634 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002635
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002636 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002637 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002638 "|OOO:load_verify_locations", kwlist,
2639 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002641
Antoine Pitrou152efa22010-05-16 18:19:27 +00002642 if (cafile == Py_None)
2643 cafile = NULL;
2644 if (capath == Py_None)
2645 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002646 if (cadata == Py_None)
2647 cadata = NULL;
2648
2649 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002650 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002651 "cafile, capath and cadata cannot be all omitted");
2652 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002653 }
2654 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2655 PyErr_SetString(PyExc_TypeError,
2656 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002657 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002658 }
2659 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002660 PyErr_SetString(PyExc_TypeError,
2661 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002662 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002663 }
Christian Heimesefff7062013-11-21 03:35:02 +01002664
2665 /* validata cadata type and load cadata */
2666 if (cadata) {
2667 Py_buffer buf;
2668 PyObject *cadata_ascii = NULL;
2669
2670 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2671 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2672 PyBuffer_Release(&buf);
2673 PyErr_SetString(PyExc_TypeError,
2674 "cadata should be a contiguous buffer with "
2675 "a single dimension");
2676 goto error;
2677 }
2678 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2679 PyBuffer_Release(&buf);
2680 if (r == -1) {
2681 goto error;
2682 }
2683 } else {
2684 PyErr_Clear();
2685 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2686 if (cadata_ascii == NULL) {
2687 PyErr_SetString(PyExc_TypeError,
2688 "cadata should be a ASCII string or a "
2689 "bytes-like object");
2690 goto error;
2691 }
2692 r = _add_ca_certs(self,
2693 PyBytes_AS_STRING(cadata_ascii),
2694 PyBytes_GET_SIZE(cadata_ascii),
2695 SSL_FILETYPE_PEM);
2696 Py_DECREF(cadata_ascii);
2697 if (r == -1) {
2698 goto error;
2699 }
2700 }
2701 }
2702
2703 /* load cafile or capath */
2704 if (cafile || capath) {
2705 if (cafile)
2706 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2707 if (capath)
2708 capath_buf = PyBytes_AS_STRING(capath_bytes);
2709 PySSL_BEGIN_ALLOW_THREADS
2710 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2711 PySSL_END_ALLOW_THREADS
2712 if (r != 1) {
2713 ok = 0;
2714 if (errno != 0) {
2715 ERR_clear_error();
2716 PyErr_SetFromErrno(PyExc_IOError);
2717 }
2718 else {
2719 _setSSLError(NULL, 0, __FILE__, __LINE__);
2720 }
2721 goto error;
2722 }
2723 }
2724 goto end;
2725
2726 error:
2727 ok = 0;
2728 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002729 Py_XDECREF(cafile_bytes);
2730 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002731 if (ok) {
2732 Py_RETURN_NONE;
2733 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734 return NULL;
2735 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736}
2737
2738static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002739load_dh_params(PySSLContext *self, PyObject *filepath)
2740{
2741 FILE *f;
2742 DH *dh;
2743
Victor Stinnerdaf45552013-08-28 00:53:59 +02002744 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002745 if (f == NULL) {
2746 if (!PyErr_Occurred())
2747 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2748 return NULL;
2749 }
2750 errno = 0;
2751 PySSL_BEGIN_ALLOW_THREADS
2752 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002753 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002754 PySSL_END_ALLOW_THREADS
2755 if (dh == NULL) {
2756 if (errno != 0) {
2757 ERR_clear_error();
2758 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2759 }
2760 else {
2761 _setSSLError(NULL, 0, __FILE__, __LINE__);
2762 }
2763 return NULL;
2764 }
2765 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2766 _setSSLError(NULL, 0, __FILE__, __LINE__);
2767 DH_free(dh);
2768 Py_RETURN_NONE;
2769}
2770
2771static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002772context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2773{
Antoine Pitroud5323212010-10-22 18:19:07 +00002774 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002775 PySocketSockObject *sock;
2776 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002777 char *hostname = NULL;
2778 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002779
Antoine Pitroud5323212010-10-22 18:19:07 +00002780 /* server_hostname is either None (or absent), or to be encoded
2781 using the idna encoding. */
2782 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002783 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002784 &sock, &server_side,
2785 Py_TYPE(Py_None), &hostname_obj)) {
2786 PyErr_Clear();
2787 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2788 PySocketModule.Sock_Type,
2789 &sock, &server_side,
2790 "idna", &hostname))
2791 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002792#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002793 PyMem_Free(hostname);
2794 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2795 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002796 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002797#endif
2798 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002800 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002801 hostname);
2802 if (hostname != NULL)
2803 PyMem_Free(hostname);
2804 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805}
2806
Antoine Pitroub0182c82010-10-12 20:09:02 +00002807static PyObject *
2808session_stats(PySSLContext *self, PyObject *unused)
2809{
2810 int r;
2811 PyObject *value, *stats = PyDict_New();
2812 if (!stats)
2813 return NULL;
2814
2815#define ADD_STATS(SSL_NAME, KEY_NAME) \
2816 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2817 if (value == NULL) \
2818 goto error; \
2819 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2820 Py_DECREF(value); \
2821 if (r < 0) \
2822 goto error;
2823
2824 ADD_STATS(number, "number");
2825 ADD_STATS(connect, "connect");
2826 ADD_STATS(connect_good, "connect_good");
2827 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2828 ADD_STATS(accept, "accept");
2829 ADD_STATS(accept_good, "accept_good");
2830 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2831 ADD_STATS(accept, "accept");
2832 ADD_STATS(hits, "hits");
2833 ADD_STATS(misses, "misses");
2834 ADD_STATS(timeouts, "timeouts");
2835 ADD_STATS(cache_full, "cache_full");
2836
2837#undef ADD_STATS
2838
2839 return stats;
2840
2841error:
2842 Py_DECREF(stats);
2843 return NULL;
2844}
2845
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002846static PyObject *
2847set_default_verify_paths(PySSLContext *self, PyObject *unused)
2848{
2849 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2850 _setSSLError(NULL, 0, __FILE__, __LINE__);
2851 return NULL;
2852 }
2853 Py_RETURN_NONE;
2854}
2855
Antoine Pitrou501da612011-12-21 09:27:41 +01002856#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002857static PyObject *
2858set_ecdh_curve(PySSLContext *self, PyObject *name)
2859{
2860 PyObject *name_bytes;
2861 int nid;
2862 EC_KEY *key;
2863
2864 if (!PyUnicode_FSConverter(name, &name_bytes))
2865 return NULL;
2866 assert(PyBytes_Check(name_bytes));
2867 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2868 Py_DECREF(name_bytes);
2869 if (nid == 0) {
2870 PyErr_Format(PyExc_ValueError,
2871 "unknown elliptic curve name %R", name);
2872 return NULL;
2873 }
2874 key = EC_KEY_new_by_curve_name(nid);
2875 if (key == NULL) {
2876 _setSSLError(NULL, 0, __FILE__, __LINE__);
2877 return NULL;
2878 }
2879 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2880 EC_KEY_free(key);
2881 Py_RETURN_NONE;
2882}
Antoine Pitrou501da612011-12-21 09:27:41 +01002883#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002884
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002885#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002886static int
2887_servername_callback(SSL *s, int *al, void *args)
2888{
2889 int ret;
2890 PySSLContext *ssl_ctx = (PySSLContext *) args;
2891 PySSLSocket *ssl;
2892 PyObject *servername_o;
2893 PyObject *servername_idna;
2894 PyObject *result;
2895 /* The high-level ssl.SSLSocket object */
2896 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002897 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002898#ifdef WITH_THREAD
2899 PyGILState_STATE gstate = PyGILState_Ensure();
2900#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002901
2902 if (ssl_ctx->set_hostname == NULL) {
2903 /* remove race condition in this the call back while if removing the
2904 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002905#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002906 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002907#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002908 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002909 }
2910
2911 ssl = SSL_get_app_data(s);
2912 assert(PySSLSocket_Check(ssl));
2913 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2914 Py_INCREF(ssl_socket);
2915 if (ssl_socket == Py_None) {
2916 goto error;
2917 }
Victor Stinner7e001512013-06-25 00:44:31 +02002918
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002919 if (servername == NULL) {
2920 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2921 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002922 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002923 else {
2924 servername_o = PyBytes_FromString(servername);
2925 if (servername_o == NULL) {
2926 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2927 goto error;
2928 }
2929 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2930 if (servername_idna == NULL) {
2931 PyErr_WriteUnraisable(servername_o);
2932 Py_DECREF(servername_o);
2933 goto error;
2934 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002935 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002936 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2937 servername_idna, ssl_ctx, NULL);
2938 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002939 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002940 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002941
2942 if (result == NULL) {
2943 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2944 *al = SSL_AD_HANDSHAKE_FAILURE;
2945 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2946 }
2947 else {
2948 if (result != Py_None) {
2949 *al = (int) PyLong_AsLong(result);
2950 if (PyErr_Occurred()) {
2951 PyErr_WriteUnraisable(result);
2952 *al = SSL_AD_INTERNAL_ERROR;
2953 }
2954 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2955 }
2956 else {
2957 ret = SSL_TLSEXT_ERR_OK;
2958 }
2959 Py_DECREF(result);
2960 }
2961
Stefan Krah20d60802013-01-17 17:07:17 +01002962#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002963 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002964#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002965 return ret;
2966
2967error:
2968 Py_DECREF(ssl_socket);
2969 *al = SSL_AD_INTERNAL_ERROR;
2970 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002971#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002972 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002973#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002974 return ret;
2975}
Antoine Pitroua5963382013-03-30 16:39:00 +01002976#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002977
2978PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2979"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002980\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002981This sets a callback that will be called when a server name is provided by\n\
2982the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002983\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002984If the argument is None then the callback is disabled. The method is called\n\
2985with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002986See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002987
2988static PyObject *
2989set_servername_callback(PySSLContext *self, PyObject *args)
2990{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002991#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002992 PyObject *cb;
2993
2994 if (!PyArg_ParseTuple(args, "O", &cb))
2995 return NULL;
2996
2997 Py_CLEAR(self->set_hostname);
2998 if (cb == Py_None) {
2999 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3000 }
3001 else {
3002 if (!PyCallable_Check(cb)) {
3003 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3004 PyErr_SetString(PyExc_TypeError,
3005 "not a callable object");
3006 return NULL;
3007 }
3008 Py_INCREF(cb);
3009 self->set_hostname = cb;
3010 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3011 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3012 }
3013 Py_RETURN_NONE;
3014#else
3015 PyErr_SetString(PyExc_NotImplementedError,
3016 "The TLS extension servername callback, "
3017 "SSL_CTX_set_tlsext_servername_callback, "
3018 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003019 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003020#endif
3021}
3022
Christian Heimes9a5395a2013-06-17 15:44:12 +02003023PyDoc_STRVAR(PySSL_get_stats_doc,
3024"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3025\n\
3026Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3027CA extension and certificate revocation lists inside the context's cert\n\
3028store.\n\
3029NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3030been used at least once.");
3031
3032static PyObject *
3033cert_store_stats(PySSLContext *self)
3034{
3035 X509_STORE *store;
3036 X509_OBJECT *obj;
3037 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3038
3039 store = SSL_CTX_get_cert_store(self->ctx);
3040 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3041 obj = sk_X509_OBJECT_value(store->objs, i);
3042 switch (obj->type) {
3043 case X509_LU_X509:
3044 x509++;
3045 if (X509_check_ca(obj->data.x509)) {
3046 ca++;
3047 }
3048 break;
3049 case X509_LU_CRL:
3050 crl++;
3051 break;
3052 case X509_LU_PKEY:
3053 pkey++;
3054 break;
3055 default:
3056 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3057 * As far as I can tell they are internal states and never
3058 * stored in a cert store */
3059 break;
3060 }
3061 }
3062 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3063 "x509_ca", ca);
3064}
3065
3066PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003067"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003068\n\
3069Returns a list of dicts with information of loaded CA certs. If the\n\
3070optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3071NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3072been used at least once.");
3073
3074static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003075get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003076{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003077 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003078 X509_STORE *store;
3079 PyObject *ci = NULL, *rlist = NULL;
3080 int i;
3081 int binary_mode = 0;
3082
Christian Heimesf22e8e52013-11-22 02:22:51 +01003083 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3084 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003085 return NULL;
3086 }
3087
3088 if ((rlist = PyList_New(0)) == NULL) {
3089 return NULL;
3090 }
3091
3092 store = SSL_CTX_get_cert_store(self->ctx);
3093 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3094 X509_OBJECT *obj;
3095 X509 *cert;
3096
3097 obj = sk_X509_OBJECT_value(store->objs, i);
3098 if (obj->type != X509_LU_X509) {
3099 /* not a x509 cert */
3100 continue;
3101 }
3102 /* CA for any purpose */
3103 cert = obj->data.x509;
3104 if (!X509_check_ca(cert)) {
3105 continue;
3106 }
3107 if (binary_mode) {
3108 ci = _certificate_to_der(cert);
3109 } else {
3110 ci = _decode_certificate(cert);
3111 }
3112 if (ci == NULL) {
3113 goto error;
3114 }
3115 if (PyList_Append(rlist, ci) == -1) {
3116 goto error;
3117 }
3118 Py_CLEAR(ci);
3119 }
3120 return rlist;
3121
3122 error:
3123 Py_XDECREF(ci);
3124 Py_XDECREF(rlist);
3125 return NULL;
3126}
3127
3128
Antoine Pitrou152efa22010-05-16 18:19:27 +00003129static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003130 {"check_hostname", (getter) get_check_hostname,
3131 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003132 {"options", (getter) get_options,
3133 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003134#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003135 {"verify_flags", (getter) get_verify_flags,
3136 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003137#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003138 {"verify_mode", (getter) get_verify_mode,
3139 (setter) set_verify_mode, NULL},
3140 {NULL}, /* sentinel */
3141};
3142
3143static struct PyMethodDef context_methods[] = {
3144 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3145 METH_VARARGS | METH_KEYWORDS, NULL},
3146 {"set_ciphers", (PyCFunction) set_ciphers,
3147 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003148 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3149 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150 {"load_cert_chain", (PyCFunction) load_cert_chain,
3151 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003152 {"load_dh_params", (PyCFunction) load_dh_params,
3153 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003154 {"load_verify_locations", (PyCFunction) load_verify_locations,
3155 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003156 {"session_stats", (PyCFunction) session_stats,
3157 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003158 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3159 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003160#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003161 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3162 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003163#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003164 {"set_servername_callback", (PyCFunction) set_servername_callback,
3165 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003166 {"cert_store_stats", (PyCFunction) cert_store_stats,
3167 METH_NOARGS, PySSL_get_stats_doc},
3168 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003169 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003170 {NULL, NULL} /* sentinel */
3171};
3172
3173static PyTypeObject PySSLContext_Type = {
3174 PyVarObject_HEAD_INIT(NULL, 0)
3175 "_ssl._SSLContext", /*tp_name*/
3176 sizeof(PySSLContext), /*tp_basicsize*/
3177 0, /*tp_itemsize*/
3178 (destructor)context_dealloc, /*tp_dealloc*/
3179 0, /*tp_print*/
3180 0, /*tp_getattr*/
3181 0, /*tp_setattr*/
3182 0, /*tp_reserved*/
3183 0, /*tp_repr*/
3184 0, /*tp_as_number*/
3185 0, /*tp_as_sequence*/
3186 0, /*tp_as_mapping*/
3187 0, /*tp_hash*/
3188 0, /*tp_call*/
3189 0, /*tp_str*/
3190 0, /*tp_getattro*/
3191 0, /*tp_setattro*/
3192 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003193 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003194 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003195 (traverseproc) context_traverse, /*tp_traverse*/
3196 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003197 0, /*tp_richcompare*/
3198 0, /*tp_weaklistoffset*/
3199 0, /*tp_iter*/
3200 0, /*tp_iternext*/
3201 context_methods, /*tp_methods*/
3202 0, /*tp_members*/
3203 context_getsetlist, /*tp_getset*/
3204 0, /*tp_base*/
3205 0, /*tp_dict*/
3206 0, /*tp_descr_get*/
3207 0, /*tp_descr_set*/
3208 0, /*tp_dictoffset*/
3209 0, /*tp_init*/
3210 0, /*tp_alloc*/
3211 context_new, /*tp_new*/
3212};
3213
3214
3215
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003216#ifdef HAVE_OPENSSL_RAND
3217
3218/* helper routines for seeding the SSL PRNG */
3219static PyObject *
3220PySSL_RAND_add(PyObject *self, PyObject *args)
3221{
3222 char *buf;
3223 int len;
3224 double entropy;
3225
3226 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003227 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003228 RAND_add(buf, len, entropy);
3229 Py_INCREF(Py_None);
3230 return Py_None;
3231}
3232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003233PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003234"RAND_add(string, entropy)\n\
3235\n\
3236Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003237bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003238
3239static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003240PySSL_RAND(int len, int pseudo)
3241{
3242 int ok;
3243 PyObject *bytes;
3244 unsigned long err;
3245 const char *errstr;
3246 PyObject *v;
3247
Victor Stinner1e81a392013-12-19 16:47:04 +01003248 if (len < 0) {
3249 PyErr_SetString(PyExc_ValueError, "num must be positive");
3250 return NULL;
3251 }
3252
Victor Stinner99c8b162011-05-24 12:05:19 +02003253 bytes = PyBytes_FromStringAndSize(NULL, len);
3254 if (bytes == NULL)
3255 return NULL;
3256 if (pseudo) {
3257 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3258 if (ok == 0 || ok == 1)
3259 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3260 }
3261 else {
3262 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3263 if (ok == 1)
3264 return bytes;
3265 }
3266 Py_DECREF(bytes);
3267
3268 err = ERR_get_error();
3269 errstr = ERR_reason_error_string(err);
3270 v = Py_BuildValue("(ks)", err, errstr);
3271 if (v != NULL) {
3272 PyErr_SetObject(PySSLErrorObject, v);
3273 Py_DECREF(v);
3274 }
3275 return NULL;
3276}
3277
3278static PyObject *
3279PySSL_RAND_bytes(PyObject *self, PyObject *args)
3280{
3281 int len;
3282 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3283 return NULL;
3284 return PySSL_RAND(len, 0);
3285}
3286
3287PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3288"RAND_bytes(n) -> bytes\n\
3289\n\
3290Generate n cryptographically strong pseudo-random bytes.");
3291
3292static PyObject *
3293PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3294{
3295 int len;
3296 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3297 return NULL;
3298 return PySSL_RAND(len, 1);
3299}
3300
3301PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3302"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3303\n\
3304Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3305generated are cryptographically strong.");
3306
3307static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003308PySSL_RAND_status(PyObject *self)
3309{
Christian Heimes217cfd12007-12-02 14:31:20 +00003310 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003311}
3312
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003313PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003314"RAND_status() -> 0 or 1\n\
3315\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003316Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3317It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3318using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003319
3320static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003321PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003322{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003323 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003324 int bytes;
3325
Jesus Ceac8754a12012-09-11 02:00:58 +02003326 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003327 PyUnicode_FSConverter, &path))
3328 return NULL;
3329
3330 bytes = RAND_egd(PyBytes_AsString(path));
3331 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003332 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003333 PyErr_SetString(PySSLErrorObject,
3334 "EGD connection failed or EGD did not return "
3335 "enough data to seed the PRNG");
3336 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003337 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003338 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003339}
3340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003341PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003342"RAND_egd(path) -> bytes\n\
3343\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003344Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3345Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003346fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003347
Christian Heimesf77b4b22013-08-21 13:26:05 +02003348#endif /* HAVE_OPENSSL_RAND */
3349
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003350
Christian Heimes6d7ad132013-06-09 18:02:55 +02003351PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3352"get_default_verify_paths() -> tuple\n\
3353\n\
3354Return search paths and environment vars that are used by SSLContext's\n\
3355set_default_verify_paths() to load default CAs. The values are\n\
3356'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3357
3358static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003359PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003360{
3361 PyObject *ofile_env = NULL;
3362 PyObject *ofile = NULL;
3363 PyObject *odir_env = NULL;
3364 PyObject *odir = NULL;
3365
3366#define convert(info, target) { \
3367 const char *tmp = (info); \
3368 target = NULL; \
3369 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3370 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3371 target = PyBytes_FromString(tmp); } \
3372 if (!target) goto error; \
3373 } while(0)
3374
3375 convert(X509_get_default_cert_file_env(), ofile_env);
3376 convert(X509_get_default_cert_file(), ofile);
3377 convert(X509_get_default_cert_dir_env(), odir_env);
3378 convert(X509_get_default_cert_dir(), odir);
3379#undef convert
3380
Christian Heimes200bb1b2013-06-14 15:14:29 +02003381 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003382
3383 error:
3384 Py_XDECREF(ofile_env);
3385 Py_XDECREF(ofile);
3386 Py_XDECREF(odir_env);
3387 Py_XDECREF(odir);
3388 return NULL;
3389}
3390
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003391static PyObject*
3392asn1obj2py(ASN1_OBJECT *obj)
3393{
3394 int nid;
3395 const char *ln, *sn;
3396 char buf[100];
3397 int buflen;
3398
3399 nid = OBJ_obj2nid(obj);
3400 if (nid == NID_undef) {
3401 PyErr_Format(PyExc_ValueError, "Unknown object");
3402 return NULL;
3403 }
3404 sn = OBJ_nid2sn(nid);
3405 ln = OBJ_nid2ln(nid);
3406 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3407 if (buflen < 0) {
3408 _setSSLError(NULL, 0, __FILE__, __LINE__);
3409 return NULL;
3410 }
3411 if (buflen) {
3412 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3413 } else {
3414 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3415 }
3416}
3417
3418PyDoc_STRVAR(PySSL_txt2obj_doc,
3419"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3420\n\
3421Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3422objects are looked up by OID. With name=True short and long name are also\n\
3423matched.");
3424
3425static PyObject*
3426PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3427{
3428 char *kwlist[] = {"txt", "name", NULL};
3429 PyObject *result = NULL;
3430 char *txt;
3431 int name = 0;
3432 ASN1_OBJECT *obj;
3433
3434 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3435 kwlist, &txt, &name)) {
3436 return NULL;
3437 }
3438 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3439 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003440 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003441 return NULL;
3442 }
3443 result = asn1obj2py(obj);
3444 ASN1_OBJECT_free(obj);
3445 return result;
3446}
3447
3448PyDoc_STRVAR(PySSL_nid2obj_doc,
3449"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3450\n\
3451Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3452
3453static PyObject*
3454PySSL_nid2obj(PyObject *self, PyObject *args)
3455{
3456 PyObject *result = NULL;
3457 int nid;
3458 ASN1_OBJECT *obj;
3459
3460 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3461 return NULL;
3462 }
3463 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003464 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003465 return NULL;
3466 }
3467 obj = OBJ_nid2obj(nid);
3468 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003469 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003470 return NULL;
3471 }
3472 result = asn1obj2py(obj);
3473 ASN1_OBJECT_free(obj);
3474 return result;
3475}
3476
Christian Heimes46bebee2013-06-09 19:03:31 +02003477#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003478
3479static PyObject*
3480certEncodingType(DWORD encodingType)
3481{
3482 static PyObject *x509_asn = NULL;
3483 static PyObject *pkcs_7_asn = NULL;
3484
3485 if (x509_asn == NULL) {
3486 x509_asn = PyUnicode_InternFromString("x509_asn");
3487 if (x509_asn == NULL)
3488 return NULL;
3489 }
3490 if (pkcs_7_asn == NULL) {
3491 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3492 if (pkcs_7_asn == NULL)
3493 return NULL;
3494 }
3495 switch(encodingType) {
3496 case X509_ASN_ENCODING:
3497 Py_INCREF(x509_asn);
3498 return x509_asn;
3499 case PKCS_7_ASN_ENCODING:
3500 Py_INCREF(pkcs_7_asn);
3501 return pkcs_7_asn;
3502 default:
3503 return PyLong_FromLong(encodingType);
3504 }
3505}
3506
3507static PyObject*
3508parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3509{
3510 CERT_ENHKEY_USAGE *usage;
3511 DWORD size, error, i;
3512 PyObject *retval;
3513
3514 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3515 error = GetLastError();
3516 if (error == CRYPT_E_NOT_FOUND) {
3517 Py_RETURN_TRUE;
3518 }
3519 return PyErr_SetFromWindowsErr(error);
3520 }
3521
3522 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3523 if (usage == NULL) {
3524 return PyErr_NoMemory();
3525 }
3526
3527 /* Now get the actual enhanced usage property */
3528 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3529 PyMem_Free(usage);
3530 error = GetLastError();
3531 if (error == CRYPT_E_NOT_FOUND) {
3532 Py_RETURN_TRUE;
3533 }
3534 return PyErr_SetFromWindowsErr(error);
3535 }
3536 retval = PySet_New(NULL);
3537 if (retval == NULL) {
3538 goto error;
3539 }
3540 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3541 if (usage->rgpszUsageIdentifier[i]) {
3542 PyObject *oid;
3543 int err;
3544 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3545 if (oid == NULL) {
3546 Py_CLEAR(retval);
3547 goto error;
3548 }
3549 err = PySet_Add(retval, oid);
3550 Py_DECREF(oid);
3551 if (err == -1) {
3552 Py_CLEAR(retval);
3553 goto error;
3554 }
3555 }
3556 }
3557 error:
3558 PyMem_Free(usage);
3559 return retval;
3560}
3561
3562PyDoc_STRVAR(PySSL_enum_certificates_doc,
3563"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003564\n\
3565Retrieve certificates from Windows' cert store. store_name may be one of\n\
3566'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003567The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003568encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003569PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3570boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003571
Christian Heimes46bebee2013-06-09 19:03:31 +02003572static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003573PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003574{
Christian Heimes44109d72013-11-22 01:51:30 +01003575 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003576 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003577 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003578 PCCERT_CONTEXT pCertCtx = NULL;
3579 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003580 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003581
Christian Heimes44109d72013-11-22 01:51:30 +01003582 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3583 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003584 return NULL;
3585 }
Christian Heimes44109d72013-11-22 01:51:30 +01003586 result = PyList_New(0);
3587 if (result == NULL) {
3588 return NULL;
3589 }
3590 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3591 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003592 Py_DECREF(result);
3593 return PyErr_SetFromWindowsErr(GetLastError());
3594 }
3595
Christian Heimes44109d72013-11-22 01:51:30 +01003596 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3597 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3598 pCertCtx->cbCertEncoded);
3599 if (!cert) {
3600 Py_CLEAR(result);
3601 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003602 }
Christian Heimes44109d72013-11-22 01:51:30 +01003603 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3604 Py_CLEAR(result);
3605 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003606 }
Christian Heimes44109d72013-11-22 01:51:30 +01003607 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3608 if (keyusage == Py_True) {
3609 Py_DECREF(keyusage);
3610 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003611 }
Christian Heimes44109d72013-11-22 01:51:30 +01003612 if (keyusage == NULL) {
3613 Py_CLEAR(result);
3614 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003615 }
Christian Heimes44109d72013-11-22 01:51:30 +01003616 if ((tup = PyTuple_New(3)) == NULL) {
3617 Py_CLEAR(result);
3618 break;
3619 }
3620 PyTuple_SET_ITEM(tup, 0, cert);
3621 cert = NULL;
3622 PyTuple_SET_ITEM(tup, 1, enc);
3623 enc = NULL;
3624 PyTuple_SET_ITEM(tup, 2, keyusage);
3625 keyusage = NULL;
3626 if (PyList_Append(result, tup) < 0) {
3627 Py_CLEAR(result);
3628 break;
3629 }
3630 Py_CLEAR(tup);
3631 }
3632 if (pCertCtx) {
3633 /* loop ended with an error, need to clean up context manually */
3634 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003635 }
3636
3637 /* In error cases cert, enc and tup may not be NULL */
3638 Py_XDECREF(cert);
3639 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003640 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003641 Py_XDECREF(tup);
3642
3643 if (!CertCloseStore(hStore, 0)) {
3644 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003645 Py_XDECREF(result);
3646 return PyErr_SetFromWindowsErr(GetLastError());
3647 }
3648 return result;
3649}
3650
3651PyDoc_STRVAR(PySSL_enum_crls_doc,
3652"enum_crls(store_name) -> []\n\
3653\n\
3654Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3655'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3656The function returns a list of (bytes, encoding_type) tuples. The\n\
3657encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3658PKCS_7_ASN_ENCODING.");
3659
3660static PyObject *
3661PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3662{
3663 char *kwlist[] = {"store_name", NULL};
3664 char *store_name;
3665 HCERTSTORE hStore = NULL;
3666 PCCRL_CONTEXT pCrlCtx = NULL;
3667 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3668 PyObject *result = NULL;
3669
3670 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3671 kwlist, &store_name)) {
3672 return NULL;
3673 }
3674 result = PyList_New(0);
3675 if (result == NULL) {
3676 return NULL;
3677 }
3678 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3679 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003680 Py_DECREF(result);
3681 return PyErr_SetFromWindowsErr(GetLastError());
3682 }
Christian Heimes44109d72013-11-22 01:51:30 +01003683
3684 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3685 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3686 pCrlCtx->cbCrlEncoded);
3687 if (!crl) {
3688 Py_CLEAR(result);
3689 break;
3690 }
3691 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3692 Py_CLEAR(result);
3693 break;
3694 }
3695 if ((tup = PyTuple_New(2)) == NULL) {
3696 Py_CLEAR(result);
3697 break;
3698 }
3699 PyTuple_SET_ITEM(tup, 0, crl);
3700 crl = NULL;
3701 PyTuple_SET_ITEM(tup, 1, enc);
3702 enc = NULL;
3703
3704 if (PyList_Append(result, tup) < 0) {
3705 Py_CLEAR(result);
3706 break;
3707 }
3708 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003709 }
Christian Heimes44109d72013-11-22 01:51:30 +01003710 if (pCrlCtx) {
3711 /* loop ended with an error, need to clean up context manually */
3712 CertFreeCRLContext(pCrlCtx);
3713 }
3714
3715 /* In error cases cert, enc and tup may not be NULL */
3716 Py_XDECREF(crl);
3717 Py_XDECREF(enc);
3718 Py_XDECREF(tup);
3719
3720 if (!CertCloseStore(hStore, 0)) {
3721 /* This error case might shadow another exception.*/
3722 Py_XDECREF(result);
3723 return PyErr_SetFromWindowsErr(GetLastError());
3724 }
3725 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003726}
Christian Heimes44109d72013-11-22 01:51:30 +01003727
3728#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003729
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003730/* List of functions exported by this module. */
3731
3732static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003733 {"_test_decode_cert", PySSL_test_decode_certificate,
3734 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003735#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003736 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3737 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003738 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3739 PySSL_RAND_bytes_doc},
3740 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3741 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003742 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003743 PySSL_RAND_egd_doc},
3744 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3745 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003746#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003747 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003748 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003749#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003750 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3751 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3752 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3753 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003754#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003755 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3756 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3757 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3758 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003759 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003760};
3761
3762
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003763#ifdef WITH_THREAD
3764
3765/* an implementation of OpenSSL threading operations in terms
3766 of the Python C thread library */
3767
3768static PyThread_type_lock *_ssl_locks = NULL;
3769
Christian Heimes4d98ca92013-08-19 17:36:29 +02003770#if OPENSSL_VERSION_NUMBER >= 0x10000000
3771/* use new CRYPTO_THREADID API. */
3772static void
3773_ssl_threadid_callback(CRYPTO_THREADID *id)
3774{
3775 CRYPTO_THREADID_set_numeric(id,
3776 (unsigned long)PyThread_get_thread_ident());
3777}
3778#else
3779/* deprecated CRYPTO_set_id_callback() API. */
3780static unsigned long
3781_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003782 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003783}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003784#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003785
Bill Janssen6e027db2007-11-15 22:23:56 +00003786static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003787 (int mode, int n, const char *file, int line) {
3788 /* this function is needed to perform locking on shared data
3789 structures. (Note that OpenSSL uses a number of global data
3790 structures that will be implicitly shared whenever multiple
3791 threads use OpenSSL.) Multi-threaded applications will
3792 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003794 locking_function() must be able to handle up to
3795 CRYPTO_num_locks() different mutex locks. It sets the n-th
3796 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003798 file and line are the file number of the function setting the
3799 lock. They can be useful for debugging.
3800 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003801
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003802 if ((_ssl_locks == NULL) ||
3803 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3804 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003806 if (mode & CRYPTO_LOCK) {
3807 PyThread_acquire_lock(_ssl_locks[n], 1);
3808 } else {
3809 PyThread_release_lock(_ssl_locks[n]);
3810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003811}
3812
3813static int _setup_ssl_threads(void) {
3814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003815 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003817 if (_ssl_locks == NULL) {
3818 _ssl_locks_count = CRYPTO_num_locks();
3819 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003820 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003821 if (_ssl_locks == NULL)
3822 return 0;
3823 memset(_ssl_locks, 0,
3824 sizeof(PyThread_type_lock) * _ssl_locks_count);
3825 for (i = 0; i < _ssl_locks_count; i++) {
3826 _ssl_locks[i] = PyThread_allocate_lock();
3827 if (_ssl_locks[i] == NULL) {
3828 unsigned int j;
3829 for (j = 0; j < i; j++) {
3830 PyThread_free_lock(_ssl_locks[j]);
3831 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003832 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003833 return 0;
3834 }
3835 }
3836 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003837#if OPENSSL_VERSION_NUMBER >= 0x10000000
3838 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3839#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003840 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003841#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003842 }
3843 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003844}
3845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003846#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003847
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003848PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003849"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003850for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003851
Martin v. Löwis1a214512008-06-11 05:26:20 +00003852
3853static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003854 PyModuleDef_HEAD_INIT,
3855 "_ssl",
3856 module_doc,
3857 -1,
3858 PySSL_methods,
3859 NULL,
3860 NULL,
3861 NULL,
3862 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003863};
3864
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003865
3866static void
3867parse_openssl_version(unsigned long libver,
3868 unsigned int *major, unsigned int *minor,
3869 unsigned int *fix, unsigned int *patch,
3870 unsigned int *status)
3871{
3872 *status = libver & 0xF;
3873 libver >>= 4;
3874 *patch = libver & 0xFF;
3875 libver >>= 8;
3876 *fix = libver & 0xFF;
3877 libver >>= 8;
3878 *minor = libver & 0xFF;
3879 libver >>= 8;
3880 *major = libver & 0xFF;
3881}
3882
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003883PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003884PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003885{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003886 PyObject *m, *d, *r;
3887 unsigned long libver;
3888 unsigned int major, minor, fix, patch, status;
3889 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003890 struct py_ssl_error_code *errcode;
3891 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003892
Antoine Pitrou152efa22010-05-16 18:19:27 +00003893 if (PyType_Ready(&PySSLContext_Type) < 0)
3894 return NULL;
3895 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003896 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003898 m = PyModule_Create(&_sslmodule);
3899 if (m == NULL)
3900 return NULL;
3901 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003903 /* Load _socket module and its C API */
3904 socket_api = PySocketModule_ImportModuleAndAPI();
3905 if (!socket_api)
3906 return NULL;
3907 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003909 /* Init OpenSSL */
3910 SSL_load_error_strings();
3911 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003912#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003913 /* note that this will start threading if not already started */
3914 if (!_setup_ssl_threads()) {
3915 return NULL;
3916 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003917#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003918 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003920 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003921 sslerror_type_slots[0].pfunc = PyExc_OSError;
3922 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003923 if (PySSLErrorObject == NULL)
3924 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003925
Antoine Pitrou41032a62011-10-27 23:56:55 +02003926 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3927 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3928 PySSLErrorObject, NULL);
3929 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3930 "ssl.SSLWantReadError", SSLWantReadError_doc,
3931 PySSLErrorObject, NULL);
3932 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3933 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3934 PySSLErrorObject, NULL);
3935 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3936 "ssl.SSLSyscallError", SSLSyscallError_doc,
3937 PySSLErrorObject, NULL);
3938 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3939 "ssl.SSLEOFError", SSLEOFError_doc,
3940 PySSLErrorObject, NULL);
3941 if (PySSLZeroReturnErrorObject == NULL
3942 || PySSLWantReadErrorObject == NULL
3943 || PySSLWantWriteErrorObject == NULL
3944 || PySSLSyscallErrorObject == NULL
3945 || PySSLEOFErrorObject == NULL)
3946 return NULL;
3947 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3948 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3949 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3950 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3951 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3952 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003953 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003954 if (PyDict_SetItemString(d, "_SSLContext",
3955 (PyObject *)&PySSLContext_Type) != 0)
3956 return NULL;
3957 if (PyDict_SetItemString(d, "_SSLSocket",
3958 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003959 return NULL;
3960 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3961 PY_SSL_ERROR_ZERO_RETURN);
3962 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3963 PY_SSL_ERROR_WANT_READ);
3964 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3965 PY_SSL_ERROR_WANT_WRITE);
3966 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3967 PY_SSL_ERROR_WANT_X509_LOOKUP);
3968 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3969 PY_SSL_ERROR_SYSCALL);
3970 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3971 PY_SSL_ERROR_SSL);
3972 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3973 PY_SSL_ERROR_WANT_CONNECT);
3974 /* non ssl.h errorcodes */
3975 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3976 PY_SSL_ERROR_EOF);
3977 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3978 PY_SSL_ERROR_INVALID_ERROR_CODE);
3979 /* cert requirements */
3980 PyModule_AddIntConstant(m, "CERT_NONE",
3981 PY_SSL_CERT_NONE);
3982 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3983 PY_SSL_CERT_OPTIONAL);
3984 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3985 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01003986 /* CRL verification for verification_flags */
3987 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
3988 0);
3989 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
3990 X509_V_FLAG_CRL_CHECK);
3991 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
3992 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3993 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
3994 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003995
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003996 /* Alert Descriptions from ssl.h */
3997 /* note RESERVED constants no longer intended for use have been removed */
3998 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3999
4000#define ADD_AD_CONSTANT(s) \
4001 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4002 SSL_AD_##s)
4003
4004 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4005 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4006 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4007 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4008 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4009 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4010 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4011 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4012 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4013 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4014 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4015 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4016 ADD_AD_CONSTANT(UNKNOWN_CA);
4017 ADD_AD_CONSTANT(ACCESS_DENIED);
4018 ADD_AD_CONSTANT(DECODE_ERROR);
4019 ADD_AD_CONSTANT(DECRYPT_ERROR);
4020 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4021 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4022 ADD_AD_CONSTANT(INTERNAL_ERROR);
4023 ADD_AD_CONSTANT(USER_CANCELLED);
4024 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004025 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004026#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4027 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4028#endif
4029#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4030 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4031#endif
4032#ifdef SSL_AD_UNRECOGNIZED_NAME
4033 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4034#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004035#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4036 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4037#endif
4038#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4039 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4040#endif
4041#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4042 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4043#endif
4044
4045#undef ADD_AD_CONSTANT
4046
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004047 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004048#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004049 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4050 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004051#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004052 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4053 PY_SSL_VERSION_SSL3);
4054 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4055 PY_SSL_VERSION_SSL23);
4056 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4057 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004058#if HAVE_TLSv1_2
4059 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4060 PY_SSL_VERSION_TLS1_1);
4061 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4062 PY_SSL_VERSION_TLS1_2);
4063#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004064
Antoine Pitroub5218772010-05-21 09:56:06 +00004065 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004066 PyModule_AddIntConstant(m, "OP_ALL",
4067 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004068 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4069 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4070 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004071#if HAVE_TLSv1_2
4072 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4073 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4074#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004075 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4076 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004077 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004078#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004079 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004080#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004081#ifdef SSL_OP_NO_COMPRESSION
4082 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4083 SSL_OP_NO_COMPRESSION);
4084#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004085
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004086#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004087 r = Py_True;
4088#else
4089 r = Py_False;
4090#endif
4091 Py_INCREF(r);
4092 PyModule_AddObject(m, "HAS_SNI", r);
4093
Antoine Pitroud6494802011-07-21 01:11:30 +02004094#if HAVE_OPENSSL_FINISHED
4095 r = Py_True;
4096#else
4097 r = Py_False;
4098#endif
4099 Py_INCREF(r);
4100 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4101
Antoine Pitrou501da612011-12-21 09:27:41 +01004102#ifdef OPENSSL_NO_ECDH
4103 r = Py_False;
4104#else
4105 r = Py_True;
4106#endif
4107 Py_INCREF(r);
4108 PyModule_AddObject(m, "HAS_ECDH", r);
4109
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004110#ifdef OPENSSL_NPN_NEGOTIATED
4111 r = Py_True;
4112#else
4113 r = Py_False;
4114#endif
4115 Py_INCREF(r);
4116 PyModule_AddObject(m, "HAS_NPN", r);
4117
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004118 /* Mappings for error codes */
4119 err_codes_to_names = PyDict_New();
4120 err_names_to_codes = PyDict_New();
4121 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4122 return NULL;
4123 errcode = error_codes;
4124 while (errcode->mnemonic != NULL) {
4125 PyObject *mnemo, *key;
4126 mnemo = PyUnicode_FromString(errcode->mnemonic);
4127 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4128 if (mnemo == NULL || key == NULL)
4129 return NULL;
4130 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4131 return NULL;
4132 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4133 return NULL;
4134 Py_DECREF(key);
4135 Py_DECREF(mnemo);
4136 errcode++;
4137 }
4138 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4139 return NULL;
4140 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4141 return NULL;
4142
4143 lib_codes_to_names = PyDict_New();
4144 if (lib_codes_to_names == NULL)
4145 return NULL;
4146 libcode = library_codes;
4147 while (libcode->library != NULL) {
4148 PyObject *mnemo, *key;
4149 key = PyLong_FromLong(libcode->code);
4150 mnemo = PyUnicode_FromString(libcode->library);
4151 if (key == NULL || mnemo == NULL)
4152 return NULL;
4153 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4154 return NULL;
4155 Py_DECREF(key);
4156 Py_DECREF(mnemo);
4157 libcode++;
4158 }
4159 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4160 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004162 /* OpenSSL version */
4163 /* SSLeay() gives us the version of the library linked against,
4164 which could be different from the headers version.
4165 */
4166 libver = SSLeay();
4167 r = PyLong_FromUnsignedLong(libver);
4168 if (r == NULL)
4169 return NULL;
4170 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4171 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004172 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004173 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4174 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4175 return NULL;
4176 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4177 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4178 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004179
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004180 libver = OPENSSL_VERSION_NUMBER;
4181 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4182 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4183 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4184 return NULL;
4185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004186 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004187}