blob: 3b7226d15fb29e326a523c35b2120baf6c995ff6 [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 # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000252#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200253#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000254
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200255
256/*
257 * SSL errors.
258 */
259
260PyDoc_STRVAR(SSLError_doc,
261"An error occurred in the SSL implementation.");
262
263PyDoc_STRVAR(SSLZeroReturnError_doc,
264"SSL/TLS session closed cleanly.");
265
266PyDoc_STRVAR(SSLWantReadError_doc,
267"Non-blocking SSL socket needs to read more data\n"
268"before the requested operation can be completed.");
269
270PyDoc_STRVAR(SSLWantWriteError_doc,
271"Non-blocking SSL socket needs to write more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLSyscallError_doc,
275"System error when attempting SSL operation.");
276
277PyDoc_STRVAR(SSLEOFError_doc,
278"SSL/TLS connection terminated abruptly.");
279
280static PyObject *
281SSLError_str(PyOSErrorObject *self)
282{
283 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
284 Py_INCREF(self->strerror);
285 return self->strerror;
286 }
287 else
288 return PyObject_Str(self->args);
289}
290
291static PyType_Slot sslerror_type_slots[] = {
292 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
293 {Py_tp_doc, SSLError_doc},
294 {Py_tp_str, SSLError_str},
295 {0, 0},
296};
297
298static PyType_Spec sslerror_type_spec = {
299 "ssl.SSLError",
300 sizeof(PyOSErrorObject),
301 0,
302 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
303 sslerror_type_slots
304};
305
306static void
307fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
308 int lineno, unsigned long errcode)
309{
310 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
311 PyObject *init_value, *msg, *key;
312 _Py_IDENTIFIER(reason);
313 _Py_IDENTIFIER(library);
314
315 if (errcode != 0) {
316 int lib, reason;
317
318 lib = ERR_GET_LIB(errcode);
319 reason = ERR_GET_REASON(errcode);
320 key = Py_BuildValue("ii", lib, reason);
321 if (key == NULL)
322 goto fail;
323 reason_obj = PyDict_GetItem(err_codes_to_names, key);
324 Py_DECREF(key);
325 if (reason_obj == NULL) {
326 /* XXX if reason < 100, it might reflect a library number (!!) */
327 PyErr_Clear();
328 }
329 key = PyLong_FromLong(lib);
330 if (key == NULL)
331 goto fail;
332 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
333 Py_DECREF(key);
334 if (lib_obj == NULL) {
335 PyErr_Clear();
336 }
337 if (errstr == NULL)
338 errstr = ERR_reason_error_string(errcode);
339 }
340 if (errstr == NULL)
341 errstr = "unknown error";
342
343 if (reason_obj && lib_obj)
344 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
345 lib_obj, reason_obj, errstr, lineno);
346 else if (lib_obj)
347 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
348 lib_obj, errstr, lineno);
349 else
350 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200351 if (msg == NULL)
352 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100353
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200354 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100355 if (init_value == NULL)
356 goto fail;
357
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200358 err_value = PyObject_CallObject(type, init_value);
359 Py_DECREF(init_value);
360 if (err_value == NULL)
361 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100362
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200363 if (reason_obj == NULL)
364 reason_obj = Py_None;
365 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
366 goto fail;
367 if (lib_obj == NULL)
368 lib_obj = Py_None;
369 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
370 goto fail;
371 PyErr_SetObject(type, err_value);
372fail:
373 Py_XDECREF(err_value);
374}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375
376static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200379 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200380 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 int err;
382 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200383 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200386 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 if (obj->ssl != NULL) {
389 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 switch (err) {
392 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200393 errstr = "TLS/SSL connection has been closed (EOF)";
394 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 p = PY_SSL_ERROR_ZERO_RETURN;
396 break;
397 case SSL_ERROR_WANT_READ:
398 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200399 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000400 p = PY_SSL_ERROR_WANT_READ;
401 break;
402 case SSL_ERROR_WANT_WRITE:
403 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200404 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 errstr = "The operation did not complete (write)";
406 break;
407 case SSL_ERROR_WANT_X509_LOOKUP:
408 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000409 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 break;
411 case SSL_ERROR_WANT_CONNECT:
412 p = PY_SSL_ERROR_WANT_CONNECT;
413 errstr = "The operation did not complete (connect)";
414 break;
415 case SSL_ERROR_SYSCALL:
416 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 if (e == 0) {
418 PySocketSockObject *s
419 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
420 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000421 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200422 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000426 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000427 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000429 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000431 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200433 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000434 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 }
436 } else {
437 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 }
439 break;
440 }
441 case SSL_ERROR_SSL:
442 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000443 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200444 if (e == 0)
445 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000446 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 break;
448 }
449 default:
450 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
451 errstr = "Invalid error code";
452 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000453 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200454 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000455 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000457}
458
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459static PyObject *
460_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 else
465 errcode = 0;
466 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000467 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000469}
470
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200471/*
472 * SSL objects
473 */
474
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100476newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000477 enum py_ssl_server_or_client socket_type,
478 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000479{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000480 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100481 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200482 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 if (self == NULL)
486 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 self->peer_cert = NULL;
489 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100491 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200492 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200493 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100494 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 /* Make sure the SSL error state is initialized */
497 (void) ERR_get_state();
498 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100503 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100504 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200505 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000506#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000508#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000510
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100511#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000512 if (server_hostname != NULL)
513 SSL_set_tlsext_host_name(self->ssl, server_hostname);
514#endif
515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* If the socket is in non-blocking mode or timeout mode, set the BIO
517 * to non-blocking mode (blocking is the default)
518 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000519 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
521 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
522 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 PySSL_BEGIN_ALLOW_THREADS
525 if (socket_type == PY_SSL_CLIENT)
526 SSL_set_connect_state(self->ssl);
527 else
528 SSL_set_accept_state(self->ssl);
529 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000530
Antoine Pitroud6494802011-07-21 01:11:30 +0200531 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000532 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100533 if (self->Socket == NULL) {
534 Py_DECREF(self);
535 return NULL;
536 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000537 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000538}
539
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000540/* SSL object methods */
541
Antoine Pitrou152efa22010-05-16 18:19:27 +0000542static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000543{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 int ret;
545 int err;
546 int sockstate, nonblocking;
547 PySocketSockObject *sock
548 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 if (((PyObject*)sock) == Py_None) {
551 _setSSLError("Underlying socket connection gone",
552 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
553 return NULL;
554 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000555 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000557 /* just in case the blocking state of the socket has been changed */
558 nonblocking = (sock->sock_timeout >= 0.0);
559 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
560 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 /* Actually negotiate SSL connection */
563 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000565 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 ret = SSL_do_handshake(self->ssl);
567 err = SSL_get_error(self->ssl, ret);
568 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000569 if (PyErr_CheckSignals())
570 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 if (err == SSL_ERROR_WANT_READ) {
572 sockstate = check_socket_and_wait_for_timeout(sock, 0);
573 } else if (err == SSL_ERROR_WANT_WRITE) {
574 sockstate = check_socket_and_wait_for_timeout(sock, 1);
575 } else {
576 sockstate = SOCKET_OPERATION_OK;
577 }
578 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000579 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000580 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000581 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
583 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000584 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000585 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
587 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000588 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000589 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
591 break;
592 }
593 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000594 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 if (ret < 1)
596 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 if (self->peer_cert)
599 X509_free (self->peer_cert);
600 PySSL_BEGIN_ALLOW_THREADS
601 self->peer_cert = SSL_get_peer_certificate(self->ssl);
602 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200603 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604
605 Py_INCREF(Py_None);
606 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000607
608error:
609 Py_DECREF(sock);
610 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000611}
612
Thomas Woutersed03b412007-08-28 21:37:11 +0000613static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 char namebuf[X509_NAME_MAXLEN];
617 int buflen;
618 PyObject *name_obj;
619 PyObject *value_obj;
620 PyObject *attr;
621 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
624 if (buflen < 0) {
625 _setSSLError(NULL, 0, __FILE__, __LINE__);
626 goto fail;
627 }
628 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
629 if (name_obj == NULL)
630 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
633 if (buflen < 0) {
634 _setSSLError(NULL, 0, __FILE__, __LINE__);
635 Py_DECREF(name_obj);
636 goto fail;
637 }
638 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000639 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 OPENSSL_free(valuebuf);
641 if (value_obj == NULL) {
642 Py_DECREF(name_obj);
643 goto fail;
644 }
645 attr = PyTuple_New(2);
646 if (attr == NULL) {
647 Py_DECREF(name_obj);
648 Py_DECREF(value_obj);
649 goto fail;
650 }
651 PyTuple_SET_ITEM(attr, 0, name_obj);
652 PyTuple_SET_ITEM(attr, 1, value_obj);
653 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000654
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000657}
658
659static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000661{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
663 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
664 PyObject *rdnt;
665 PyObject *attr = NULL; /* tuple to hold an attribute */
666 int entry_count = X509_NAME_entry_count(xname);
667 X509_NAME_ENTRY *entry;
668 ASN1_OBJECT *name;
669 ASN1_STRING *value;
670 int index_counter;
671 int rdn_level = -1;
672 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 dn = PyList_New(0);
675 if (dn == NULL)
676 return NULL;
677 /* now create another tuple to hold the top-level RDN */
678 rdn = PyList_New(0);
679 if (rdn == NULL)
680 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 for (index_counter = 0;
683 index_counter < entry_count;
684 index_counter++)
685 {
686 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 /* check to see if we've gotten to a new RDN */
689 if (rdn_level >= 0) {
690 if (rdn_level != entry->set) {
691 /* yes, new RDN */
692 /* add old RDN to DN */
693 rdnt = PyList_AsTuple(rdn);
694 Py_DECREF(rdn);
695 if (rdnt == NULL)
696 goto fail0;
697 retcode = PyList_Append(dn, rdnt);
698 Py_DECREF(rdnt);
699 if (retcode < 0)
700 goto fail0;
701 /* create new RDN */
702 rdn = PyList_New(0);
703 if (rdn == NULL)
704 goto fail0;
705 }
706 }
707 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 /* now add this attribute to the current RDN */
710 name = X509_NAME_ENTRY_get_object(entry);
711 value = X509_NAME_ENTRY_get_data(entry);
712 attr = _create_tuple_for_attribute(name, value);
713 /*
714 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
715 entry->set,
716 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
717 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
718 */
719 if (attr == NULL)
720 goto fail1;
721 retcode = PyList_Append(rdn, attr);
722 Py_DECREF(attr);
723 if (retcode < 0)
724 goto fail1;
725 }
726 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100727 if (rdn != NULL) {
728 if (PyList_GET_SIZE(rdn) > 0) {
729 rdnt = PyList_AsTuple(rdn);
730 Py_DECREF(rdn);
731 if (rdnt == NULL)
732 goto fail0;
733 retcode = PyList_Append(dn, rdnt);
734 Py_DECREF(rdnt);
735 if (retcode < 0)
736 goto fail0;
737 }
738 else {
739 Py_DECREF(rdn);
740 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 /* convert list to tuple */
744 rdnt = PyList_AsTuple(dn);
745 Py_DECREF(dn);
746 if (rdnt == NULL)
747 return NULL;
748 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749
750 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752
753 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 Py_XDECREF(dn);
755 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756}
757
758static PyObject *
759_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 /* this code follows the procedure outlined in
762 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
763 function to extract the STACK_OF(GENERAL_NAME),
764 then iterates through the stack to add the
765 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 int i, j;
768 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200769 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 X509_EXTENSION *ext = NULL;
771 GENERAL_NAMES *names = NULL;
772 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000773 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 BIO *biobuf = NULL;
775 char buf[2048];
776 char *vptr;
777 int len;
778 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000779#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000781#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000783#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 if (certificate == NULL)
786 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 /* get a memory buffer */
789 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200791 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 while ((i = X509_get_ext_by_NID(
793 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 if (peer_alt_names == Py_None) {
796 peer_alt_names = PyList_New(0);
797 if (peer_alt_names == NULL)
798 goto fail;
799 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 /* now decode the altName */
802 ext = X509_get_ext(certificate, i);
803 if(!(method = X509V3_EXT_get(ext))) {
804 PyErr_SetString
805 (PySSLErrorObject,
806 ERRSTR("No method for internalizing subjectAltName!"));
807 goto fail;
808 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 p = ext->value->data;
811 if (method->it)
812 names = (GENERAL_NAMES*)
813 (ASN1_item_d2i(NULL,
814 &p,
815 ext->value->length,
816 ASN1_ITEM_ptr(method->it)));
817 else
818 names = (GENERAL_NAMES*)
819 (method->d2i(NULL,
820 &p,
821 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200825 int gntype;
826 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200829 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200830 switch (gntype) {
831 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* we special-case DirName as a tuple of
833 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 t = PyTuple_New(2);
836 if (t == NULL) {
837 goto fail;
838 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 v = PyUnicode_FromString("DirName");
841 if (v == NULL) {
842 Py_DECREF(t);
843 goto fail;
844 }
845 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 v = _create_tuple_for_X509_NAME (name->d.dirn);
848 if (v == NULL) {
849 Py_DECREF(t);
850 goto fail;
851 }
852 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200853 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000854
Christian Heimes824f7f32013-08-17 00:54:47 +0200855 case GEN_EMAIL:
856 case GEN_DNS:
857 case GEN_URI:
858 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
859 correctly, CVE-2013-4238 */
860 t = PyTuple_New(2);
861 if (t == NULL)
862 goto fail;
863 switch (gntype) {
864 case GEN_EMAIL:
865 v = PyUnicode_FromString("email");
866 as = name->d.rfc822Name;
867 break;
868 case GEN_DNS:
869 v = PyUnicode_FromString("DNS");
870 as = name->d.dNSName;
871 break;
872 case GEN_URI:
873 v = PyUnicode_FromString("URI");
874 as = name->d.uniformResourceIdentifier;
875 break;
876 }
877 if (v == NULL) {
878 Py_DECREF(t);
879 goto fail;
880 }
881 PyTuple_SET_ITEM(t, 0, v);
882 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
883 ASN1_STRING_length(as));
884 if (v == NULL) {
885 Py_DECREF(t);
886 goto fail;
887 }
888 PyTuple_SET_ITEM(t, 1, v);
889 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Christian Heimes824f7f32013-08-17 00:54:47 +0200891 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200893 switch (gntype) {
894 /* check for new general name type */
895 case GEN_OTHERNAME:
896 case GEN_X400:
897 case GEN_EDIPARTY:
898 case GEN_IPADD:
899 case GEN_RID:
900 break;
901 default:
902 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
903 "Unknown general name type %d",
904 gntype) == -1) {
905 goto fail;
906 }
907 break;
908 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 (void) BIO_reset(biobuf);
910 GENERAL_NAME_print(biobuf, name);
911 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
912 if (len < 0) {
913 _setSSLError(NULL, 0, __FILE__, __LINE__);
914 goto fail;
915 }
916 vptr = strchr(buf, ':');
917 if (vptr == NULL)
918 goto fail;
919 t = PyTuple_New(2);
920 if (t == NULL)
921 goto fail;
922 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
923 if (v == NULL) {
924 Py_DECREF(t);
925 goto fail;
926 }
927 PyTuple_SET_ITEM(t, 0, v);
928 v = PyUnicode_FromStringAndSize((vptr + 1),
929 (len - (vptr - buf + 1)));
930 if (v == NULL) {
931 Py_DECREF(t);
932 goto fail;
933 }
934 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200935 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 if (PyList_Append(peer_alt_names, t) < 0) {
941 Py_DECREF(t);
942 goto fail;
943 }
944 Py_DECREF(t);
945 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100946 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 }
948 BIO_free(biobuf);
949 if (peer_alt_names != Py_None) {
950 v = PyList_AsTuple(peer_alt_names);
951 Py_DECREF(peer_alt_names);
952 return v;
953 } else {
954 return peer_alt_names;
955 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000956
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957
958 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 if (biobuf != NULL)
960 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 if (peer_alt_names != Py_None) {
963 Py_XDECREF(peer_alt_names);
964 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967}
968
969static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100970_get_aia_uri(X509 *certificate, int nid) {
971 PyObject *lst = NULL, *ostr = NULL;
972 int i, result;
973 AUTHORITY_INFO_ACCESS *info;
974
975 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
976 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
977 return Py_None;
978 }
979
980 if ((lst = PyList_New(0)) == NULL) {
981 goto fail;
982 }
983
984 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
985 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
986 ASN1_IA5STRING *uri;
987
988 if ((OBJ_obj2nid(ad->method) != nid) ||
989 (ad->location->type != GEN_URI)) {
990 continue;
991 }
992 uri = ad->location->d.uniformResourceIdentifier;
993 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
994 uri->length);
995 if (ostr == NULL) {
996 goto fail;
997 }
998 result = PyList_Append(lst, ostr);
999 Py_DECREF(ostr);
1000 if (result < 0) {
1001 goto fail;
1002 }
1003 }
1004 AUTHORITY_INFO_ACCESS_free(info);
1005
1006 /* convert to tuple or None */
1007 if (PyList_Size(lst) == 0) {
1008 Py_DECREF(lst);
1009 return Py_None;
1010 } else {
1011 PyObject *tup;
1012 tup = PyList_AsTuple(lst);
1013 Py_DECREF(lst);
1014 return tup;
1015 }
1016
1017 fail:
1018 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001019 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001020 return NULL;
1021}
1022
1023static PyObject *
1024_get_crl_dp(X509 *certificate) {
1025 STACK_OF(DIST_POINT) *dps;
1026 int i, j, result;
1027 PyObject *lst;
1028
Christian Heimes949ec142013-11-21 16:26:51 +01001029#if OPENSSL_VERSION_NUMBER < 0x10001000L
1030 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1031 NULL, NULL);
1032#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001033 /* Calls x509v3_cache_extensions and sets up crldp */
1034 X509_check_ca(certificate);
1035 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001036#endif
1037
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001038 if (dps == NULL) {
1039 return Py_None;
1040 }
1041
1042 if ((lst = PyList_New(0)) == NULL) {
1043 return NULL;
1044 }
1045
1046 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1047 DIST_POINT *dp;
1048 STACK_OF(GENERAL_NAME) *gns;
1049
1050 dp = sk_DIST_POINT_value(dps, i);
1051 gns = dp->distpoint->name.fullname;
1052
1053 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1054 GENERAL_NAME *gn;
1055 ASN1_IA5STRING *uri;
1056 PyObject *ouri;
1057
1058 gn = sk_GENERAL_NAME_value(gns, j);
1059 if (gn->type != GEN_URI) {
1060 continue;
1061 }
1062 uri = gn->d.uniformResourceIdentifier;
1063 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1064 uri->length);
1065 if (ouri == NULL) {
1066 Py_DECREF(lst);
1067 return NULL;
1068 }
1069 result = PyList_Append(lst, ouri);
1070 Py_DECREF(ouri);
1071 if (result < 0) {
1072 Py_DECREF(lst);
1073 return NULL;
1074 }
1075 }
1076 }
1077 /* convert to tuple or None */
1078 if (PyList_Size(lst) == 0) {
1079 Py_DECREF(lst);
1080 return Py_None;
1081 } else {
1082 PyObject *tup;
1083 tup = PyList_AsTuple(lst);
1084 Py_DECREF(lst);
1085 return tup;
1086 }
1087}
1088
1089static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001090_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 PyObject *retval = NULL;
1093 BIO *biobuf = NULL;
1094 PyObject *peer;
1095 PyObject *peer_alt_names = NULL;
1096 PyObject *issuer;
1097 PyObject *version;
1098 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001099 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 ASN1_INTEGER *serialNumber;
1101 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001102 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 ASN1_TIME *notBefore, *notAfter;
1104 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 retval = PyDict_New();
1107 if (retval == NULL)
1108 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 peer = _create_tuple_for_X509_NAME(
1111 X509_get_subject_name(certificate));
1112 if (peer == NULL)
1113 goto fail0;
1114 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1115 Py_DECREF(peer);
1116 goto fail0;
1117 }
1118 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001119
Antoine Pitroufb046912010-11-09 20:21:19 +00001120 issuer = _create_tuple_for_X509_NAME(
1121 X509_get_issuer_name(certificate));
1122 if (issuer == NULL)
1123 goto fail0;
1124 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001126 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001128 Py_DECREF(issuer);
1129
1130 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001131 if (version == NULL)
1132 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001133 if (PyDict_SetItemString(retval, "version", version) < 0) {
1134 Py_DECREF(version);
1135 goto fail0;
1136 }
1137 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 /* get a memory buffer */
1140 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001141
Antoine Pitroufb046912010-11-09 20:21:19 +00001142 (void) BIO_reset(biobuf);
1143 serialNumber = X509_get_serialNumber(certificate);
1144 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1145 i2a_ASN1_INTEGER(biobuf, serialNumber);
1146 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1147 if (len < 0) {
1148 _setSSLError(NULL, 0, __FILE__, __LINE__);
1149 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001151 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1152 if (sn_obj == NULL)
1153 goto fail1;
1154 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1155 Py_DECREF(sn_obj);
1156 goto fail1;
1157 }
1158 Py_DECREF(sn_obj);
1159
1160 (void) BIO_reset(biobuf);
1161 notBefore = X509_get_notBefore(certificate);
1162 ASN1_TIME_print(biobuf, notBefore);
1163 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1164 if (len < 0) {
1165 _setSSLError(NULL, 0, __FILE__, __LINE__);
1166 goto fail1;
1167 }
1168 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1169 if (pnotBefore == NULL)
1170 goto fail1;
1171 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1172 Py_DECREF(pnotBefore);
1173 goto fail1;
1174 }
1175 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 (void) BIO_reset(biobuf);
1178 notAfter = X509_get_notAfter(certificate);
1179 ASN1_TIME_print(biobuf, notAfter);
1180 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1181 if (len < 0) {
1182 _setSSLError(NULL, 0, __FILE__, __LINE__);
1183 goto fail1;
1184 }
1185 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1186 if (pnotAfter == NULL)
1187 goto fail1;
1188 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1189 Py_DECREF(pnotAfter);
1190 goto fail1;
1191 }
1192 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 peer_alt_names = _get_peer_alt_names(certificate);
1197 if (peer_alt_names == NULL)
1198 goto fail1;
1199 else if (peer_alt_names != Py_None) {
1200 if (PyDict_SetItemString(retval, "subjectAltName",
1201 peer_alt_names) < 0) {
1202 Py_DECREF(peer_alt_names);
1203 goto fail1;
1204 }
1205 Py_DECREF(peer_alt_names);
1206 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001207
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001208 /* Authority Information Access: OCSP URIs */
1209 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1210 if (obj == NULL) {
1211 goto fail1;
1212 } else if (obj != Py_None) {
1213 result = PyDict_SetItemString(retval, "OCSP", obj);
1214 Py_DECREF(obj);
1215 if (result < 0) {
1216 goto fail1;
1217 }
1218 }
1219
1220 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1221 if (obj == NULL) {
1222 goto fail1;
1223 } else if (obj != Py_None) {
1224 result = PyDict_SetItemString(retval, "caIssuers", obj);
1225 Py_DECREF(obj);
1226 if (result < 0) {
1227 goto fail1;
1228 }
1229 }
1230
1231 /* CDP (CRL distribution points) */
1232 obj = _get_crl_dp(certificate);
1233 if (obj == NULL) {
1234 goto fail1;
1235 } else if (obj != Py_None) {
1236 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1237 Py_DECREF(obj);
1238 if (result < 0) {
1239 goto fail1;
1240 }
1241 }
1242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 BIO_free(biobuf);
1244 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001245
1246 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 if (biobuf != NULL)
1248 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001249 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 Py_XDECREF(retval);
1251 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001252}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253
Christian Heimes9a5395a2013-06-17 15:44:12 +02001254static PyObject *
1255_certificate_to_der(X509 *certificate)
1256{
1257 unsigned char *bytes_buf = NULL;
1258 int len;
1259 PyObject *retval;
1260
1261 bytes_buf = NULL;
1262 len = i2d_X509(certificate, &bytes_buf);
1263 if (len < 0) {
1264 _setSSLError(NULL, 0, __FILE__, __LINE__);
1265 return NULL;
1266 }
1267 /* this is actually an immutable bytes sequence */
1268 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1269 OPENSSL_free(bytes_buf);
1270 return retval;
1271}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272
1273static PyObject *
1274PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001277 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 X509 *x=NULL;
1279 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001280
Antoine Pitroufb046912010-11-09 20:21:19 +00001281 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1282 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1286 PyErr_SetString(PySSLErrorObject,
1287 "Can't malloc memory to read file");
1288 goto fail0;
1289 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001290
Victor Stinner3800e1e2010-05-16 21:23:48 +00001291 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 PyErr_SetString(PySSLErrorObject,
1293 "Can't open file");
1294 goto fail0;
1295 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1298 if (x == NULL) {
1299 PyErr_SetString(PySSLErrorObject,
1300 "Error decoding PEM-encoded file");
1301 goto fail0;
1302 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001303
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001305 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
1307 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001308 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 if (cert != NULL) BIO_free(cert);
1310 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311}
1312
1313
1314static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001315PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001318 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Antoine Pitrou721738f2012-08-15 23:20:39 +02001320 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Antoine Pitrou20b85552013-09-29 19:50:53 +02001323 if (!self->handshake_done) {
1324 PyErr_SetString(PyExc_ValueError,
1325 "handshake not done yet");
1326 return NULL;
1327 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 if (!self->peer_cert)
1329 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Antoine Pitrou721738f2012-08-15 23:20:39 +02001331 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001333 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001335 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 if ((verification & SSL_VERIFY_PEER) == 0)
1337 return PyDict_New();
1338 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001339 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001341}
1342
1343PyDoc_STRVAR(PySSL_peercert_doc,
1344"peer_certificate([der=False]) -> certificate\n\
1345\n\
1346Returns the certificate for the peer. If no certificate was provided,\n\
1347returns None. If a certificate was provided, but not validated, returns\n\
1348an empty dictionary. Otherwise returns a dict containing information\n\
1349about the peer certificate.\n\
1350\n\
1351If the optional argument is True, returns a DER-encoded copy of the\n\
1352peer certificate, or None if no certificate was provided. This will\n\
1353return the certificate even if it wasn't validated.");
1354
Antoine Pitrou152efa22010-05-16 18:19:27 +00001355static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001356
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001358 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 char *cipher_name;
1360 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001363 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 current = SSL_get_current_cipher(self->ssl);
1365 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001366 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 retval = PyTuple_New(3);
1369 if (retval == NULL)
1370 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 cipher_name = (char *) SSL_CIPHER_get_name(current);
1373 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001374 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 PyTuple_SET_ITEM(retval, 0, Py_None);
1376 } else {
1377 v = PyUnicode_FromString(cipher_name);
1378 if (v == NULL)
1379 goto fail0;
1380 PyTuple_SET_ITEM(retval, 0, v);
1381 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001382 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001384 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 PyTuple_SET_ITEM(retval, 1, Py_None);
1386 } else {
1387 v = PyUnicode_FromString(cipher_protocol);
1388 if (v == NULL)
1389 goto fail0;
1390 PyTuple_SET_ITEM(retval, 1, v);
1391 }
1392 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1393 if (v == NULL)
1394 goto fail0;
1395 PyTuple_SET_ITEM(retval, 2, v);
1396 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001397
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 Py_DECREF(retval);
1400 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401}
1402
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001403#ifdef OPENSSL_NPN_NEGOTIATED
1404static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1405 const unsigned char *out;
1406 unsigned int outlen;
1407
Victor Stinner4569cd52013-06-23 14:58:43 +02001408 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001409 &out, &outlen);
1410
1411 if (out == NULL)
1412 Py_RETURN_NONE;
1413 return PyUnicode_FromStringAndSize((char *) out, outlen);
1414}
1415#endif
1416
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001417static PyObject *PySSL_compression(PySSLSocket *self) {
1418#ifdef OPENSSL_NO_COMP
1419 Py_RETURN_NONE;
1420#else
1421 const COMP_METHOD *comp_method;
1422 const char *short_name;
1423
1424 if (self->ssl == NULL)
1425 Py_RETURN_NONE;
1426 comp_method = SSL_get_current_compression(self->ssl);
1427 if (comp_method == NULL || comp_method->type == NID_undef)
1428 Py_RETURN_NONE;
1429 short_name = OBJ_nid2sn(comp_method->type);
1430 if (short_name == NULL)
1431 Py_RETURN_NONE;
1432 return PyUnicode_DecodeFSDefault(short_name);
1433#endif
1434}
1435
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001436static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1437 Py_INCREF(self->ctx);
1438 return self->ctx;
1439}
1440
1441static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1442 void *closure) {
1443
1444 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001445#if !HAVE_SNI
1446 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1447 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001448 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001449#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001450 Py_INCREF(value);
1451 Py_DECREF(self->ctx);
1452 self->ctx = (PySSLContext *) value;
1453 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001454#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001455 } else {
1456 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1457 return -1;
1458 }
1459
1460 return 0;
1461}
1462
1463PyDoc_STRVAR(PySSL_set_context_doc,
1464"_setter_context(ctx)\n\
1465\
1466This changes the context associated with the SSLSocket. This is typically\n\
1467used from within a callback function set by the set_servername_callback\n\
1468on the SSLContext to change the certificate information associated with the\n\
1469SSLSocket before the cryptographic exchange handshake messages\n");
1470
1471
1472
Antoine Pitrou152efa22010-05-16 18:19:27 +00001473static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001474{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001475 if (self->peer_cert) /* Possible not to have one? */
1476 X509_free (self->peer_cert);
1477 if (self->ssl)
1478 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001480 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482}
1483
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001484/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001485 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001486 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001487 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001488
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001489static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001490check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001491{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 fd_set fds;
1493 struct timeval tv;
1494 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1497 if (s->sock_timeout < 0.0)
1498 return SOCKET_IS_BLOCKING;
1499 else if (s->sock_timeout == 0.0)
1500 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 /* Guard against closed socket */
1503 if (s->sock_fd < 0)
1504 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 /* Prefer poll, if available, since you can poll() any fd
1507 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001508#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 {
1510 struct pollfd pollfd;
1511 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 pollfd.fd = s->sock_fd;
1514 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 /* s->sock_timeout is in seconds, timeout in ms */
1517 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1518 PySSL_BEGIN_ALLOW_THREADS
1519 rc = poll(&pollfd, 1, timeout);
1520 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 goto normal_return;
1523 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001524#endif
1525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001527 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 /* Construct the arguments to select */
1531 tv.tv_sec = (int)s->sock_timeout;
1532 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1533 FD_ZERO(&fds);
1534 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 /* See if the socket is ready */
1537 PySSL_BEGIN_ALLOW_THREADS
1538 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001539 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1540 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001542 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1543 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001545
Bill Janssen6e027db2007-11-15 22:23:56 +00001546#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001547normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001548#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1550 (when we are able to write or when there's something to read) */
1551 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001552}
1553
Antoine Pitrou152efa22010-05-16 18:19:27 +00001554static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001555{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 Py_buffer buf;
1557 int len;
1558 int sockstate;
1559 int err;
1560 int nonblocking;
1561 PySocketSockObject *sock
1562 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 if (((PyObject*)sock) == Py_None) {
1565 _setSSLError("Underlying socket connection gone",
1566 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1567 return NULL;
1568 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001569 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001571 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1572 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001574 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575
Victor Stinner6efa9652013-06-25 00:42:31 +02001576 if (buf.len > INT_MAX) {
1577 PyErr_Format(PyExc_OverflowError,
1578 "string longer than %d bytes", INT_MAX);
1579 goto error;
1580 }
1581
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 /* just in case the blocking state of the socket has been changed */
1583 nonblocking = (sock->sock_timeout >= 0.0);
1584 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1585 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1586
1587 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1588 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001589 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001590 "The write operation timed out");
1591 goto error;
1592 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1593 PyErr_SetString(PySSLErrorObject,
1594 "Underlying socket has been closed.");
1595 goto error;
1596 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1597 PyErr_SetString(PySSLErrorObject,
1598 "Underlying socket too large for select().");
1599 goto error;
1600 }
1601 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001603 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 err = SSL_get_error(self->ssl, len);
1605 PySSL_END_ALLOW_THREADS
1606 if (PyErr_CheckSignals()) {
1607 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001608 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001610 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001612 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 } else {
1614 sockstate = SOCKET_OPERATION_OK;
1615 }
1616 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001617 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 "The write operation timed out");
1619 goto error;
1620 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1621 PyErr_SetString(PySSLErrorObject,
1622 "Underlying socket has been closed.");
1623 goto error;
1624 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1625 break;
1626 }
1627 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001628
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001629 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 PyBuffer_Release(&buf);
1631 if (len > 0)
1632 return PyLong_FromLong(len);
1633 else
1634 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001635
1636error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001637 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 PyBuffer_Release(&buf);
1639 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001640}
1641
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001642PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001643"write(s) -> len\n\
1644\n\
1645Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001647
Antoine Pitrou152efa22010-05-16 18:19:27 +00001648static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001649{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 PySSL_BEGIN_ALLOW_THREADS
1653 count = SSL_pending(self->ssl);
1654 PySSL_END_ALLOW_THREADS
1655 if (count < 0)
1656 return PySSL_SetError(self, count, __FILE__, __LINE__);
1657 else
1658 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001659}
1660
1661PyDoc_STRVAR(PySSL_SSLpending_doc,
1662"pending() -> count\n\
1663\n\
1664Returns the number of already decrypted bytes available for read,\n\
1665pending on the connection.\n");
1666
Antoine Pitrou152efa22010-05-16 18:19:27 +00001667static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001668{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 PyObject *dest = NULL;
1670 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001672 int len, count;
1673 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 int sockstate;
1675 int err;
1676 int nonblocking;
1677 PySocketSockObject *sock
1678 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 if (((PyObject*)sock) == Py_None) {
1681 _setSSLError("Underlying socket connection gone",
1682 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1683 return NULL;
1684 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001685 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001687 buf.obj = NULL;
1688 buf.buf = NULL;
1689 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001690 goto error;
1691
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001692 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1693 dest = PyBytes_FromStringAndSize(NULL, len);
1694 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001695 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001696 mem = PyBytes_AS_STRING(dest);
1697 }
1698 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001700 mem = buf.buf;
1701 if (len <= 0 || len > buf.len) {
1702 len = (int) buf.len;
1703 if (buf.len != len) {
1704 PyErr_SetString(PyExc_OverflowError,
1705 "maximum length can't fit in a C 'int'");
1706 goto error;
1707 }
1708 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 }
1710
1711 /* just in case the blocking state of the socket has been changed */
1712 nonblocking = (sock->sock_timeout >= 0.0);
1713 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1714 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1715
1716 /* first check if there are bytes ready to be read */
1717 PySSL_BEGIN_ALLOW_THREADS
1718 count = SSL_pending(self->ssl);
1719 PySSL_END_ALLOW_THREADS
1720
1721 if (!count) {
1722 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1723 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001724 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 "The read operation timed out");
1726 goto error;
1727 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1728 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001729 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 goto error;
1731 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1732 count = 0;
1733 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001734 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 }
1736 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PySSL_BEGIN_ALLOW_THREADS
1738 count = SSL_read(self->ssl, mem, len);
1739 err = SSL_get_error(self->ssl, count);
1740 PySSL_END_ALLOW_THREADS
1741 if (PyErr_CheckSignals())
1742 goto error;
1743 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001744 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001746 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1748 (SSL_get_shutdown(self->ssl) ==
1749 SSL_RECEIVED_SHUTDOWN))
1750 {
1751 count = 0;
1752 goto done;
1753 } else {
1754 sockstate = SOCKET_OPERATION_OK;
1755 }
1756 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001757 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001758 "The read operation timed out");
1759 goto error;
1760 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1761 break;
1762 }
1763 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1764 if (count <= 0) {
1765 PySSL_SetError(self, count, __FILE__, __LINE__);
1766 goto error;
1767 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001768
1769done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001770 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001772 _PyBytes_Resize(&dest, count);
1773 return dest;
1774 }
1775 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 PyBuffer_Release(&buf);
1777 return PyLong_FromLong(count);
1778 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001779
1780error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001781 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001782 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001783 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001784 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787}
1788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001789PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001790"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001791\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001792Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001795{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 int err, ssl_err, sockstate, nonblocking;
1797 int zeros = 0;
1798 PySocketSockObject *sock
1799 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 /* Guard against closed socket */
1802 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1803 _setSSLError("Underlying socket connection gone",
1804 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1805 return NULL;
1806 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001807 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808
1809 /* Just in case the blocking state of the socket has been changed */
1810 nonblocking = (sock->sock_timeout >= 0.0);
1811 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1812 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1813
1814 while (1) {
1815 PySSL_BEGIN_ALLOW_THREADS
1816 /* Disable read-ahead so that unwrap can work correctly.
1817 * Otherwise OpenSSL might read in too much data,
1818 * eating clear text data that happens to be
1819 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001820 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 * function is used and the shutdown_seen_zero != 0
1822 * condition is met.
1823 */
1824 if (self->shutdown_seen_zero)
1825 SSL_set_read_ahead(self->ssl, 0);
1826 err = SSL_shutdown(self->ssl);
1827 PySSL_END_ALLOW_THREADS
1828 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1829 if (err > 0)
1830 break;
1831 if (err == 0) {
1832 /* Don't loop endlessly; instead preserve legacy
1833 behaviour of trying SSL_shutdown() only twice.
1834 This looks necessary for OpenSSL < 0.9.8m */
1835 if (++zeros > 1)
1836 break;
1837 /* Shutdown was sent, now try receiving */
1838 self->shutdown_seen_zero = 1;
1839 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001840 }
1841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 /* Possibly retry shutdown until timeout or failure */
1843 ssl_err = SSL_get_error(self->ssl, err);
1844 if (ssl_err == SSL_ERROR_WANT_READ)
1845 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1846 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1847 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1848 else
1849 break;
1850 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1851 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001852 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 "The read operation timed out");
1854 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001855 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001857 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 }
1859 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1860 PyErr_SetString(PySSLErrorObject,
1861 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001862 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 }
1864 else if (sockstate != SOCKET_OPERATION_OK)
1865 /* Retain the SSL error code */
1866 break;
1867 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001868
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001869 if (err < 0) {
1870 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001873 else
1874 /* It's already INCREF'ed */
1875 return (PyObject *) sock;
1876
1877error:
1878 Py_DECREF(sock);
1879 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001880}
1881
1882PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1883"shutdown(s) -> socket\n\
1884\n\
1885Does the SSL shutdown handshake with the remote end, and returns\n\
1886the underlying socket object.");
1887
Antoine Pitroud6494802011-07-21 01:11:30 +02001888#if HAVE_OPENSSL_FINISHED
1889static PyObject *
1890PySSL_tls_unique_cb(PySSLSocket *self)
1891{
1892 PyObject *retval = NULL;
1893 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001894 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001895
1896 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1897 /* if session is resumed XOR we are the client */
1898 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1899 }
1900 else {
1901 /* if a new session XOR we are the server */
1902 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1903 }
1904
1905 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001906 if (len == 0)
1907 Py_RETURN_NONE;
1908
1909 retval = PyBytes_FromStringAndSize(buf, len);
1910
1911 return retval;
1912}
1913
1914PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1915"tls_unique_cb() -> bytes\n\
1916\n\
1917Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1918\n\
1919If the TLS handshake is not yet complete, None is returned");
1920
1921#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001922
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001923static PyGetSetDef ssl_getsetlist[] = {
1924 {"context", (getter) PySSL_get_context,
1925 (setter) PySSL_set_context, PySSL_set_context_doc},
1926 {NULL}, /* sentinel */
1927};
1928
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001929static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1931 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1932 PySSL_SSLwrite_doc},
1933 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1934 PySSL_SSLread_doc},
1935 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1936 PySSL_SSLpending_doc},
1937 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1938 PySSL_peercert_doc},
1939 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001940#ifdef OPENSSL_NPN_NEGOTIATED
1941 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1942#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001943 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1945 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001946#if HAVE_OPENSSL_FINISHED
1947 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1948 PySSL_tls_unique_cb_doc},
1949#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001951};
1952
Antoine Pitrou152efa22010-05-16 18:19:27 +00001953static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001955 "_ssl._SSLSocket", /*tp_name*/
1956 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 0, /*tp_itemsize*/
1958 /* methods */
1959 (destructor)PySSL_dealloc, /*tp_dealloc*/
1960 0, /*tp_print*/
1961 0, /*tp_getattr*/
1962 0, /*tp_setattr*/
1963 0, /*tp_reserved*/
1964 0, /*tp_repr*/
1965 0, /*tp_as_number*/
1966 0, /*tp_as_sequence*/
1967 0, /*tp_as_mapping*/
1968 0, /*tp_hash*/
1969 0, /*tp_call*/
1970 0, /*tp_str*/
1971 0, /*tp_getattro*/
1972 0, /*tp_setattro*/
1973 0, /*tp_as_buffer*/
1974 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1975 0, /*tp_doc*/
1976 0, /*tp_traverse*/
1977 0, /*tp_clear*/
1978 0, /*tp_richcompare*/
1979 0, /*tp_weaklistoffset*/
1980 0, /*tp_iter*/
1981 0, /*tp_iternext*/
1982 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001983 0, /*tp_members*/
1984 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001985};
1986
Antoine Pitrou152efa22010-05-16 18:19:27 +00001987
1988/*
1989 * _SSLContext objects
1990 */
1991
1992static PyObject *
1993context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1994{
1995 char *kwlist[] = {"protocol", NULL};
1996 PySSLContext *self;
1997 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001998 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001999 SSL_CTX *ctx = NULL;
2000
2001 if (!PyArg_ParseTupleAndKeywords(
2002 args, kwds, "i:_SSLContext", kwlist,
2003 &proto_version))
2004 return NULL;
2005
2006 PySSL_BEGIN_ALLOW_THREADS
2007 if (proto_version == PY_SSL_VERSION_TLS1)
2008 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002009#if HAVE_TLSv1_2
2010 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2011 ctx = SSL_CTX_new(TLSv1_1_method());
2012 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2013 ctx = SSL_CTX_new(TLSv1_2_method());
2014#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002015 else if (proto_version == PY_SSL_VERSION_SSL3)
2016 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002017#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002018 else if (proto_version == PY_SSL_VERSION_SSL2)
2019 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002020#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002021 else if (proto_version == PY_SSL_VERSION_SSL23)
2022 ctx = SSL_CTX_new(SSLv23_method());
2023 else
2024 proto_version = -1;
2025 PySSL_END_ALLOW_THREADS
2026
2027 if (proto_version == -1) {
2028 PyErr_SetString(PyExc_ValueError,
2029 "invalid protocol version");
2030 return NULL;
2031 }
2032 if (ctx == NULL) {
2033 PyErr_SetString(PySSLErrorObject,
2034 "failed to allocate SSL context");
2035 return NULL;
2036 }
2037
2038 assert(type != NULL && type->tp_alloc != NULL);
2039 self = (PySSLContext *) type->tp_alloc(type, 0);
2040 if (self == NULL) {
2041 SSL_CTX_free(ctx);
2042 return NULL;
2043 }
2044 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002045#ifdef OPENSSL_NPN_NEGOTIATED
2046 self->npn_protocols = NULL;
2047#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002048#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002049 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002050#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002051 /* Don't check host name by default */
2052 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002053 /* Defaults */
2054 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002055 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2056 if (proto_version != PY_SSL_VERSION_SSL2)
2057 options |= SSL_OP_NO_SSLv2;
2058 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002059
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002060#ifndef OPENSSL_NO_ECDH
2061 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2062 prime256v1 by default. This is Apache mod_ssl's initialization
2063 policy, so we should be safe. */
2064#if defined(SSL_CTX_set_ecdh_auto)
2065 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2066#else
2067 {
2068 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2069 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2070 EC_KEY_free(key);
2071 }
2072#endif
2073#endif
2074
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002075#define SID_CTX "Python"
2076 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2077 sizeof(SID_CTX));
2078#undef SID_CTX
2079
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080 return (PyObject *)self;
2081}
2082
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002083static int
2084context_traverse(PySSLContext *self, visitproc visit, void *arg)
2085{
2086#ifndef OPENSSL_NO_TLSEXT
2087 Py_VISIT(self->set_hostname);
2088#endif
2089 return 0;
2090}
2091
2092static int
2093context_clear(PySSLContext *self)
2094{
2095#ifndef OPENSSL_NO_TLSEXT
2096 Py_CLEAR(self->set_hostname);
2097#endif
2098 return 0;
2099}
2100
Antoine Pitrou152efa22010-05-16 18:19:27 +00002101static void
2102context_dealloc(PySSLContext *self)
2103{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002104 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002105 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002106#ifdef OPENSSL_NPN_NEGOTIATED
2107 PyMem_Free(self->npn_protocols);
2108#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002109 Py_TYPE(self)->tp_free(self);
2110}
2111
2112static PyObject *
2113set_ciphers(PySSLContext *self, PyObject *args)
2114{
2115 int ret;
2116 const char *cipherlist;
2117
2118 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2119 return NULL;
2120 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2121 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002122 /* Clearing the error queue is necessary on some OpenSSL versions,
2123 otherwise the error will be reported again when another SSL call
2124 is done. */
2125 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002126 PyErr_SetString(PySSLErrorObject,
2127 "No cipher can be selected.");
2128 return NULL;
2129 }
2130 Py_RETURN_NONE;
2131}
2132
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002133#ifdef OPENSSL_NPN_NEGOTIATED
2134/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2135static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002136_advertiseNPN_cb(SSL *s,
2137 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002138 void *args)
2139{
2140 PySSLContext *ssl_ctx = (PySSLContext *) args;
2141
2142 if (ssl_ctx->npn_protocols == NULL) {
2143 *data = (unsigned char *) "";
2144 *len = 0;
2145 } else {
2146 *data = (unsigned char *) ssl_ctx->npn_protocols;
2147 *len = ssl_ctx->npn_protocols_len;
2148 }
2149
2150 return SSL_TLSEXT_ERR_OK;
2151}
2152/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2153static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002154_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002155 unsigned char **out, unsigned char *outlen,
2156 const unsigned char *server, unsigned int server_len,
2157 void *args)
2158{
2159 PySSLContext *ssl_ctx = (PySSLContext *) args;
2160
2161 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2162 int client_len;
2163
2164 if (client == NULL) {
2165 client = (unsigned char *) "";
2166 client_len = 0;
2167 } else {
2168 client_len = ssl_ctx->npn_protocols_len;
2169 }
2170
2171 SSL_select_next_proto(out, outlen,
2172 server, server_len,
2173 client, client_len);
2174
2175 return SSL_TLSEXT_ERR_OK;
2176}
2177#endif
2178
2179static PyObject *
2180_set_npn_protocols(PySSLContext *self, PyObject *args)
2181{
2182#ifdef OPENSSL_NPN_NEGOTIATED
2183 Py_buffer protos;
2184
2185 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2186 return NULL;
2187
Christian Heimes5cb31c92012-09-20 12:42:54 +02002188 if (self->npn_protocols != NULL) {
2189 PyMem_Free(self->npn_protocols);
2190 }
2191
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002192 self->npn_protocols = PyMem_Malloc(protos.len);
2193 if (self->npn_protocols == NULL) {
2194 PyBuffer_Release(&protos);
2195 return PyErr_NoMemory();
2196 }
2197 memcpy(self->npn_protocols, protos.buf, protos.len);
2198 self->npn_protocols_len = (int) protos.len;
2199
2200 /* set both server and client callbacks, because the context can
2201 * be used to create both types of sockets */
2202 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2203 _advertiseNPN_cb,
2204 self);
2205 SSL_CTX_set_next_proto_select_cb(self->ctx,
2206 _selectNPN_cb,
2207 self);
2208
2209 PyBuffer_Release(&protos);
2210 Py_RETURN_NONE;
2211#else
2212 PyErr_SetString(PyExc_NotImplementedError,
2213 "The NPN extension requires OpenSSL 1.0.1 or later.");
2214 return NULL;
2215#endif
2216}
2217
Antoine Pitrou152efa22010-05-16 18:19:27 +00002218static PyObject *
2219get_verify_mode(PySSLContext *self, void *c)
2220{
2221 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2222 case SSL_VERIFY_NONE:
2223 return PyLong_FromLong(PY_SSL_CERT_NONE);
2224 case SSL_VERIFY_PEER:
2225 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2226 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2227 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2228 }
2229 PyErr_SetString(PySSLErrorObject,
2230 "invalid return value from SSL_CTX_get_verify_mode");
2231 return NULL;
2232}
2233
2234static int
2235set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2236{
2237 int n, mode;
2238 if (!PyArg_Parse(arg, "i", &n))
2239 return -1;
2240 if (n == PY_SSL_CERT_NONE)
2241 mode = SSL_VERIFY_NONE;
2242 else if (n == PY_SSL_CERT_OPTIONAL)
2243 mode = SSL_VERIFY_PEER;
2244 else if (n == PY_SSL_CERT_REQUIRED)
2245 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2246 else {
2247 PyErr_SetString(PyExc_ValueError,
2248 "invalid value for verify_mode");
2249 return -1;
2250 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002251 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2252 PyErr_SetString(PyExc_ValueError,
2253 "Cannot set verify_mode to CERT_NONE when "
2254 "check_hostname is enabled.");
2255 return -1;
2256 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002257 SSL_CTX_set_verify(self->ctx, mode, NULL);
2258 return 0;
2259}
2260
Christian Heimes2427b502013-11-23 11:24:32 +01002261#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002262static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002263get_verify_flags(PySSLContext *self, void *c)
2264{
2265 X509_STORE *store;
2266 unsigned long flags;
2267
2268 store = SSL_CTX_get_cert_store(self->ctx);
2269 flags = X509_VERIFY_PARAM_get_flags(store->param);
2270 return PyLong_FromUnsignedLong(flags);
2271}
2272
2273static int
2274set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2275{
2276 X509_STORE *store;
2277 unsigned long new_flags, flags, set, clear;
2278
2279 if (!PyArg_Parse(arg, "k", &new_flags))
2280 return -1;
2281 store = SSL_CTX_get_cert_store(self->ctx);
2282 flags = X509_VERIFY_PARAM_get_flags(store->param);
2283 clear = flags & ~new_flags;
2284 set = ~flags & new_flags;
2285 if (clear) {
2286 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2287 _setSSLError(NULL, 0, __FILE__, __LINE__);
2288 return -1;
2289 }
2290 }
2291 if (set) {
2292 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2293 _setSSLError(NULL, 0, __FILE__, __LINE__);
2294 return -1;
2295 }
2296 }
2297 return 0;
2298}
Christian Heimes2427b502013-11-23 11:24:32 +01002299#endif
Christian Heimes22587792013-11-21 23:56:13 +01002300
2301static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002302get_options(PySSLContext *self, void *c)
2303{
2304 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2305}
2306
2307static int
2308set_options(PySSLContext *self, PyObject *arg, void *c)
2309{
2310 long new_opts, opts, set, clear;
2311 if (!PyArg_Parse(arg, "l", &new_opts))
2312 return -1;
2313 opts = SSL_CTX_get_options(self->ctx);
2314 clear = opts & ~new_opts;
2315 set = ~opts & new_opts;
2316 if (clear) {
2317#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2318 SSL_CTX_clear_options(self->ctx, clear);
2319#else
2320 PyErr_SetString(PyExc_ValueError,
2321 "can't clear options before OpenSSL 0.9.8m");
2322 return -1;
2323#endif
2324 }
2325 if (set)
2326 SSL_CTX_set_options(self->ctx, set);
2327 return 0;
2328}
2329
Christian Heimes1aa9a752013-12-02 02:41:19 +01002330static PyObject *
2331get_check_hostname(PySSLContext *self, void *c)
2332{
2333 return PyBool_FromLong(self->check_hostname);
2334}
2335
2336static int
2337set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2338{
2339 int check_hostname;
2340 if (!PyArg_Parse(arg, "p", &check_hostname))
2341 return -1;
2342 if (check_hostname &&
2343 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2344 PyErr_SetString(PyExc_ValueError,
2345 "check_hostname needs a SSL context with either "
2346 "CERT_OPTIONAL or CERT_REQUIRED");
2347 return -1;
2348 }
2349 self->check_hostname = check_hostname;
2350 return 0;
2351}
2352
2353
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002354typedef struct {
2355 PyThreadState *thread_state;
2356 PyObject *callable;
2357 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002358 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002359 int error;
2360} _PySSLPasswordInfo;
2361
2362static int
2363_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2364 const char *bad_type_error)
2365{
2366 /* Set the password and size fields of a _PySSLPasswordInfo struct
2367 from a unicode, bytes, or byte array object.
2368 The password field will be dynamically allocated and must be freed
2369 by the caller */
2370 PyObject *password_bytes = NULL;
2371 const char *data = NULL;
2372 Py_ssize_t size;
2373
2374 if (PyUnicode_Check(password)) {
2375 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2376 if (!password_bytes) {
2377 goto error;
2378 }
2379 data = PyBytes_AS_STRING(password_bytes);
2380 size = PyBytes_GET_SIZE(password_bytes);
2381 } else if (PyBytes_Check(password)) {
2382 data = PyBytes_AS_STRING(password);
2383 size = PyBytes_GET_SIZE(password);
2384 } else if (PyByteArray_Check(password)) {
2385 data = PyByteArray_AS_STRING(password);
2386 size = PyByteArray_GET_SIZE(password);
2387 } else {
2388 PyErr_SetString(PyExc_TypeError, bad_type_error);
2389 goto error;
2390 }
2391
Victor Stinner9ee02032013-06-23 15:08:23 +02002392 if (size > (Py_ssize_t)INT_MAX) {
2393 PyErr_Format(PyExc_ValueError,
2394 "password cannot be longer than %d bytes", INT_MAX);
2395 goto error;
2396 }
2397
Victor Stinner11ebff22013-07-07 17:07:52 +02002398 PyMem_Free(pw_info->password);
2399 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002400 if (!pw_info->password) {
2401 PyErr_SetString(PyExc_MemoryError,
2402 "unable to allocate password buffer");
2403 goto error;
2404 }
2405 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002406 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002407
2408 Py_XDECREF(password_bytes);
2409 return 1;
2410
2411error:
2412 Py_XDECREF(password_bytes);
2413 return 0;
2414}
2415
2416static int
2417_password_callback(char *buf, int size, int rwflag, void *userdata)
2418{
2419 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2420 PyObject *fn_ret = NULL;
2421
2422 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2423
2424 if (pw_info->callable) {
2425 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2426 if (!fn_ret) {
2427 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2428 core python API, so we could use it to add a frame here */
2429 goto error;
2430 }
2431
2432 if (!_pwinfo_set(pw_info, fn_ret,
2433 "password callback must return a string")) {
2434 goto error;
2435 }
2436 Py_CLEAR(fn_ret);
2437 }
2438
2439 if (pw_info->size > size) {
2440 PyErr_Format(PyExc_ValueError,
2441 "password cannot be longer than %d bytes", size);
2442 goto error;
2443 }
2444
2445 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2446 memcpy(buf, pw_info->password, pw_info->size);
2447 return pw_info->size;
2448
2449error:
2450 Py_XDECREF(fn_ret);
2451 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2452 pw_info->error = 1;
2453 return -1;
2454}
2455
Antoine Pitroub5218772010-05-21 09:56:06 +00002456static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002457load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2458{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002459 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2460 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002461 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002462 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2463 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2464 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002465 int r;
2466
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002467 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002468 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002469 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002470 "O|OO:load_cert_chain", kwlist,
2471 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002472 return NULL;
2473 if (keyfile == Py_None)
2474 keyfile = NULL;
2475 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2476 PyErr_SetString(PyExc_TypeError,
2477 "certfile should be a valid filesystem path");
2478 return NULL;
2479 }
2480 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2481 PyErr_SetString(PyExc_TypeError,
2482 "keyfile should be a valid filesystem path");
2483 goto error;
2484 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002485 if (password && password != Py_None) {
2486 if (PyCallable_Check(password)) {
2487 pw_info.callable = password;
2488 } else if (!_pwinfo_set(&pw_info, password,
2489 "password should be a string or callable")) {
2490 goto error;
2491 }
2492 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2493 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2494 }
2495 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002496 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2497 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002498 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002499 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002500 if (pw_info.error) {
2501 ERR_clear_error();
2502 /* the password callback has already set the error information */
2503 }
2504 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002505 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002506 PyErr_SetFromErrno(PyExc_IOError);
2507 }
2508 else {
2509 _setSSLError(NULL, 0, __FILE__, __LINE__);
2510 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002511 goto error;
2512 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002513 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002514 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002515 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2516 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002517 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2518 Py_CLEAR(keyfile_bytes);
2519 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002520 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002521 if (pw_info.error) {
2522 ERR_clear_error();
2523 /* the password callback has already set the error information */
2524 }
2525 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002526 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002527 PyErr_SetFromErrno(PyExc_IOError);
2528 }
2529 else {
2530 _setSSLError(NULL, 0, __FILE__, __LINE__);
2531 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002532 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002533 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002534 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002535 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002536 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002537 if (r != 1) {
2538 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002539 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002540 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002541 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2542 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002543 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002544 Py_RETURN_NONE;
2545
2546error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002547 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2548 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002549 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002550 Py_XDECREF(keyfile_bytes);
2551 Py_XDECREF(certfile_bytes);
2552 return NULL;
2553}
2554
Christian Heimesefff7062013-11-21 03:35:02 +01002555/* internal helper function, returns -1 on error
2556 */
2557static int
2558_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2559 int filetype)
2560{
2561 BIO *biobuf = NULL;
2562 X509_STORE *store;
2563 int retval = 0, err, loaded = 0;
2564
2565 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2566
2567 if (len <= 0) {
2568 PyErr_SetString(PyExc_ValueError,
2569 "Empty certificate data");
2570 return -1;
2571 } else if (len > INT_MAX) {
2572 PyErr_SetString(PyExc_OverflowError,
2573 "Certificate data is too long.");
2574 return -1;
2575 }
2576
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002577 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002578 if (biobuf == NULL) {
2579 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2580 return -1;
2581 }
2582
2583 store = SSL_CTX_get_cert_store(self->ctx);
2584 assert(store != NULL);
2585
2586 while (1) {
2587 X509 *cert = NULL;
2588 int r;
2589
2590 if (filetype == SSL_FILETYPE_ASN1) {
2591 cert = d2i_X509_bio(biobuf, NULL);
2592 } else {
2593 cert = PEM_read_bio_X509(biobuf, NULL,
2594 self->ctx->default_passwd_callback,
2595 self->ctx->default_passwd_callback_userdata);
2596 }
2597 if (cert == NULL) {
2598 break;
2599 }
2600 r = X509_STORE_add_cert(store, cert);
2601 X509_free(cert);
2602 if (!r) {
2603 err = ERR_peek_last_error();
2604 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2605 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2606 /* cert already in hash table, not an error */
2607 ERR_clear_error();
2608 } else {
2609 break;
2610 }
2611 }
2612 loaded++;
2613 }
2614
2615 err = ERR_peek_last_error();
2616 if ((filetype == SSL_FILETYPE_ASN1) &&
2617 (loaded > 0) &&
2618 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2619 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2620 /* EOF ASN1 file, not an error */
2621 ERR_clear_error();
2622 retval = 0;
2623 } else if ((filetype == SSL_FILETYPE_PEM) &&
2624 (loaded > 0) &&
2625 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2626 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2627 /* EOF PEM file, not an error */
2628 ERR_clear_error();
2629 retval = 0;
2630 } else {
2631 _setSSLError(NULL, 0, __FILE__, __LINE__);
2632 retval = -1;
2633 }
2634
2635 BIO_free(biobuf);
2636 return retval;
2637}
2638
2639
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640static PyObject *
2641load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2642{
Christian Heimesefff7062013-11-21 03:35:02 +01002643 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2644 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002645 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2646 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002647 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002648
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002649 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002650 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002651 "|OOO:load_verify_locations", kwlist,
2652 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002653 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002654
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 if (cafile == Py_None)
2656 cafile = NULL;
2657 if (capath == Py_None)
2658 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002659 if (cadata == Py_None)
2660 cadata = NULL;
2661
2662 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002663 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002664 "cafile, capath and cadata cannot be all omitted");
2665 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002666 }
2667 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2668 PyErr_SetString(PyExc_TypeError,
2669 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002670 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002671 }
2672 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673 PyErr_SetString(PyExc_TypeError,
2674 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002675 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002676 }
Christian Heimesefff7062013-11-21 03:35:02 +01002677
2678 /* validata cadata type and load cadata */
2679 if (cadata) {
2680 Py_buffer buf;
2681 PyObject *cadata_ascii = NULL;
2682
2683 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2684 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2685 PyBuffer_Release(&buf);
2686 PyErr_SetString(PyExc_TypeError,
2687 "cadata should be a contiguous buffer with "
2688 "a single dimension");
2689 goto error;
2690 }
2691 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2692 PyBuffer_Release(&buf);
2693 if (r == -1) {
2694 goto error;
2695 }
2696 } else {
2697 PyErr_Clear();
2698 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2699 if (cadata_ascii == NULL) {
2700 PyErr_SetString(PyExc_TypeError,
2701 "cadata should be a ASCII string or a "
2702 "bytes-like object");
2703 goto error;
2704 }
2705 r = _add_ca_certs(self,
2706 PyBytes_AS_STRING(cadata_ascii),
2707 PyBytes_GET_SIZE(cadata_ascii),
2708 SSL_FILETYPE_PEM);
2709 Py_DECREF(cadata_ascii);
2710 if (r == -1) {
2711 goto error;
2712 }
2713 }
2714 }
2715
2716 /* load cafile or capath */
2717 if (cafile || capath) {
2718 if (cafile)
2719 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2720 if (capath)
2721 capath_buf = PyBytes_AS_STRING(capath_bytes);
2722 PySSL_BEGIN_ALLOW_THREADS
2723 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2724 PySSL_END_ALLOW_THREADS
2725 if (r != 1) {
2726 ok = 0;
2727 if (errno != 0) {
2728 ERR_clear_error();
2729 PyErr_SetFromErrno(PyExc_IOError);
2730 }
2731 else {
2732 _setSSLError(NULL, 0, __FILE__, __LINE__);
2733 }
2734 goto error;
2735 }
2736 }
2737 goto end;
2738
2739 error:
2740 ok = 0;
2741 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002742 Py_XDECREF(cafile_bytes);
2743 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002744 if (ok) {
2745 Py_RETURN_NONE;
2746 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002747 return NULL;
2748 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002749}
2750
2751static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002752load_dh_params(PySSLContext *self, PyObject *filepath)
2753{
2754 FILE *f;
2755 DH *dh;
2756
Victor Stinnerdaf45552013-08-28 00:53:59 +02002757 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002758 if (f == NULL) {
2759 if (!PyErr_Occurred())
2760 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2761 return NULL;
2762 }
2763 errno = 0;
2764 PySSL_BEGIN_ALLOW_THREADS
2765 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002766 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002767 PySSL_END_ALLOW_THREADS
2768 if (dh == NULL) {
2769 if (errno != 0) {
2770 ERR_clear_error();
2771 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2772 }
2773 else {
2774 _setSSLError(NULL, 0, __FILE__, __LINE__);
2775 }
2776 return NULL;
2777 }
2778 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2779 _setSSLError(NULL, 0, __FILE__, __LINE__);
2780 DH_free(dh);
2781 Py_RETURN_NONE;
2782}
2783
2784static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2786{
Antoine Pitroud5323212010-10-22 18:19:07 +00002787 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788 PySocketSockObject *sock;
2789 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002790 char *hostname = NULL;
2791 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792
Antoine Pitroud5323212010-10-22 18:19:07 +00002793 /* server_hostname is either None (or absent), or to be encoded
2794 using the idna encoding. */
2795 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002796 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002797 &sock, &server_side,
2798 Py_TYPE(Py_None), &hostname_obj)) {
2799 PyErr_Clear();
2800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2801 PySocketModule.Sock_Type,
2802 &sock, &server_side,
2803 "idna", &hostname))
2804 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002805#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002806 PyMem_Free(hostname);
2807 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2808 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002809 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002810#endif
2811 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002812
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002813 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002814 hostname);
2815 if (hostname != NULL)
2816 PyMem_Free(hostname);
2817 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818}
2819
Antoine Pitroub0182c82010-10-12 20:09:02 +00002820static PyObject *
2821session_stats(PySSLContext *self, PyObject *unused)
2822{
2823 int r;
2824 PyObject *value, *stats = PyDict_New();
2825 if (!stats)
2826 return NULL;
2827
2828#define ADD_STATS(SSL_NAME, KEY_NAME) \
2829 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2830 if (value == NULL) \
2831 goto error; \
2832 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2833 Py_DECREF(value); \
2834 if (r < 0) \
2835 goto error;
2836
2837 ADD_STATS(number, "number");
2838 ADD_STATS(connect, "connect");
2839 ADD_STATS(connect_good, "connect_good");
2840 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2841 ADD_STATS(accept, "accept");
2842 ADD_STATS(accept_good, "accept_good");
2843 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2844 ADD_STATS(accept, "accept");
2845 ADD_STATS(hits, "hits");
2846 ADD_STATS(misses, "misses");
2847 ADD_STATS(timeouts, "timeouts");
2848 ADD_STATS(cache_full, "cache_full");
2849
2850#undef ADD_STATS
2851
2852 return stats;
2853
2854error:
2855 Py_DECREF(stats);
2856 return NULL;
2857}
2858
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002859static PyObject *
2860set_default_verify_paths(PySSLContext *self, PyObject *unused)
2861{
2862 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2863 _setSSLError(NULL, 0, __FILE__, __LINE__);
2864 return NULL;
2865 }
2866 Py_RETURN_NONE;
2867}
2868
Antoine Pitrou501da612011-12-21 09:27:41 +01002869#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002870static PyObject *
2871set_ecdh_curve(PySSLContext *self, PyObject *name)
2872{
2873 PyObject *name_bytes;
2874 int nid;
2875 EC_KEY *key;
2876
2877 if (!PyUnicode_FSConverter(name, &name_bytes))
2878 return NULL;
2879 assert(PyBytes_Check(name_bytes));
2880 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2881 Py_DECREF(name_bytes);
2882 if (nid == 0) {
2883 PyErr_Format(PyExc_ValueError,
2884 "unknown elliptic curve name %R", name);
2885 return NULL;
2886 }
2887 key = EC_KEY_new_by_curve_name(nid);
2888 if (key == NULL) {
2889 _setSSLError(NULL, 0, __FILE__, __LINE__);
2890 return NULL;
2891 }
2892 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2893 EC_KEY_free(key);
2894 Py_RETURN_NONE;
2895}
Antoine Pitrou501da612011-12-21 09:27:41 +01002896#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002897
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002898#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002899static int
2900_servername_callback(SSL *s, int *al, void *args)
2901{
2902 int ret;
2903 PySSLContext *ssl_ctx = (PySSLContext *) args;
2904 PySSLSocket *ssl;
2905 PyObject *servername_o;
2906 PyObject *servername_idna;
2907 PyObject *result;
2908 /* The high-level ssl.SSLSocket object */
2909 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002910 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002911#ifdef WITH_THREAD
2912 PyGILState_STATE gstate = PyGILState_Ensure();
2913#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002914
2915 if (ssl_ctx->set_hostname == NULL) {
2916 /* remove race condition in this the call back while if removing the
2917 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002918#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002919 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002920#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002921 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002922 }
2923
2924 ssl = SSL_get_app_data(s);
2925 assert(PySSLSocket_Check(ssl));
2926 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2927 Py_INCREF(ssl_socket);
2928 if (ssl_socket == Py_None) {
2929 goto error;
2930 }
Victor Stinner7e001512013-06-25 00:44:31 +02002931
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002932 if (servername == NULL) {
2933 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2934 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002935 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002936 else {
2937 servername_o = PyBytes_FromString(servername);
2938 if (servername_o == NULL) {
2939 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2940 goto error;
2941 }
2942 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2943 if (servername_idna == NULL) {
2944 PyErr_WriteUnraisable(servername_o);
2945 Py_DECREF(servername_o);
2946 goto error;
2947 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002948 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002949 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2950 servername_idna, ssl_ctx, NULL);
2951 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002952 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002953 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002954
2955 if (result == NULL) {
2956 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2957 *al = SSL_AD_HANDSHAKE_FAILURE;
2958 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2959 }
2960 else {
2961 if (result != Py_None) {
2962 *al = (int) PyLong_AsLong(result);
2963 if (PyErr_Occurred()) {
2964 PyErr_WriteUnraisable(result);
2965 *al = SSL_AD_INTERNAL_ERROR;
2966 }
2967 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2968 }
2969 else {
2970 ret = SSL_TLSEXT_ERR_OK;
2971 }
2972 Py_DECREF(result);
2973 }
2974
Stefan Krah20d60802013-01-17 17:07:17 +01002975#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002976 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002977#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002978 return ret;
2979
2980error:
2981 Py_DECREF(ssl_socket);
2982 *al = SSL_AD_INTERNAL_ERROR;
2983 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002984#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002985 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002986#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002987 return ret;
2988}
Antoine Pitroua5963382013-03-30 16:39:00 +01002989#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002990
2991PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2992"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002993\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002994This sets a callback that will be called when a server name is provided by\n\
2995the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002996\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002997If the argument is None then the callback is disabled. The method is called\n\
2998with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002999See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003000
3001static PyObject *
3002set_servername_callback(PySSLContext *self, PyObject *args)
3003{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003004#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003005 PyObject *cb;
3006
3007 if (!PyArg_ParseTuple(args, "O", &cb))
3008 return NULL;
3009
3010 Py_CLEAR(self->set_hostname);
3011 if (cb == Py_None) {
3012 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3013 }
3014 else {
3015 if (!PyCallable_Check(cb)) {
3016 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3017 PyErr_SetString(PyExc_TypeError,
3018 "not a callable object");
3019 return NULL;
3020 }
3021 Py_INCREF(cb);
3022 self->set_hostname = cb;
3023 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3024 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3025 }
3026 Py_RETURN_NONE;
3027#else
3028 PyErr_SetString(PyExc_NotImplementedError,
3029 "The TLS extension servername callback, "
3030 "SSL_CTX_set_tlsext_servername_callback, "
3031 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003032 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003033#endif
3034}
3035
Christian Heimes9a5395a2013-06-17 15:44:12 +02003036PyDoc_STRVAR(PySSL_get_stats_doc,
3037"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3038\n\
3039Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3040CA extension and certificate revocation lists inside the context's cert\n\
3041store.\n\
3042NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3043been used at least once.");
3044
3045static PyObject *
3046cert_store_stats(PySSLContext *self)
3047{
3048 X509_STORE *store;
3049 X509_OBJECT *obj;
3050 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3051
3052 store = SSL_CTX_get_cert_store(self->ctx);
3053 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3054 obj = sk_X509_OBJECT_value(store->objs, i);
3055 switch (obj->type) {
3056 case X509_LU_X509:
3057 x509++;
3058 if (X509_check_ca(obj->data.x509)) {
3059 ca++;
3060 }
3061 break;
3062 case X509_LU_CRL:
3063 crl++;
3064 break;
3065 case X509_LU_PKEY:
3066 pkey++;
3067 break;
3068 default:
3069 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3070 * As far as I can tell they are internal states and never
3071 * stored in a cert store */
3072 break;
3073 }
3074 }
3075 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3076 "x509_ca", ca);
3077}
3078
3079PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003080"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003081\n\
3082Returns a list of dicts with information of loaded CA certs. If the\n\
3083optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3084NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3085been used at least once.");
3086
3087static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003088get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003089{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003090 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003091 X509_STORE *store;
3092 PyObject *ci = NULL, *rlist = NULL;
3093 int i;
3094 int binary_mode = 0;
3095
Christian Heimesf22e8e52013-11-22 02:22:51 +01003096 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3097 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003098 return NULL;
3099 }
3100
3101 if ((rlist = PyList_New(0)) == NULL) {
3102 return NULL;
3103 }
3104
3105 store = SSL_CTX_get_cert_store(self->ctx);
3106 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3107 X509_OBJECT *obj;
3108 X509 *cert;
3109
3110 obj = sk_X509_OBJECT_value(store->objs, i);
3111 if (obj->type != X509_LU_X509) {
3112 /* not a x509 cert */
3113 continue;
3114 }
3115 /* CA for any purpose */
3116 cert = obj->data.x509;
3117 if (!X509_check_ca(cert)) {
3118 continue;
3119 }
3120 if (binary_mode) {
3121 ci = _certificate_to_der(cert);
3122 } else {
3123 ci = _decode_certificate(cert);
3124 }
3125 if (ci == NULL) {
3126 goto error;
3127 }
3128 if (PyList_Append(rlist, ci) == -1) {
3129 goto error;
3130 }
3131 Py_CLEAR(ci);
3132 }
3133 return rlist;
3134
3135 error:
3136 Py_XDECREF(ci);
3137 Py_XDECREF(rlist);
3138 return NULL;
3139}
3140
3141
Antoine Pitrou152efa22010-05-16 18:19:27 +00003142static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003143 {"check_hostname", (getter) get_check_hostname,
3144 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003145 {"options", (getter) get_options,
3146 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003147#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003148 {"verify_flags", (getter) get_verify_flags,
3149 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003150#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003151 {"verify_mode", (getter) get_verify_mode,
3152 (setter) set_verify_mode, NULL},
3153 {NULL}, /* sentinel */
3154};
3155
3156static struct PyMethodDef context_methods[] = {
3157 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3158 METH_VARARGS | METH_KEYWORDS, NULL},
3159 {"set_ciphers", (PyCFunction) set_ciphers,
3160 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003161 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3162 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003163 {"load_cert_chain", (PyCFunction) load_cert_chain,
3164 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003165 {"load_dh_params", (PyCFunction) load_dh_params,
3166 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003167 {"load_verify_locations", (PyCFunction) load_verify_locations,
3168 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003169 {"session_stats", (PyCFunction) session_stats,
3170 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003171 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3172 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003173#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003174 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3175 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003176#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003177 {"set_servername_callback", (PyCFunction) set_servername_callback,
3178 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003179 {"cert_store_stats", (PyCFunction) cert_store_stats,
3180 METH_NOARGS, PySSL_get_stats_doc},
3181 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003182 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003183 {NULL, NULL} /* sentinel */
3184};
3185
3186static PyTypeObject PySSLContext_Type = {
3187 PyVarObject_HEAD_INIT(NULL, 0)
3188 "_ssl._SSLContext", /*tp_name*/
3189 sizeof(PySSLContext), /*tp_basicsize*/
3190 0, /*tp_itemsize*/
3191 (destructor)context_dealloc, /*tp_dealloc*/
3192 0, /*tp_print*/
3193 0, /*tp_getattr*/
3194 0, /*tp_setattr*/
3195 0, /*tp_reserved*/
3196 0, /*tp_repr*/
3197 0, /*tp_as_number*/
3198 0, /*tp_as_sequence*/
3199 0, /*tp_as_mapping*/
3200 0, /*tp_hash*/
3201 0, /*tp_call*/
3202 0, /*tp_str*/
3203 0, /*tp_getattro*/
3204 0, /*tp_setattro*/
3205 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003206 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003207 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003208 (traverseproc) context_traverse, /*tp_traverse*/
3209 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003210 0, /*tp_richcompare*/
3211 0, /*tp_weaklistoffset*/
3212 0, /*tp_iter*/
3213 0, /*tp_iternext*/
3214 context_methods, /*tp_methods*/
3215 0, /*tp_members*/
3216 context_getsetlist, /*tp_getset*/
3217 0, /*tp_base*/
3218 0, /*tp_dict*/
3219 0, /*tp_descr_get*/
3220 0, /*tp_descr_set*/
3221 0, /*tp_dictoffset*/
3222 0, /*tp_init*/
3223 0, /*tp_alloc*/
3224 context_new, /*tp_new*/
3225};
3226
3227
3228
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003229#ifdef HAVE_OPENSSL_RAND
3230
3231/* helper routines for seeding the SSL PRNG */
3232static PyObject *
3233PySSL_RAND_add(PyObject *self, PyObject *args)
3234{
3235 char *buf;
3236 int len;
3237 double entropy;
3238
3239 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003240 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003241 RAND_add(buf, len, entropy);
3242 Py_INCREF(Py_None);
3243 return Py_None;
3244}
3245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003246PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003247"RAND_add(string, entropy)\n\
3248\n\
3249Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003250bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003251
3252static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003253PySSL_RAND(int len, int pseudo)
3254{
3255 int ok;
3256 PyObject *bytes;
3257 unsigned long err;
3258 const char *errstr;
3259 PyObject *v;
3260
Victor Stinner1e81a392013-12-19 16:47:04 +01003261 if (len < 0) {
3262 PyErr_SetString(PyExc_ValueError, "num must be positive");
3263 return NULL;
3264 }
3265
Victor Stinner99c8b162011-05-24 12:05:19 +02003266 bytes = PyBytes_FromStringAndSize(NULL, len);
3267 if (bytes == NULL)
3268 return NULL;
3269 if (pseudo) {
3270 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3271 if (ok == 0 || ok == 1)
3272 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3273 }
3274 else {
3275 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3276 if (ok == 1)
3277 return bytes;
3278 }
3279 Py_DECREF(bytes);
3280
3281 err = ERR_get_error();
3282 errstr = ERR_reason_error_string(err);
3283 v = Py_BuildValue("(ks)", err, errstr);
3284 if (v != NULL) {
3285 PyErr_SetObject(PySSLErrorObject, v);
3286 Py_DECREF(v);
3287 }
3288 return NULL;
3289}
3290
3291static PyObject *
3292PySSL_RAND_bytes(PyObject *self, PyObject *args)
3293{
3294 int len;
3295 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3296 return NULL;
3297 return PySSL_RAND(len, 0);
3298}
3299
3300PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3301"RAND_bytes(n) -> bytes\n\
3302\n\
3303Generate n cryptographically strong pseudo-random bytes.");
3304
3305static PyObject *
3306PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3307{
3308 int len;
3309 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3310 return NULL;
3311 return PySSL_RAND(len, 1);
3312}
3313
3314PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3315"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3316\n\
3317Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3318generated are cryptographically strong.");
3319
3320static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003321PySSL_RAND_status(PyObject *self)
3322{
Christian Heimes217cfd12007-12-02 14:31:20 +00003323 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003324}
3325
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003326PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003327"RAND_status() -> 0 or 1\n\
3328\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003329Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3330It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3331using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003332
3333static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003334PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003335{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003336 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003337 int bytes;
3338
Jesus Ceac8754a12012-09-11 02:00:58 +02003339 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003340 PyUnicode_FSConverter, &path))
3341 return NULL;
3342
3343 bytes = RAND_egd(PyBytes_AsString(path));
3344 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003345 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003346 PyErr_SetString(PySSLErrorObject,
3347 "EGD connection failed or EGD did not return "
3348 "enough data to seed the PRNG");
3349 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003350 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003351 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003352}
3353
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003354PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003355"RAND_egd(path) -> bytes\n\
3356\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003357Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3358Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003359fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003360
Christian Heimesf77b4b22013-08-21 13:26:05 +02003361#endif /* HAVE_OPENSSL_RAND */
3362
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003363
Christian Heimes6d7ad132013-06-09 18:02:55 +02003364PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3365"get_default_verify_paths() -> tuple\n\
3366\n\
3367Return search paths and environment vars that are used by SSLContext's\n\
3368set_default_verify_paths() to load default CAs. The values are\n\
3369'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3370
3371static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003372PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003373{
3374 PyObject *ofile_env = NULL;
3375 PyObject *ofile = NULL;
3376 PyObject *odir_env = NULL;
3377 PyObject *odir = NULL;
3378
3379#define convert(info, target) { \
3380 const char *tmp = (info); \
3381 target = NULL; \
3382 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3383 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3384 target = PyBytes_FromString(tmp); } \
3385 if (!target) goto error; \
3386 } while(0)
3387
3388 convert(X509_get_default_cert_file_env(), ofile_env);
3389 convert(X509_get_default_cert_file(), ofile);
3390 convert(X509_get_default_cert_dir_env(), odir_env);
3391 convert(X509_get_default_cert_dir(), odir);
3392#undef convert
3393
Christian Heimes200bb1b2013-06-14 15:14:29 +02003394 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003395
3396 error:
3397 Py_XDECREF(ofile_env);
3398 Py_XDECREF(ofile);
3399 Py_XDECREF(odir_env);
3400 Py_XDECREF(odir);
3401 return NULL;
3402}
3403
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003404static PyObject*
3405asn1obj2py(ASN1_OBJECT *obj)
3406{
3407 int nid;
3408 const char *ln, *sn;
3409 char buf[100];
3410 int buflen;
3411
3412 nid = OBJ_obj2nid(obj);
3413 if (nid == NID_undef) {
3414 PyErr_Format(PyExc_ValueError, "Unknown object");
3415 return NULL;
3416 }
3417 sn = OBJ_nid2sn(nid);
3418 ln = OBJ_nid2ln(nid);
3419 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3420 if (buflen < 0) {
3421 _setSSLError(NULL, 0, __FILE__, __LINE__);
3422 return NULL;
3423 }
3424 if (buflen) {
3425 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3426 } else {
3427 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3428 }
3429}
3430
3431PyDoc_STRVAR(PySSL_txt2obj_doc,
3432"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3433\n\
3434Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3435objects are looked up by OID. With name=True short and long name are also\n\
3436matched.");
3437
3438static PyObject*
3439PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3440{
3441 char *kwlist[] = {"txt", "name", NULL};
3442 PyObject *result = NULL;
3443 char *txt;
3444 int name = 0;
3445 ASN1_OBJECT *obj;
3446
3447 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3448 kwlist, &txt, &name)) {
3449 return NULL;
3450 }
3451 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3452 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003453 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003454 return NULL;
3455 }
3456 result = asn1obj2py(obj);
3457 ASN1_OBJECT_free(obj);
3458 return result;
3459}
3460
3461PyDoc_STRVAR(PySSL_nid2obj_doc,
3462"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3463\n\
3464Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3465
3466static PyObject*
3467PySSL_nid2obj(PyObject *self, PyObject *args)
3468{
3469 PyObject *result = NULL;
3470 int nid;
3471 ASN1_OBJECT *obj;
3472
3473 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3474 return NULL;
3475 }
3476 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003477 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003478 return NULL;
3479 }
3480 obj = OBJ_nid2obj(nid);
3481 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003482 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003483 return NULL;
3484 }
3485 result = asn1obj2py(obj);
3486 ASN1_OBJECT_free(obj);
3487 return result;
3488}
3489
Christian Heimes46bebee2013-06-09 19:03:31 +02003490#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003491
3492static PyObject*
3493certEncodingType(DWORD encodingType)
3494{
3495 static PyObject *x509_asn = NULL;
3496 static PyObject *pkcs_7_asn = NULL;
3497
3498 if (x509_asn == NULL) {
3499 x509_asn = PyUnicode_InternFromString("x509_asn");
3500 if (x509_asn == NULL)
3501 return NULL;
3502 }
3503 if (pkcs_7_asn == NULL) {
3504 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3505 if (pkcs_7_asn == NULL)
3506 return NULL;
3507 }
3508 switch(encodingType) {
3509 case X509_ASN_ENCODING:
3510 Py_INCREF(x509_asn);
3511 return x509_asn;
3512 case PKCS_7_ASN_ENCODING:
3513 Py_INCREF(pkcs_7_asn);
3514 return pkcs_7_asn;
3515 default:
3516 return PyLong_FromLong(encodingType);
3517 }
3518}
3519
3520static PyObject*
3521parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3522{
3523 CERT_ENHKEY_USAGE *usage;
3524 DWORD size, error, i;
3525 PyObject *retval;
3526
3527 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3528 error = GetLastError();
3529 if (error == CRYPT_E_NOT_FOUND) {
3530 Py_RETURN_TRUE;
3531 }
3532 return PyErr_SetFromWindowsErr(error);
3533 }
3534
3535 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3536 if (usage == NULL) {
3537 return PyErr_NoMemory();
3538 }
3539
3540 /* Now get the actual enhanced usage property */
3541 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3542 PyMem_Free(usage);
3543 error = GetLastError();
3544 if (error == CRYPT_E_NOT_FOUND) {
3545 Py_RETURN_TRUE;
3546 }
3547 return PyErr_SetFromWindowsErr(error);
3548 }
3549 retval = PySet_New(NULL);
3550 if (retval == NULL) {
3551 goto error;
3552 }
3553 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3554 if (usage->rgpszUsageIdentifier[i]) {
3555 PyObject *oid;
3556 int err;
3557 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3558 if (oid == NULL) {
3559 Py_CLEAR(retval);
3560 goto error;
3561 }
3562 err = PySet_Add(retval, oid);
3563 Py_DECREF(oid);
3564 if (err == -1) {
3565 Py_CLEAR(retval);
3566 goto error;
3567 }
3568 }
3569 }
3570 error:
3571 PyMem_Free(usage);
3572 return retval;
3573}
3574
3575PyDoc_STRVAR(PySSL_enum_certificates_doc,
3576"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003577\n\
3578Retrieve certificates from Windows' cert store. store_name may be one of\n\
3579'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003580The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003581encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003582PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3583boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003584
Christian Heimes46bebee2013-06-09 19:03:31 +02003585static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003586PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003587{
Christian Heimes44109d72013-11-22 01:51:30 +01003588 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003589 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003590 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003591 PCCERT_CONTEXT pCertCtx = NULL;
3592 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003593 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003594
Christian Heimes44109d72013-11-22 01:51:30 +01003595 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3596 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003597 return NULL;
3598 }
Christian Heimes44109d72013-11-22 01:51:30 +01003599 result = PyList_New(0);
3600 if (result == NULL) {
3601 return NULL;
3602 }
3603 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3604 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003605 Py_DECREF(result);
3606 return PyErr_SetFromWindowsErr(GetLastError());
3607 }
3608
Christian Heimes44109d72013-11-22 01:51:30 +01003609 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3610 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3611 pCertCtx->cbCertEncoded);
3612 if (!cert) {
3613 Py_CLEAR(result);
3614 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003615 }
Christian Heimes44109d72013-11-22 01:51:30 +01003616 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3617 Py_CLEAR(result);
3618 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003619 }
Christian Heimes44109d72013-11-22 01:51:30 +01003620 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3621 if (keyusage == Py_True) {
3622 Py_DECREF(keyusage);
3623 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003624 }
Christian Heimes44109d72013-11-22 01:51:30 +01003625 if (keyusage == NULL) {
3626 Py_CLEAR(result);
3627 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003628 }
Christian Heimes44109d72013-11-22 01:51:30 +01003629 if ((tup = PyTuple_New(3)) == NULL) {
3630 Py_CLEAR(result);
3631 break;
3632 }
3633 PyTuple_SET_ITEM(tup, 0, cert);
3634 cert = NULL;
3635 PyTuple_SET_ITEM(tup, 1, enc);
3636 enc = NULL;
3637 PyTuple_SET_ITEM(tup, 2, keyusage);
3638 keyusage = NULL;
3639 if (PyList_Append(result, tup) < 0) {
3640 Py_CLEAR(result);
3641 break;
3642 }
3643 Py_CLEAR(tup);
3644 }
3645 if (pCertCtx) {
3646 /* loop ended with an error, need to clean up context manually */
3647 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003648 }
3649
3650 /* In error cases cert, enc and tup may not be NULL */
3651 Py_XDECREF(cert);
3652 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003653 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003654 Py_XDECREF(tup);
3655
3656 if (!CertCloseStore(hStore, 0)) {
3657 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003658 Py_XDECREF(result);
3659 return PyErr_SetFromWindowsErr(GetLastError());
3660 }
3661 return result;
3662}
3663
3664PyDoc_STRVAR(PySSL_enum_crls_doc,
3665"enum_crls(store_name) -> []\n\
3666\n\
3667Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3668'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3669The function returns a list of (bytes, encoding_type) tuples. The\n\
3670encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3671PKCS_7_ASN_ENCODING.");
3672
3673static PyObject *
3674PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3675{
3676 char *kwlist[] = {"store_name", NULL};
3677 char *store_name;
3678 HCERTSTORE hStore = NULL;
3679 PCCRL_CONTEXT pCrlCtx = NULL;
3680 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3681 PyObject *result = NULL;
3682
3683 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3684 kwlist, &store_name)) {
3685 return NULL;
3686 }
3687 result = PyList_New(0);
3688 if (result == NULL) {
3689 return NULL;
3690 }
3691 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3692 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003693 Py_DECREF(result);
3694 return PyErr_SetFromWindowsErr(GetLastError());
3695 }
Christian Heimes44109d72013-11-22 01:51:30 +01003696
3697 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3698 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3699 pCrlCtx->cbCrlEncoded);
3700 if (!crl) {
3701 Py_CLEAR(result);
3702 break;
3703 }
3704 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3705 Py_CLEAR(result);
3706 break;
3707 }
3708 if ((tup = PyTuple_New(2)) == NULL) {
3709 Py_CLEAR(result);
3710 break;
3711 }
3712 PyTuple_SET_ITEM(tup, 0, crl);
3713 crl = NULL;
3714 PyTuple_SET_ITEM(tup, 1, enc);
3715 enc = NULL;
3716
3717 if (PyList_Append(result, tup) < 0) {
3718 Py_CLEAR(result);
3719 break;
3720 }
3721 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003722 }
Christian Heimes44109d72013-11-22 01:51:30 +01003723 if (pCrlCtx) {
3724 /* loop ended with an error, need to clean up context manually */
3725 CertFreeCRLContext(pCrlCtx);
3726 }
3727
3728 /* In error cases cert, enc and tup may not be NULL */
3729 Py_XDECREF(crl);
3730 Py_XDECREF(enc);
3731 Py_XDECREF(tup);
3732
3733 if (!CertCloseStore(hStore, 0)) {
3734 /* This error case might shadow another exception.*/
3735 Py_XDECREF(result);
3736 return PyErr_SetFromWindowsErr(GetLastError());
3737 }
3738 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003739}
Christian Heimes44109d72013-11-22 01:51:30 +01003740
3741#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003742
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003743/* List of functions exported by this module. */
3744
3745static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003746 {"_test_decode_cert", PySSL_test_decode_certificate,
3747 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003748#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003749 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3750 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003751 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3752 PySSL_RAND_bytes_doc},
3753 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3754 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003755 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003756 PySSL_RAND_egd_doc},
3757 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3758 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003759#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003760 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003761 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003762#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003763 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3764 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3765 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3766 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003767#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003768 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3769 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3770 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3771 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003772 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003773};
3774
3775
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003776#ifdef WITH_THREAD
3777
3778/* an implementation of OpenSSL threading operations in terms
3779 of the Python C thread library */
3780
3781static PyThread_type_lock *_ssl_locks = NULL;
3782
Christian Heimes4d98ca92013-08-19 17:36:29 +02003783#if OPENSSL_VERSION_NUMBER >= 0x10000000
3784/* use new CRYPTO_THREADID API. */
3785static void
3786_ssl_threadid_callback(CRYPTO_THREADID *id)
3787{
3788 CRYPTO_THREADID_set_numeric(id,
3789 (unsigned long)PyThread_get_thread_ident());
3790}
3791#else
3792/* deprecated CRYPTO_set_id_callback() API. */
3793static unsigned long
3794_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003795 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003796}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003797#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003798
Bill Janssen6e027db2007-11-15 22:23:56 +00003799static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003800 (int mode, int n, const char *file, int line) {
3801 /* this function is needed to perform locking on shared data
3802 structures. (Note that OpenSSL uses a number of global data
3803 structures that will be implicitly shared whenever multiple
3804 threads use OpenSSL.) Multi-threaded applications will
3805 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003807 locking_function() must be able to handle up to
3808 CRYPTO_num_locks() different mutex locks. It sets the n-th
3809 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003811 file and line are the file number of the function setting the
3812 lock. They can be useful for debugging.
3813 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003815 if ((_ssl_locks == NULL) ||
3816 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3817 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003819 if (mode & CRYPTO_LOCK) {
3820 PyThread_acquire_lock(_ssl_locks[n], 1);
3821 } else {
3822 PyThread_release_lock(_ssl_locks[n]);
3823 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003824}
3825
3826static int _setup_ssl_threads(void) {
3827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003828 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003830 if (_ssl_locks == NULL) {
3831 _ssl_locks_count = CRYPTO_num_locks();
3832 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003833 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003834 if (_ssl_locks == NULL)
3835 return 0;
3836 memset(_ssl_locks, 0,
3837 sizeof(PyThread_type_lock) * _ssl_locks_count);
3838 for (i = 0; i < _ssl_locks_count; i++) {
3839 _ssl_locks[i] = PyThread_allocate_lock();
3840 if (_ssl_locks[i] == NULL) {
3841 unsigned int j;
3842 for (j = 0; j < i; j++) {
3843 PyThread_free_lock(_ssl_locks[j]);
3844 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003845 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003846 return 0;
3847 }
3848 }
3849 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003850#if OPENSSL_VERSION_NUMBER >= 0x10000000
3851 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3852#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003853 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003854#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003855 }
3856 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003857}
3858
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003859#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003861PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003862"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003863for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003864
Martin v. Löwis1a214512008-06-11 05:26:20 +00003865
3866static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003867 PyModuleDef_HEAD_INIT,
3868 "_ssl",
3869 module_doc,
3870 -1,
3871 PySSL_methods,
3872 NULL,
3873 NULL,
3874 NULL,
3875 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003876};
3877
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003878
3879static void
3880parse_openssl_version(unsigned long libver,
3881 unsigned int *major, unsigned int *minor,
3882 unsigned int *fix, unsigned int *patch,
3883 unsigned int *status)
3884{
3885 *status = libver & 0xF;
3886 libver >>= 4;
3887 *patch = libver & 0xFF;
3888 libver >>= 8;
3889 *fix = libver & 0xFF;
3890 libver >>= 8;
3891 *minor = libver & 0xFF;
3892 libver >>= 8;
3893 *major = libver & 0xFF;
3894}
3895
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003896PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003897PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003898{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003899 PyObject *m, *d, *r;
3900 unsigned long libver;
3901 unsigned int major, minor, fix, patch, status;
3902 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003903 struct py_ssl_error_code *errcode;
3904 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003905
Antoine Pitrou152efa22010-05-16 18:19:27 +00003906 if (PyType_Ready(&PySSLContext_Type) < 0)
3907 return NULL;
3908 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003909 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003911 m = PyModule_Create(&_sslmodule);
3912 if (m == NULL)
3913 return NULL;
3914 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003916 /* Load _socket module and its C API */
3917 socket_api = PySocketModule_ImportModuleAndAPI();
3918 if (!socket_api)
3919 return NULL;
3920 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003922 /* Init OpenSSL */
3923 SSL_load_error_strings();
3924 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003926 /* note that this will start threading if not already started */
3927 if (!_setup_ssl_threads()) {
3928 return NULL;
3929 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003931 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003933 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003934 sslerror_type_slots[0].pfunc = PyExc_OSError;
3935 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003936 if (PySSLErrorObject == NULL)
3937 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003938
Antoine Pitrou41032a62011-10-27 23:56:55 +02003939 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3940 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3941 PySSLErrorObject, NULL);
3942 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3943 "ssl.SSLWantReadError", SSLWantReadError_doc,
3944 PySSLErrorObject, NULL);
3945 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3946 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3947 PySSLErrorObject, NULL);
3948 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3949 "ssl.SSLSyscallError", SSLSyscallError_doc,
3950 PySSLErrorObject, NULL);
3951 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3952 "ssl.SSLEOFError", SSLEOFError_doc,
3953 PySSLErrorObject, NULL);
3954 if (PySSLZeroReturnErrorObject == NULL
3955 || PySSLWantReadErrorObject == NULL
3956 || PySSLWantWriteErrorObject == NULL
3957 || PySSLSyscallErrorObject == NULL
3958 || PySSLEOFErrorObject == NULL)
3959 return NULL;
3960 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3961 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3962 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3963 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3964 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3965 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003966 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003967 if (PyDict_SetItemString(d, "_SSLContext",
3968 (PyObject *)&PySSLContext_Type) != 0)
3969 return NULL;
3970 if (PyDict_SetItemString(d, "_SSLSocket",
3971 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003972 return NULL;
3973 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3974 PY_SSL_ERROR_ZERO_RETURN);
3975 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3976 PY_SSL_ERROR_WANT_READ);
3977 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3978 PY_SSL_ERROR_WANT_WRITE);
3979 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3980 PY_SSL_ERROR_WANT_X509_LOOKUP);
3981 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3982 PY_SSL_ERROR_SYSCALL);
3983 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3984 PY_SSL_ERROR_SSL);
3985 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3986 PY_SSL_ERROR_WANT_CONNECT);
3987 /* non ssl.h errorcodes */
3988 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3989 PY_SSL_ERROR_EOF);
3990 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3991 PY_SSL_ERROR_INVALID_ERROR_CODE);
3992 /* cert requirements */
3993 PyModule_AddIntConstant(m, "CERT_NONE",
3994 PY_SSL_CERT_NONE);
3995 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3996 PY_SSL_CERT_OPTIONAL);
3997 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3998 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01003999 /* CRL verification for verification_flags */
4000 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4001 0);
4002 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4003 X509_V_FLAG_CRL_CHECK);
4004 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4005 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4006 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4007 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004008
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004009 /* Alert Descriptions from ssl.h */
4010 /* note RESERVED constants no longer intended for use have been removed */
4011 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4012
4013#define ADD_AD_CONSTANT(s) \
4014 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4015 SSL_AD_##s)
4016
4017 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4018 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4019 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4020 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4021 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4022 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4023 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4024 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4025 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4026 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4027 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4028 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4029 ADD_AD_CONSTANT(UNKNOWN_CA);
4030 ADD_AD_CONSTANT(ACCESS_DENIED);
4031 ADD_AD_CONSTANT(DECODE_ERROR);
4032 ADD_AD_CONSTANT(DECRYPT_ERROR);
4033 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4034 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4035 ADD_AD_CONSTANT(INTERNAL_ERROR);
4036 ADD_AD_CONSTANT(USER_CANCELLED);
4037 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004038 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004039#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4040 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4041#endif
4042#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4043 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4044#endif
4045#ifdef SSL_AD_UNRECOGNIZED_NAME
4046 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4047#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004048#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4049 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4050#endif
4051#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4052 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4053#endif
4054#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4055 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4056#endif
4057
4058#undef ADD_AD_CONSTANT
4059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004060 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004061#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004062 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4063 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004064#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004065 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4066 PY_SSL_VERSION_SSL3);
4067 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4068 PY_SSL_VERSION_SSL23);
4069 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4070 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004071#if HAVE_TLSv1_2
4072 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4073 PY_SSL_VERSION_TLS1_1);
4074 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4075 PY_SSL_VERSION_TLS1_2);
4076#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004077
Antoine Pitroub5218772010-05-21 09:56:06 +00004078 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004079 PyModule_AddIntConstant(m, "OP_ALL",
4080 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004081 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4082 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4083 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004084#if HAVE_TLSv1_2
4085 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4086 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4087#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004088 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4089 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004090 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004091#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004092 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004093#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004094#ifdef SSL_OP_NO_COMPRESSION
4095 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4096 SSL_OP_NO_COMPRESSION);
4097#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004098
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004099#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004100 r = Py_True;
4101#else
4102 r = Py_False;
4103#endif
4104 Py_INCREF(r);
4105 PyModule_AddObject(m, "HAS_SNI", r);
4106
Antoine Pitroud6494802011-07-21 01:11:30 +02004107#if HAVE_OPENSSL_FINISHED
4108 r = Py_True;
4109#else
4110 r = Py_False;
4111#endif
4112 Py_INCREF(r);
4113 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4114
Antoine Pitrou501da612011-12-21 09:27:41 +01004115#ifdef OPENSSL_NO_ECDH
4116 r = Py_False;
4117#else
4118 r = Py_True;
4119#endif
4120 Py_INCREF(r);
4121 PyModule_AddObject(m, "HAS_ECDH", r);
4122
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004123#ifdef OPENSSL_NPN_NEGOTIATED
4124 r = Py_True;
4125#else
4126 r = Py_False;
4127#endif
4128 Py_INCREF(r);
4129 PyModule_AddObject(m, "HAS_NPN", r);
4130
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004131 /* Mappings for error codes */
4132 err_codes_to_names = PyDict_New();
4133 err_names_to_codes = PyDict_New();
4134 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4135 return NULL;
4136 errcode = error_codes;
4137 while (errcode->mnemonic != NULL) {
4138 PyObject *mnemo, *key;
4139 mnemo = PyUnicode_FromString(errcode->mnemonic);
4140 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4141 if (mnemo == NULL || key == NULL)
4142 return NULL;
4143 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4144 return NULL;
4145 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4146 return NULL;
4147 Py_DECREF(key);
4148 Py_DECREF(mnemo);
4149 errcode++;
4150 }
4151 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4152 return NULL;
4153 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4154 return NULL;
4155
4156 lib_codes_to_names = PyDict_New();
4157 if (lib_codes_to_names == NULL)
4158 return NULL;
4159 libcode = library_codes;
4160 while (libcode->library != NULL) {
4161 PyObject *mnemo, *key;
4162 key = PyLong_FromLong(libcode->code);
4163 mnemo = PyUnicode_FromString(libcode->library);
4164 if (key == NULL || mnemo == NULL)
4165 return NULL;
4166 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4167 return NULL;
4168 Py_DECREF(key);
4169 Py_DECREF(mnemo);
4170 libcode++;
4171 }
4172 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4173 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004175 /* OpenSSL version */
4176 /* SSLeay() gives us the version of the library linked against,
4177 which could be different from the headers version.
4178 */
4179 libver = SSLeay();
4180 r = PyLong_FromUnsignedLong(libver);
4181 if (r == NULL)
4182 return NULL;
4183 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4184 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004185 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004186 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4187 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4188 return NULL;
4189 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4190 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4191 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004192
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004193 libver = OPENSSL_VERSION_NUMBER;
4194 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4195 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4196 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4197 return NULL;
4198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004199 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004200}