blob: a92710077cc2831d7ad84dc9b735367f23b5f4e0 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +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
Benjamin Petersondaeb9252014-08-20 14:14:50 -050017#define PY_SSIZE_T_CLEAN
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000018#include "Python.h"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000019
Bill Janssen98d19da2007-09-10 21:51:02 +000020#ifdef WITH_THREAD
21#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020022
Christian Heimes0d604cf2013-08-21 13:26:05 +020023
Benjamin Petersondaeb9252014-08-20 14:14:50 -050024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Bill Janssen98d19da2007-09-10 21:51:02 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000029 PyThreadState *_save = NULL; \
Benjamin Petersondaeb9252014-08-20 14:14:50 -050030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Bill Janssen98d19da2007-09-10 21:51:02 +000034
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000035#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000036
Benjamin Petersondaeb9252014-08-20 14:14:50 -050037#define PySSL_BEGIN_ALLOW_THREADS_S(save)
38#define PySSL_END_ALLOW_THREADS_S(save)
Bill Janssen98d19da2007-09-10 21:51:02 +000039#define PySSL_BEGIN_ALLOW_THREADS
40#define PySSL_BLOCK_THREADS
41#define PySSL_UNBLOCK_THREADS
42#define PySSL_END_ALLOW_THREADS
43
44#endif
45
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000046/* Include symbols from _socket module */
47#include "socketmodule.h"
48
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000049#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000050#include <poll.h>
51#elif defined(HAVE_SYS_POLL_H)
52#include <sys/poll.h>
53#endif
54
Christian Heimesc2fc7c42016-09-05 23:37:13 +020055/* Don't warn about deprecated functions */
56#ifdef __GNUC__
57#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
58#endif
59#ifdef __clang__
60#pragma clang diagnostic ignored "-Wdeprecated-declarations"
61#endif
62
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000063/* Include OpenSSL header files */
64#include "openssl/rsa.h"
65#include "openssl/crypto.h"
66#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000067#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000068#include "openssl/pem.h"
69#include "openssl/ssl.h"
70#include "openssl/err.h"
71#include "openssl/rand.h"
72
73/* SSL error object */
74static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050075static PyObject *PySSLZeroReturnErrorObject;
76static PyObject *PySSLWantReadErrorObject;
77static PyObject *PySSLWantWriteErrorObject;
78static PyObject *PySSLSyscallErrorObject;
79static PyObject *PySSLEOFErrorObject;
80
81/* Error mappings */
82static PyObject *err_codes_to_names;
83static PyObject *err_names_to_codes;
84static PyObject *lib_codes_to_names;
85
86struct py_ssl_error_code {
87 const char *mnemonic;
88 int library, reason;
89};
90struct py_ssl_library_code {
91 const char *library;
92 int code;
93};
94
95/* Include generated data (error codes) */
96#include "_ssl_data.h"
97
Christian Heimesc2fc7c42016-09-05 23:37:13 +020098#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
99# define OPENSSL_VERSION_1_1 1
100#endif
101
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500102/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
103 http://www.openssl.org/news/changelog.html
104 */
105#if OPENSSL_VERSION_NUMBER >= 0x10001000L
106# define HAVE_TLSv1_2 1
107#else
108# define HAVE_TLSv1_2 0
109#endif
110
111/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
112 * This includes the SSL_set_SSL_CTX() function.
113 */
114#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
115# define HAVE_SNI 1
116#else
117# define HAVE_SNI 0
118#endif
119
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500120/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500121#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500122# define HAVE_ALPN
123#endif
124
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200125#ifndef INVALID_SOCKET /* MS defines this */
126#define INVALID_SOCKET (-1)
127#endif
128
129#ifdef OPENSSL_VERSION_1_1
130/* OpenSSL 1.1.0+ */
131#ifndef OPENSSL_NO_SSL2
132#define OPENSSL_NO_SSL2
133#endif
134#else /* OpenSSL < 1.1.0 */
135#if defined(WITH_THREAD)
136#define HAVE_OPENSSL_CRYPTO_LOCK
137#endif
138
139#define TLS_method SSLv23_method
140
141static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
142{
143 return ne->set;
144}
145
146#ifndef OPENSSL_NO_COMP
147static int COMP_get_type(const COMP_METHOD *meth)
148{
149 return meth->type;
150}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200151#endif
152
153static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
154{
155 return ctx->default_passwd_callback;
156}
157
158static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
159{
160 return ctx->default_passwd_callback_userdata;
161}
162
163static int X509_OBJECT_get_type(X509_OBJECT *x)
164{
165 return x->type;
166}
167
168static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
169{
170 return x->data.x509;
171}
172
173static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
174 return store->objs;
175}
176
177static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
178{
179 return store->param;
180}
181#endif /* OpenSSL < 1.1.0 or LibreSSL */
182
183
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500184enum py_ssl_error {
185 /* these mirror ssl.h */
186 PY_SSL_ERROR_NONE,
187 PY_SSL_ERROR_SSL,
188 PY_SSL_ERROR_WANT_READ,
189 PY_SSL_ERROR_WANT_WRITE,
190 PY_SSL_ERROR_WANT_X509_LOOKUP,
191 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
192 PY_SSL_ERROR_ZERO_RETURN,
193 PY_SSL_ERROR_WANT_CONNECT,
194 /* start of non ssl.h errorcodes */
195 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
196 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
197 PY_SSL_ERROR_INVALID_ERROR_CODE
198};
199
200enum py_ssl_server_or_client {
201 PY_SSL_CLIENT,
202 PY_SSL_SERVER
203};
204
205enum py_ssl_cert_requirements {
206 PY_SSL_CERT_NONE,
207 PY_SSL_CERT_OPTIONAL,
208 PY_SSL_CERT_REQUIRED
209};
210
211enum py_ssl_version {
212 PY_SSL_VERSION_SSL2,
213 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200214 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500215#if HAVE_TLSv1_2
216 PY_SSL_VERSION_TLS1,
217 PY_SSL_VERSION_TLS1_1,
218 PY_SSL_VERSION_TLS1_2
219#else
220 PY_SSL_VERSION_TLS1
221#endif
222};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000223
Bill Janssen98d19da2007-09-10 21:51:02 +0000224#ifdef WITH_THREAD
225
226/* serves as a flag to see whether we've initialized the SSL thread support. */
227/* 0 means no, greater than 0 means yes */
228
229static unsigned int _ssl_locks_count = 0;
230
231#endif /* def WITH_THREAD */
232
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000233/* SSL socket object */
234
235#define X509_NAME_MAXLEN 256
236
237/* RAND_* APIs got added to OpenSSL in 0.9.5 */
238#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
239# define HAVE_OPENSSL_RAND 1
240#else
241# undef HAVE_OPENSSL_RAND
242#endif
243
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500244/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
245 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
246 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
247#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
248# define HAVE_SSL_CTX_CLEAR_OPTIONS
249#else
250# undef HAVE_SSL_CTX_CLEAR_OPTIONS
251#endif
252
253/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
254 * older SSL, but let's be safe */
255#define PySSL_CB_MAXLEN 128
256
257/* SSL_get_finished got added to OpenSSL in 0.9.5 */
258#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
259# define HAVE_OPENSSL_FINISHED 1
260#else
261# define HAVE_OPENSSL_FINISHED 0
262#endif
263
264/* ECDH support got added to OpenSSL in 0.9.8 */
265#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
266# define OPENSSL_NO_ECDH
267#endif
268
269/* compression support got added to OpenSSL in 0.9.8 */
270#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
271# define OPENSSL_NO_COMP
272#endif
273
274/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
275#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
276# define HAVE_OPENSSL_VERIFY_PARAM
277#endif
278
279
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000281 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500282 SSL_CTX *ctx;
283#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500284 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500285 int npn_protocols_len;
286#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500287#ifdef HAVE_ALPN
288 unsigned char *alpn_protocols;
289 int alpn_protocols_len;
290#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500291#ifndef OPENSSL_NO_TLSEXT
292 PyObject *set_hostname;
293#endif
294 int check_hostname;
295} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500297typedef struct {
298 PyObject_HEAD
299 PySocketSockObject *Socket;
300 PyObject *ssl_sock;
301 SSL *ssl;
302 PySSLContext *ctx; /* weakref to SSL context */
303 X509 *peer_cert;
304 char shutdown_seen_zero;
305 char handshake_done;
306 enum py_ssl_server_or_client socket_type;
307} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000308
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500309static PyTypeObject PySSLContext_Type;
310static PyTypeObject PySSLSocket_Type;
311
312static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
313static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000314static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000315 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500316static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
317static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000318
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500319#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
320#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000321
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000322typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000323 SOCKET_IS_NONBLOCKING,
324 SOCKET_IS_BLOCKING,
325 SOCKET_HAS_TIMED_OUT,
326 SOCKET_HAS_BEEN_CLOSED,
327 SOCKET_TOO_LARGE_FOR_SELECT,
328 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000329} timeout_state;
330
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000331/* Wrap error strings with filename and line # */
332#define STRINGIFY1(x) #x
333#define STRINGIFY2(x) STRINGIFY1(x)
334#define ERRSTR1(x,y,z) (x ":" y ": " z)
335#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
336
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500337
338/*
339 * SSL errors.
340 */
341
342PyDoc_STRVAR(SSLError_doc,
343"An error occurred in the SSL implementation.");
344
345PyDoc_STRVAR(SSLZeroReturnError_doc,
346"SSL/TLS session closed cleanly.");
347
348PyDoc_STRVAR(SSLWantReadError_doc,
349"Non-blocking SSL socket needs to read more data\n"
350"before the requested operation can be completed.");
351
352PyDoc_STRVAR(SSLWantWriteError_doc,
353"Non-blocking SSL socket needs to write more data\n"
354"before the requested operation can be completed.");
355
356PyDoc_STRVAR(SSLSyscallError_doc,
357"System error when attempting SSL operation.");
358
359PyDoc_STRVAR(SSLEOFError_doc,
360"SSL/TLS connection terminated abruptly.");
361
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362
363static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500364SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500366 if (self->strerror != NULL) {
367 Py_INCREF(self->strerror);
368 return self->strerror;
369 }
370 else
371 return PyObject_Str(self->args);
372}
373
374static void
375fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
376 int lineno, unsigned long errcode)
377{
378 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
379 PyObject *init_value, *msg, *key;
380
381 if (errcode != 0) {
382 int lib, reason;
383
384 lib = ERR_GET_LIB(errcode);
385 reason = ERR_GET_REASON(errcode);
386 key = Py_BuildValue("ii", lib, reason);
387 if (key == NULL)
388 goto fail;
389 reason_obj = PyDict_GetItem(err_codes_to_names, key);
390 Py_DECREF(key);
391 if (reason_obj == NULL) {
392 /* XXX if reason < 100, it might reflect a library number (!!) */
393 PyErr_Clear();
394 }
395 key = PyLong_FromLong(lib);
396 if (key == NULL)
397 goto fail;
398 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
399 Py_DECREF(key);
400 if (lib_obj == NULL) {
401 PyErr_Clear();
402 }
403 if (errstr == NULL)
404 errstr = ERR_reason_error_string(errcode);
405 }
406 if (errstr == NULL)
407 errstr = "unknown error";
408
409 if (reason_obj && lib_obj)
410 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
411 lib_obj, reason_obj, errstr, lineno);
412 else if (lib_obj)
413 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
414 lib_obj, errstr, lineno);
415 else
416 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
417 if (msg == NULL)
418 goto fail;
419
420 init_value = Py_BuildValue("iN", ssl_errno, msg);
421 if (init_value == NULL)
422 goto fail;
423
424 err_value = PyObject_CallObject(type, init_value);
425 Py_DECREF(init_value);
426 if (err_value == NULL)
427 goto fail;
428
429 if (reason_obj == NULL)
430 reason_obj = Py_None;
431 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
432 goto fail;
433 if (lib_obj == NULL)
434 lib_obj = Py_None;
435 if (PyObject_SetAttrString(err_value, "library", lib_obj))
436 goto fail;
437 PyErr_SetObject(type, err_value);
438fail:
439 Py_XDECREF(err_value);
440}
441
442static PyObject *
443PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
444{
445 PyObject *type = PySSLErrorObject;
446 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000447 int err;
448 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500449 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000450
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000451 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500452 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000453
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000454 if (obj->ssl != NULL) {
455 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000456
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000457 switch (err) {
458 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500459 errstr = "TLS/SSL connection has been closed (EOF)";
460 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000461 p = PY_SSL_ERROR_ZERO_RETURN;
462 break;
463 case SSL_ERROR_WANT_READ:
464 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500465 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000466 p = PY_SSL_ERROR_WANT_READ;
467 break;
468 case SSL_ERROR_WANT_WRITE:
469 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500470 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000471 errstr = "The operation did not complete (write)";
472 break;
473 case SSL_ERROR_WANT_X509_LOOKUP:
474 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000475 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000476 break;
477 case SSL_ERROR_WANT_CONNECT:
478 p = PY_SSL_ERROR_WANT_CONNECT;
479 errstr = "The operation did not complete (connect)";
480 break;
481 case SSL_ERROR_SYSCALL:
482 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000483 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500484 PySocketSockObject *s = obj->Socket;
485 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000486 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500487 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000488 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000489 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000490 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500491 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000492 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500493 s->errorhandler();
494 Py_DECREF(s);
495 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000496 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000497 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500498 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000499 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000500 }
501 } else {
502 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000503 }
504 break;
505 }
506 case SSL_ERROR_SSL:
507 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000508 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500509 if (e == 0)
510 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000511 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000512 break;
513 }
514 default:
515 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
516 errstr = "Invalid error code";
517 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000518 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500519 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000520 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000521 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000522}
523
Bill Janssen98d19da2007-09-10 21:51:02 +0000524static PyObject *
525_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
526
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500527 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000528 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500529 else
530 errcode = 0;
531 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000532 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000533 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000534}
535
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500536/*
537 * SSL objects
538 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000539
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500540static PySSLSocket *
541newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
542 enum py_ssl_server_or_client socket_type,
543 char *server_hostname, PyObject *ssl_sock)
544{
545 PySSLSocket *self;
546 SSL_CTX *ctx = sslctx->ctx;
547 long mode;
548
549 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000550 if (self == NULL)
551 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000553 self->peer_cert = NULL;
554 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000555 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500556 self->ssl_sock = NULL;
557 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200558 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500559 self->handshake_done = 0;
560 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000561
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000562 /* Make sure the SSL error state is initialized */
563 (void) ERR_get_state();
564 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000565
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000566 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500567 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000568 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500569 SSL_set_app_data(self->ssl,self);
570 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
571 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000572#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500573 mode |= SSL_MODE_AUTO_RETRY;
574#endif
575 SSL_set_mode(self->ssl, mode);
576
577#if HAVE_SNI
578 if (server_hostname != NULL)
579 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000580#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000581
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000582 /* If the socket is in non-blocking mode or timeout mode, set the BIO
583 * to non-blocking mode (blocking is the default)
584 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500585 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000586 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
587 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
588 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000589
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000590 PySSL_BEGIN_ALLOW_THREADS
591 if (socket_type == PY_SSL_CLIENT)
592 SSL_set_connect_state(self->ssl);
593 else
594 SSL_set_accept_state(self->ssl);
595 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000596
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500597 self->socket_type = socket_type;
598 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400600 if (ssl_sock != Py_None) {
601 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
602 if (self->ssl_sock == NULL) {
603 Py_DECREF(self);
604 return NULL;
605 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500606 }
607 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000608}
609
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000610
611/* SSL object methods */
612
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500613static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000614{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000615 int ret;
616 int err;
617 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500618 PySocketSockObject *sock = self->Socket;
619
620 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000621
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000622 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500623 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000624 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
625 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000626
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000627 /* Actually negotiate SSL connection */
628 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
629 do {
630 PySSL_BEGIN_ALLOW_THREADS
631 ret = SSL_do_handshake(self->ssl);
632 err = SSL_get_error(self->ssl, ret);
633 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500634 if (PyErr_CheckSignals())
635 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000636 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500637 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000638 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500639 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000640 } else {
641 sockstate = SOCKET_OPERATION_OK;
642 }
643 if (sockstate == SOCKET_HAS_TIMED_OUT) {
644 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000645 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500646 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000647 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
648 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000649 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500650 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000651 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
652 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000653 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500654 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000655 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
656 break;
657 }
658 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500659 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000660 if (ret < 1)
661 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000662
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000663 if (self->peer_cert)
664 X509_free (self->peer_cert);
665 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500666 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000667 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500668 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000669
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000670 Py_INCREF(Py_None);
671 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000672
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500673error:
674 Py_DECREF(sock);
675 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000676}
677
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000678static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000679_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000680
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000681 char namebuf[X509_NAME_MAXLEN];
682 int buflen;
683 PyObject *name_obj;
684 PyObject *value_obj;
685 PyObject *attr;
686 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000687
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000688 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
689 if (buflen < 0) {
690 _setSSLError(NULL, 0, __FILE__, __LINE__);
691 goto fail;
692 }
693 name_obj = PyString_FromStringAndSize(namebuf, buflen);
694 if (name_obj == NULL)
695 goto fail;
696
697 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
698 if (buflen < 0) {
699 _setSSLError(NULL, 0, __FILE__, __LINE__);
700 Py_DECREF(name_obj);
701 goto fail;
702 }
703 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000704 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 OPENSSL_free(valuebuf);
706 if (value_obj == NULL) {
707 Py_DECREF(name_obj);
708 goto fail;
709 }
710 attr = PyTuple_New(2);
711 if (attr == NULL) {
712 Py_DECREF(name_obj);
713 Py_DECREF(value_obj);
714 goto fail;
715 }
716 PyTuple_SET_ITEM(attr, 0, name_obj);
717 PyTuple_SET_ITEM(attr, 1, value_obj);
718 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000719
Bill Janssen98d19da2007-09-10 21:51:02 +0000720 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000721 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000722}
723
724static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000725_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000726{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000727 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
728 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
729 PyObject *rdnt;
730 PyObject *attr = NULL; /* tuple to hold an attribute */
731 int entry_count = X509_NAME_entry_count(xname);
732 X509_NAME_ENTRY *entry;
733 ASN1_OBJECT *name;
734 ASN1_STRING *value;
735 int index_counter;
736 int rdn_level = -1;
737 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000738
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000739 dn = PyList_New(0);
740 if (dn == NULL)
741 return NULL;
742 /* now create another tuple to hold the top-level RDN */
743 rdn = PyList_New(0);
744 if (rdn == NULL)
745 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000746
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000747 for (index_counter = 0;
748 index_counter < entry_count;
749 index_counter++)
750 {
751 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000752
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000753 /* check to see if we've gotten to a new RDN */
754 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200755 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000756 /* yes, new RDN */
757 /* add old RDN to DN */
758 rdnt = PyList_AsTuple(rdn);
759 Py_DECREF(rdn);
760 if (rdnt == NULL)
761 goto fail0;
762 retcode = PyList_Append(dn, rdnt);
763 Py_DECREF(rdnt);
764 if (retcode < 0)
765 goto fail0;
766 /* create new RDN */
767 rdn = PyList_New(0);
768 if (rdn == NULL)
769 goto fail0;
770 }
771 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200772 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000773
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000774 /* now add this attribute to the current RDN */
775 name = X509_NAME_ENTRY_get_object(entry);
776 value = X509_NAME_ENTRY_get_data(entry);
777 attr = _create_tuple_for_attribute(name, value);
778 /*
779 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
780 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500781 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
782 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000783 */
784 if (attr == NULL)
785 goto fail1;
786 retcode = PyList_Append(rdn, attr);
787 Py_DECREF(attr);
788 if (retcode < 0)
789 goto fail1;
790 }
791 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100792 if (rdn != NULL) {
793 if (PyList_GET_SIZE(rdn) > 0) {
794 rdnt = PyList_AsTuple(rdn);
795 Py_DECREF(rdn);
796 if (rdnt == NULL)
797 goto fail0;
798 retcode = PyList_Append(dn, rdnt);
799 Py_DECREF(rdnt);
800 if (retcode < 0)
801 goto fail0;
802 }
803 else {
804 Py_DECREF(rdn);
805 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000806 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000807
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000808 /* convert list to tuple */
809 rdnt = PyList_AsTuple(dn);
810 Py_DECREF(dn);
811 if (rdnt == NULL)
812 return NULL;
813 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000814
815 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000816 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000817
818 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000819 Py_XDECREF(dn);
820 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821}
822
823static PyObject *
824_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000825
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000826 /* this code follows the procedure outlined in
827 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
828 function to extract the STACK_OF(GENERAL_NAME),
829 then iterates through the stack to add the
830 names. */
831
832 int i, j;
833 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200834 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000835 X509_EXTENSION *ext = NULL;
836 GENERAL_NAMES *names = NULL;
837 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000838 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000839 BIO *biobuf = NULL;
840 char buf[2048];
841 char *vptr;
842 int len;
843 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000844#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000845 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000846#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000847 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000848#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000849
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000850 if (certificate == NULL)
851 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000852
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000853 /* get a memory buffer */
854 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000855
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200856 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000857 while ((i = X509_get_ext_by_NID(
858 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000859
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000860 if (peer_alt_names == Py_None) {
861 peer_alt_names = PyList_New(0);
862 if (peer_alt_names == NULL)
863 goto fail;
864 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000865
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000866 /* now decode the altName */
867 ext = X509_get_ext(certificate, i);
868 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500869 PyErr_SetString
870 (PySSLErrorObject,
871 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000872 goto fail;
873 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000874
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200875 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000876 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500877 names = (GENERAL_NAMES*)
878 (ASN1_item_d2i(NULL,
879 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200880 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500881 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000882 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500883 names = (GENERAL_NAMES*)
884 (method->d2i(NULL,
885 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200886 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000887
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000888 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000889 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200890 int gntype;
891 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000893 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200894 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200895 switch (gntype) {
896 case GEN_DIRNAME:
897 /* we special-case DirName as a tuple of
898 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000899
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000900 t = PyTuple_New(2);
901 if (t == NULL) {
902 goto fail;
903 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000904
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000905 v = PyString_FromString("DirName");
906 if (v == NULL) {
907 Py_DECREF(t);
908 goto fail;
909 }
910 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000911
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000912 v = _create_tuple_for_X509_NAME (name->d.dirn);
913 if (v == NULL) {
914 Py_DECREF(t);
915 goto fail;
916 }
917 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200918 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000919
Christian Heimes88b174c2013-08-17 00:54:47 +0200920 case GEN_EMAIL:
921 case GEN_DNS:
922 case GEN_URI:
923 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
924 correctly, CVE-2013-4238 */
925 t = PyTuple_New(2);
926 if (t == NULL)
927 goto fail;
928 switch (gntype) {
929 case GEN_EMAIL:
930 v = PyString_FromString("email");
931 as = name->d.rfc822Name;
932 break;
933 case GEN_DNS:
934 v = PyString_FromString("DNS");
935 as = name->d.dNSName;
936 break;
937 case GEN_URI:
938 v = PyString_FromString("URI");
939 as = name->d.uniformResourceIdentifier;
940 break;
941 }
942 if (v == NULL) {
943 Py_DECREF(t);
944 goto fail;
945 }
946 PyTuple_SET_ITEM(t, 0, v);
947 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
948 ASN1_STRING_length(as));
949 if (v == NULL) {
950 Py_DECREF(t);
951 goto fail;
952 }
953 PyTuple_SET_ITEM(t, 1, v);
954 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000955
Christian Heimes6663eb62016-09-06 23:25:35 +0200956 case GEN_RID:
957 t = PyTuple_New(2);
958 if (t == NULL)
959 goto fail;
960
961 v = PyUnicode_FromString("Registered ID");
962 if (v == NULL) {
963 Py_DECREF(t);
964 goto fail;
965 }
966 PyTuple_SET_ITEM(t, 0, v);
967
968 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
969 if (len < 0) {
970 Py_DECREF(t);
971 _setSSLError(NULL, 0, __FILE__, __LINE__);
972 goto fail;
973 } else if (len >= (int)sizeof(buf)) {
974 v = PyUnicode_FromString("<INVALID>");
975 } else {
976 v = PyUnicode_FromStringAndSize(buf, len);
977 }
978 if (v == NULL) {
979 Py_DECREF(t);
980 goto fail;
981 }
982 PyTuple_SET_ITEM(t, 1, v);
983 break;
984
Christian Heimes88b174c2013-08-17 00:54:47 +0200985 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000986 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200987 switch (gntype) {
988 /* check for new general name type */
989 case GEN_OTHERNAME:
990 case GEN_X400:
991 case GEN_EDIPARTY:
992 case GEN_IPADD:
993 case GEN_RID:
994 break;
995 default:
996 if (PyErr_Warn(PyExc_RuntimeWarning,
997 "Unknown general name type") == -1) {
998 goto fail;
999 }
1000 break;
1001 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001002 (void) BIO_reset(biobuf);
1003 GENERAL_NAME_print(biobuf, name);
1004 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1005 if (len < 0) {
1006 _setSSLError(NULL, 0, __FILE__, __LINE__);
1007 goto fail;
1008 }
1009 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001010 if (vptr == NULL) {
1011 PyErr_Format(PyExc_ValueError,
1012 "Invalid value %.200s",
1013 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001014 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001015 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001016 t = PyTuple_New(2);
1017 if (t == NULL)
1018 goto fail;
1019 v = PyString_FromStringAndSize(buf, (vptr - buf));
1020 if (v == NULL) {
1021 Py_DECREF(t);
1022 goto fail;
1023 }
1024 PyTuple_SET_ITEM(t, 0, v);
1025 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1026 if (v == NULL) {
1027 Py_DECREF(t);
1028 goto fail;
1029 }
1030 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001031 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001032 }
1033
1034 /* and add that rendering to the list */
1035
1036 if (PyList_Append(peer_alt_names, t) < 0) {
1037 Py_DECREF(t);
1038 goto fail;
1039 }
1040 Py_DECREF(t);
1041 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001042 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001043 }
1044 BIO_free(biobuf);
1045 if (peer_alt_names != Py_None) {
1046 v = PyList_AsTuple(peer_alt_names);
1047 Py_DECREF(peer_alt_names);
1048 return v;
1049 } else {
1050 return peer_alt_names;
1051 }
1052
Bill Janssen98d19da2007-09-10 21:51:02 +00001053
1054 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001055 if (biobuf != NULL)
1056 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001057
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001058 if (peer_alt_names != Py_None) {
1059 Py_XDECREF(peer_alt_names);
1060 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001061
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001062 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001063}
1064
1065static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001066_get_aia_uri(X509 *certificate, int nid) {
1067 PyObject *lst = NULL, *ostr = NULL;
1068 int i, result;
1069 AUTHORITY_INFO_ACCESS *info;
1070
1071 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001072 if (info == NULL)
1073 return Py_None;
1074 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1075 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001076 return Py_None;
1077 }
1078
1079 if ((lst = PyList_New(0)) == NULL) {
1080 goto fail;
1081 }
1082
1083 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1084 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1085 ASN1_IA5STRING *uri;
1086
1087 if ((OBJ_obj2nid(ad->method) != nid) ||
1088 (ad->location->type != GEN_URI)) {
1089 continue;
1090 }
1091 uri = ad->location->d.uniformResourceIdentifier;
1092 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1093 uri->length);
1094 if (ostr == NULL) {
1095 goto fail;
1096 }
1097 result = PyList_Append(lst, ostr);
1098 Py_DECREF(ostr);
1099 if (result < 0) {
1100 goto fail;
1101 }
1102 }
1103 AUTHORITY_INFO_ACCESS_free(info);
1104
1105 /* convert to tuple or None */
1106 if (PyList_Size(lst) == 0) {
1107 Py_DECREF(lst);
1108 return Py_None;
1109 } else {
1110 PyObject *tup;
1111 tup = PyList_AsTuple(lst);
1112 Py_DECREF(lst);
1113 return tup;
1114 }
1115
1116 fail:
1117 AUTHORITY_INFO_ACCESS_free(info);
1118 Py_XDECREF(lst);
1119 return NULL;
1120}
1121
1122static PyObject *
1123_get_crl_dp(X509 *certificate) {
1124 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001125 int i, j;
1126 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001127
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001128#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001129 /* Calls x509v3_cache_extensions and sets up crldp */
1130 X509_check_ca(certificate);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001131#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001132 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001133
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001134 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001135 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001136
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001137 lst = PyList_New(0);
1138 if (lst == NULL)
1139 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001140
1141 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1142 DIST_POINT *dp;
1143 STACK_OF(GENERAL_NAME) *gns;
1144
1145 dp = sk_DIST_POINT_value(dps, i);
1146 gns = dp->distpoint->name.fullname;
1147
1148 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1149 GENERAL_NAME *gn;
1150 ASN1_IA5STRING *uri;
1151 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001152 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001153
1154 gn = sk_GENERAL_NAME_value(gns, j);
1155 if (gn->type != GEN_URI) {
1156 continue;
1157 }
1158 uri = gn->d.uniformResourceIdentifier;
1159 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1160 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001161 if (ouri == NULL)
1162 goto done;
1163
1164 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001165 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001166 if (err < 0)
1167 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001168 }
1169 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001170
1171 /* Convert to tuple. */
1172 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1173
1174 done:
1175 Py_XDECREF(lst);
1176#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersonb1c1e672015-11-14 00:09:22 -08001177 sk_DIST_POINT_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001178#endif
1179 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001180}
1181
1182static PyObject *
1183_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001184
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001185 PyObject *retval = NULL;
1186 BIO *biobuf = NULL;
1187 PyObject *peer;
1188 PyObject *peer_alt_names = NULL;
1189 PyObject *issuer;
1190 PyObject *version;
1191 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001192 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001193 ASN1_INTEGER *serialNumber;
1194 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001195 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001196 ASN1_TIME *notBefore, *notAfter;
1197 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001198
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001199 retval = PyDict_New();
1200 if (retval == NULL)
1201 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001202
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001203 peer = _create_tuple_for_X509_NAME(
1204 X509_get_subject_name(certificate));
1205 if (peer == NULL)
1206 goto fail0;
1207 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1208 Py_DECREF(peer);
1209 goto fail0;
1210 }
1211 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001212
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001213 issuer = _create_tuple_for_X509_NAME(
1214 X509_get_issuer_name(certificate));
1215 if (issuer == NULL)
1216 goto fail0;
1217 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001218 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001219 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001220 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001221 Py_DECREF(issuer);
1222
1223 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1224 if (version == NULL)
1225 goto fail0;
1226 if (PyDict_SetItemString(retval, "version", version) < 0) {
1227 Py_DECREF(version);
1228 goto fail0;
1229 }
1230 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001231
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001232 /* get a memory buffer */
1233 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001234
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001235 (void) BIO_reset(biobuf);
1236 serialNumber = X509_get_serialNumber(certificate);
1237 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1238 i2a_ASN1_INTEGER(biobuf, serialNumber);
1239 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1240 if (len < 0) {
1241 _setSSLError(NULL, 0, __FILE__, __LINE__);
1242 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001243 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001244 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1245 if (sn_obj == NULL)
1246 goto fail1;
1247 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1248 Py_DECREF(sn_obj);
1249 goto fail1;
1250 }
1251 Py_DECREF(sn_obj);
1252
1253 (void) BIO_reset(biobuf);
1254 notBefore = X509_get_notBefore(certificate);
1255 ASN1_TIME_print(biobuf, notBefore);
1256 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1257 if (len < 0) {
1258 _setSSLError(NULL, 0, __FILE__, __LINE__);
1259 goto fail1;
1260 }
1261 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1262 if (pnotBefore == NULL)
1263 goto fail1;
1264 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1265 Py_DECREF(pnotBefore);
1266 goto fail1;
1267 }
1268 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001269
1270 (void) BIO_reset(biobuf);
1271 notAfter = X509_get_notAfter(certificate);
1272 ASN1_TIME_print(biobuf, notAfter);
1273 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1274 if (len < 0) {
1275 _setSSLError(NULL, 0, __FILE__, __LINE__);
1276 goto fail1;
1277 }
1278 pnotAfter = PyString_FromStringAndSize(buf, len);
1279 if (pnotAfter == NULL)
1280 goto fail1;
1281 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1282 Py_DECREF(pnotAfter);
1283 goto fail1;
1284 }
1285 Py_DECREF(pnotAfter);
1286
1287 /* Now look for subjectAltName */
1288
1289 peer_alt_names = _get_peer_alt_names(certificate);
1290 if (peer_alt_names == NULL)
1291 goto fail1;
1292 else if (peer_alt_names != Py_None) {
1293 if (PyDict_SetItemString(retval, "subjectAltName",
1294 peer_alt_names) < 0) {
1295 Py_DECREF(peer_alt_names);
1296 goto fail1;
1297 }
1298 Py_DECREF(peer_alt_names);
1299 }
1300
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001301 /* Authority Information Access: OCSP URIs */
1302 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1303 if (obj == NULL) {
1304 goto fail1;
1305 } else if (obj != Py_None) {
1306 result = PyDict_SetItemString(retval, "OCSP", obj);
1307 Py_DECREF(obj);
1308 if (result < 0) {
1309 goto fail1;
1310 }
1311 }
1312
1313 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1314 if (obj == NULL) {
1315 goto fail1;
1316 } else if (obj != Py_None) {
1317 result = PyDict_SetItemString(retval, "caIssuers", obj);
1318 Py_DECREF(obj);
1319 if (result < 0) {
1320 goto fail1;
1321 }
1322 }
1323
1324 /* CDP (CRL distribution points) */
1325 obj = _get_crl_dp(certificate);
1326 if (obj == NULL) {
1327 goto fail1;
1328 } else if (obj != Py_None) {
1329 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1330 Py_DECREF(obj);
1331 if (result < 0) {
1332 goto fail1;
1333 }
1334 }
1335
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001336 BIO_free(biobuf);
1337 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001338
1339 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001340 if (biobuf != NULL)
1341 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001342 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001343 Py_XDECREF(retval);
1344 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001345}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001346
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001347static PyObject *
1348_certificate_to_der(X509 *certificate)
1349{
1350 unsigned char *bytes_buf = NULL;
1351 int len;
1352 PyObject *retval;
1353
1354 bytes_buf = NULL;
1355 len = i2d_X509(certificate, &bytes_buf);
1356 if (len < 0) {
1357 _setSSLError(NULL, 0, __FILE__, __LINE__);
1358 return NULL;
1359 }
1360 /* this is actually an immutable bytes sequence */
1361 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1362 OPENSSL_free(bytes_buf);
1363 return retval;
1364}
Bill Janssen98d19da2007-09-10 21:51:02 +00001365
1366static PyObject *
1367PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1368
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001369 PyObject *retval = NULL;
1370 char *filename = NULL;
1371 X509 *x=NULL;
1372 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001373
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001374 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001375 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001376
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001377 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001378 PyErr_SetString(PySSLErrorObject,
1379 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001380 goto fail0;
1381 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001382
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001383 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001384 PyErr_SetString(PySSLErrorObject,
1385 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001386 goto fail0;
1387 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001388
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001389 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1390 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001391 PyErr_SetString(PySSLErrorObject,
1392 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001393 goto fail0;
1394 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001395
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001396 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001397 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001398
1399 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001400
1401 if (cert != NULL) BIO_free(cert);
1402 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001403}
1404
1405
1406static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001407PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001408{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001409 int verification;
1410 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001411 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001412
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001413 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1414 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001415
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001416 if (!self->handshake_done) {
1417 PyErr_SetString(PyExc_ValueError,
1418 "handshake not done yet");
1419 return NULL;
1420 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001421 if (!self->peer_cert)
1422 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001423
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001424 b = PyObject_IsTrue(binary_mode);
1425 if (b < 0)
1426 return NULL;
1427 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001428 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001429 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001430 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001431 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001432 if ((verification & SSL_VERIFY_PEER) == 0)
1433 return PyDict_New();
1434 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001435 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001436 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001437}
1438
1439PyDoc_STRVAR(PySSL_peercert_doc,
1440"peer_certificate([der=False]) -> certificate\n\
1441\n\
1442Returns the certificate for the peer. If no certificate was provided,\n\
1443returns None. If a certificate was provided, but not validated, returns\n\
1444an empty dictionary. Otherwise returns a dict containing information\n\
1445about the peer certificate.\n\
1446\n\
1447If the optional argument is True, returns a DER-encoded copy of the\n\
1448peer certificate, or None if no certificate was provided. This will\n\
1449return the certificate even if it wasn't validated.");
1450
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001451static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001452
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001453 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001454 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001455 char *cipher_name;
1456 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001457
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001458 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001459 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001460 current = SSL_get_current_cipher(self->ssl);
1461 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001462 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001463
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001464 retval = PyTuple_New(3);
1465 if (retval == NULL)
1466 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001467
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001468 cipher_name = (char *) SSL_CIPHER_get_name(current);
1469 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001470 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001471 PyTuple_SET_ITEM(retval, 0, Py_None);
1472 } else {
1473 v = PyString_FromString(cipher_name);
1474 if (v == NULL)
1475 goto fail0;
1476 PyTuple_SET_ITEM(retval, 0, v);
1477 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001478 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001479 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001480 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001481 PyTuple_SET_ITEM(retval, 1, Py_None);
1482 } else {
1483 v = PyString_FromString(cipher_protocol);
1484 if (v == NULL)
1485 goto fail0;
1486 PyTuple_SET_ITEM(retval, 1, v);
1487 }
1488 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1489 if (v == NULL)
1490 goto fail0;
1491 PyTuple_SET_ITEM(retval, 2, v);
1492 return retval;
1493
Bill Janssen98d19da2007-09-10 21:51:02 +00001494 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001495 Py_DECREF(retval);
1496 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001497}
1498
Alex Gaynore98205d2014-09-04 13:33:22 -07001499static PyObject *PySSL_version(PySSLSocket *self)
1500{
1501 const char *version;
1502
1503 if (self->ssl == NULL)
1504 Py_RETURN_NONE;
1505 version = SSL_get_version(self->ssl);
1506 if (!strcmp(version, "unknown"))
1507 Py_RETURN_NONE;
1508 return PyUnicode_FromString(version);
1509}
1510
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001511#ifdef OPENSSL_NPN_NEGOTIATED
1512static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1513 const unsigned char *out;
1514 unsigned int outlen;
1515
1516 SSL_get0_next_proto_negotiated(self->ssl,
1517 &out, &outlen);
1518
1519 if (out == NULL)
1520 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001521 return PyString_FromStringAndSize((char *)out, outlen);
1522}
1523#endif
1524
1525#ifdef HAVE_ALPN
1526static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1527 const unsigned char *out;
1528 unsigned int outlen;
1529
1530 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1531
1532 if (out == NULL)
1533 Py_RETURN_NONE;
1534 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001535}
1536#endif
1537
1538static PyObject *PySSL_compression(PySSLSocket *self) {
1539#ifdef OPENSSL_NO_COMP
1540 Py_RETURN_NONE;
1541#else
1542 const COMP_METHOD *comp_method;
1543 const char *short_name;
1544
1545 if (self->ssl == NULL)
1546 Py_RETURN_NONE;
1547 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001548 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001549 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001550 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001551 if (short_name == NULL)
1552 Py_RETURN_NONE;
1553 return PyBytes_FromString(short_name);
1554#endif
1555}
1556
1557static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1558 Py_INCREF(self->ctx);
1559 return self->ctx;
1560}
1561
1562static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1563 void *closure) {
1564
1565 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1566#if !HAVE_SNI
1567 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1568 "context is not supported by your OpenSSL library");
1569 return -1;
1570#else
1571 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001572 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001573 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1574#endif
1575 } else {
1576 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1577 return -1;
1578 }
1579
1580 return 0;
1581}
1582
1583PyDoc_STRVAR(PySSL_set_context_doc,
1584"_setter_context(ctx)\n\
1585\
1586This changes the context associated with the SSLSocket. This is typically\n\
1587used from within a callback function set by the set_servername_callback\n\
1588on the SSLContext to change the certificate information associated with the\n\
1589SSLSocket before the cryptographic exchange handshake messages\n");
1590
1591
1592
1593static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001594{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001595 if (self->peer_cert) /* Possible not to have one? */
1596 X509_free (self->peer_cert);
1597 if (self->ssl)
1598 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001599 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001600 Py_XDECREF(self->ssl_sock);
1601 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001602 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001603}
1604
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001605/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001606 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001607 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001608 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001609
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001610static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001611check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001612{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001613 fd_set fds;
1614 struct timeval tv;
1615 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001616
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001617 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1618 if (s->sock_timeout < 0.0)
1619 return SOCKET_IS_BLOCKING;
1620 else if (s->sock_timeout == 0.0)
1621 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001622
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001623 /* Guard against closed socket */
1624 if (s->sock_fd < 0)
1625 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001626
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001627 /* Prefer poll, if available, since you can poll() any fd
1628 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001629#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001630 {
1631 struct pollfd pollfd;
1632 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001633
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001634 pollfd.fd = s->sock_fd;
1635 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001636
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001637 /* s->sock_timeout is in seconds, timeout in ms */
1638 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1639 PySSL_BEGIN_ALLOW_THREADS
1640 rc = poll(&pollfd, 1, timeout);
1641 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001642
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001643 goto normal_return;
1644 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001645#endif
1646
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001647 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001648 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001649 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001650
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001651 /* Construct the arguments to select */
1652 tv.tv_sec = (int)s->sock_timeout;
1653 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1654 FD_ZERO(&fds);
1655 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001656
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001657 /* See if the socket is ready */
1658 PySSL_BEGIN_ALLOW_THREADS
1659 if (writing)
1660 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1661 else
1662 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1663 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001664
Bill Janssen934b16d2008-06-28 22:19:33 +00001665#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001666normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001667#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001668 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1669 (when we are able to write or when there's something to read) */
1670 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001671}
1672
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001673static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001674{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001675 Py_buffer buf;
1676 int len;
1677 int sockstate;
1678 int err;
1679 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001680 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001681
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001682 Py_INCREF(sock);
1683
1684 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1685 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001686 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001687 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001688
Victor Stinnerc1a44262013-06-25 00:48:02 +02001689 if (buf.len > INT_MAX) {
1690 PyErr_Format(PyExc_OverflowError,
1691 "string longer than %d bytes", INT_MAX);
1692 goto error;
1693 }
1694
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001695 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001696 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001697 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1698 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001699
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001700 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001701 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1702 PyErr_SetString(PySSLErrorObject,
1703 "The write operation timed out");
1704 goto error;
1705 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1706 PyErr_SetString(PySSLErrorObject,
1707 "Underlying socket has been closed.");
1708 goto error;
1709 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1710 PyErr_SetString(PySSLErrorObject,
1711 "Underlying socket too large for select().");
1712 goto error;
1713 }
1714 do {
1715 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001716 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001717 err = SSL_get_error(self->ssl, len);
1718 PySSL_END_ALLOW_THREADS
1719 if (PyErr_CheckSignals()) {
1720 goto error;
1721 }
1722 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001723 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001724 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001725 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001726 } else {
1727 sockstate = SOCKET_OPERATION_OK;
1728 }
1729 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1730 PyErr_SetString(PySSLErrorObject,
1731 "The write operation timed out");
1732 goto error;
1733 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1734 PyErr_SetString(PySSLErrorObject,
1735 "Underlying socket has been closed.");
1736 goto error;
1737 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1738 break;
1739 }
1740 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001741
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001742 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001743 PyBuffer_Release(&buf);
1744 if (len > 0)
1745 return PyInt_FromLong(len);
1746 else
1747 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001748
1749error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001750 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001751 PyBuffer_Release(&buf);
1752 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001753}
1754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001755PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001756"write(s) -> len\n\
1757\n\
1758Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001759of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001761static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001762{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001763 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001764
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001765 PySSL_BEGIN_ALLOW_THREADS
1766 count = SSL_pending(self->ssl);
1767 PySSL_END_ALLOW_THREADS
1768 if (count < 0)
1769 return PySSL_SetError(self, count, __FILE__, __LINE__);
1770 else
1771 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001772}
1773
1774PyDoc_STRVAR(PySSL_SSLpending_doc,
1775"pending() -> count\n\
1776\n\
1777Returns the number of already decrypted bytes available for read,\n\
1778pending on the connection.\n");
1779
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001780static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001781{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001782 PyObject *dest = NULL;
1783 Py_buffer buf;
1784 char *mem;
1785 int len, count;
1786 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001787 int sockstate;
1788 int err;
1789 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001790 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001791
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001792 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001794 buf.obj = NULL;
1795 buf.buf = NULL;
1796 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1797 goto error;
1798
1799 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001800 if (len < 0) {
1801 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1802 goto error;
1803 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001804 dest = PyBytes_FromStringAndSize(NULL, len);
1805 if (dest == NULL)
1806 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001807 if (len == 0) {
1808 Py_XDECREF(sock);
1809 return dest;
1810 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001811 mem = PyBytes_AS_STRING(dest);
1812 }
1813 else {
1814 buf_passed = 1;
1815 mem = buf.buf;
1816 if (len <= 0 || len > buf.len) {
1817 len = (int) buf.len;
1818 if (buf.len != len) {
1819 PyErr_SetString(PyExc_OverflowError,
1820 "maximum length can't fit in a C 'int'");
1821 goto error;
1822 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001823 if (len == 0) {
1824 count = 0;
1825 goto done;
1826 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001827 }
1828 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001829
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001830 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001831 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001832 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1833 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001834
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001835 do {
1836 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001837 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001838 err = SSL_get_error(self->ssl, count);
1839 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001840 if (PyErr_CheckSignals())
1841 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001843 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001844 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001845 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001846 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1847 (SSL_get_shutdown(self->ssl) ==
1848 SSL_RECEIVED_SHUTDOWN))
1849 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001850 count = 0;
1851 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001852 } else {
1853 sockstate = SOCKET_OPERATION_OK;
1854 }
1855 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1856 PyErr_SetString(PySSLErrorObject,
1857 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001859 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1860 break;
1861 }
1862 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1863 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001864 PySSL_SetError(self, count, __FILE__, __LINE__);
1865 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001866 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001867
1868done:
1869 Py_DECREF(sock);
1870 if (!buf_passed) {
1871 _PyBytes_Resize(&dest, count);
1872 return dest;
1873 }
1874 else {
1875 PyBuffer_Release(&buf);
1876 return PyLong_FromLong(count);
1877 }
1878
1879error:
1880 Py_DECREF(sock);
1881 if (!buf_passed)
1882 Py_XDECREF(dest);
1883 else
1884 PyBuffer_Release(&buf);
1885 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001886}
1887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001888PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001889"read([len]) -> string\n\
1890\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001892
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001893static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001894{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001895 int err, ssl_err, sockstate, nonblocking;
1896 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001897 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001898
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001899 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001900 if (sock->sock_fd < 0) {
1901 _setSSLError("Underlying socket connection gone",
1902 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001903 return NULL;
1904 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001905 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001906
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001908 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001909 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1910 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001911
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001912 while (1) {
1913 PySSL_BEGIN_ALLOW_THREADS
1914 /* Disable read-ahead so that unwrap can work correctly.
1915 * Otherwise OpenSSL might read in too much data,
1916 * eating clear text data that happens to be
1917 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001918 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001919 * function is used and the shutdown_seen_zero != 0
1920 * condition is met.
1921 */
1922 if (self->shutdown_seen_zero)
1923 SSL_set_read_ahead(self->ssl, 0);
1924 err = SSL_shutdown(self->ssl);
1925 PySSL_END_ALLOW_THREADS
1926 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1927 if (err > 0)
1928 break;
1929 if (err == 0) {
1930 /* Don't loop endlessly; instead preserve legacy
1931 behaviour of trying SSL_shutdown() only twice.
1932 This looks necessary for OpenSSL < 0.9.8m */
1933 if (++zeros > 1)
1934 break;
1935 /* Shutdown was sent, now try receiving */
1936 self->shutdown_seen_zero = 1;
1937 continue;
1938 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001939
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001940 /* Possibly retry shutdown until timeout or failure */
1941 ssl_err = SSL_get_error(self->ssl, err);
1942 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001943 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001944 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001945 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001946 else
1947 break;
1948 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1949 if (ssl_err == SSL_ERROR_WANT_READ)
1950 PyErr_SetString(PySSLErrorObject,
1951 "The read operation timed out");
1952 else
1953 PyErr_SetString(PySSLErrorObject,
1954 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001955 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001956 }
1957 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1958 PyErr_SetString(PySSLErrorObject,
1959 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001960 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001961 }
1962 else if (sockstate != SOCKET_OPERATION_OK)
1963 /* Retain the SSL error code */
1964 break;
1965 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001966
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001967 if (err < 0) {
1968 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001969 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001970 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001971 else
1972 /* It's already INCREF'ed */
1973 return (PyObject *) sock;
1974
1975error:
1976 Py_DECREF(sock);
1977 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001978}
1979
1980PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1981"shutdown(s) -> socket\n\
1982\n\
1983Does the SSL shutdown handshake with the remote end, and returns\n\
1984the underlying socket object.");
1985
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001986#if HAVE_OPENSSL_FINISHED
1987static PyObject *
1988PySSL_tls_unique_cb(PySSLSocket *self)
1989{
1990 PyObject *retval = NULL;
1991 char buf[PySSL_CB_MAXLEN];
1992 size_t len;
1993
1994 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1995 /* if session is resumed XOR we are the client */
1996 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1997 }
1998 else {
1999 /* if a new session XOR we are the server */
2000 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2001 }
2002
2003 /* It cannot be negative in current OpenSSL version as of July 2011 */
2004 if (len == 0)
2005 Py_RETURN_NONE;
2006
2007 retval = PyBytes_FromStringAndSize(buf, len);
2008
2009 return retval;
2010}
2011
2012PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2013"tls_unique_cb() -> bytes\n\
2014\n\
2015Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2016\n\
2017If the TLS handshake is not yet complete, None is returned");
2018
2019#endif /* HAVE_OPENSSL_FINISHED */
2020
2021static PyGetSetDef ssl_getsetlist[] = {
2022 {"context", (getter) PySSL_get_context,
2023 (setter) PySSL_set_context, PySSL_set_context_doc},
2024 {NULL}, /* sentinel */
2025};
2026
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002027static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002028 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2029 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2030 PySSL_SSLwrite_doc},
2031 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2032 PySSL_SSLread_doc},
2033 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2034 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002035 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2036 PySSL_peercert_doc},
2037 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002038 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002039#ifdef OPENSSL_NPN_NEGOTIATED
2040 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2041#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002042#ifdef HAVE_ALPN
2043 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2044#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002045 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002046 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2047 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002048#if HAVE_OPENSSL_FINISHED
2049 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2050 PySSL_tls_unique_cb_doc},
2051#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002052 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002053};
2054
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002055static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002056 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002057 "_ssl._SSLSocket", /*tp_name*/
2058 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002059 0, /*tp_itemsize*/
2060 /* methods */
2061 (destructor)PySSL_dealloc, /*tp_dealloc*/
2062 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002063 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002064 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002065 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002066 0, /*tp_repr*/
2067 0, /*tp_as_number*/
2068 0, /*tp_as_sequence*/
2069 0, /*tp_as_mapping*/
2070 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002071 0, /*tp_call*/
2072 0, /*tp_str*/
2073 0, /*tp_getattro*/
2074 0, /*tp_setattro*/
2075 0, /*tp_as_buffer*/
2076 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2077 0, /*tp_doc*/
2078 0, /*tp_traverse*/
2079 0, /*tp_clear*/
2080 0, /*tp_richcompare*/
2081 0, /*tp_weaklistoffset*/
2082 0, /*tp_iter*/
2083 0, /*tp_iternext*/
2084 PySSLMethods, /*tp_methods*/
2085 0, /*tp_members*/
2086 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002087};
2088
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002089
2090/*
2091 * _SSLContext objects
2092 */
2093
2094static PyObject *
2095context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2096{
2097 char *kwlist[] = {"protocol", NULL};
2098 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002099 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002100 long options;
2101 SSL_CTX *ctx = NULL;
2102
2103 if (!PyArg_ParseTupleAndKeywords(
2104 args, kwds, "i:_SSLContext", kwlist,
2105 &proto_version))
2106 return NULL;
2107
2108 PySSL_BEGIN_ALLOW_THREADS
2109 if (proto_version == PY_SSL_VERSION_TLS1)
2110 ctx = SSL_CTX_new(TLSv1_method());
2111#if HAVE_TLSv1_2
2112 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2113 ctx = SSL_CTX_new(TLSv1_1_method());
2114 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2115 ctx = SSL_CTX_new(TLSv1_2_method());
2116#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002117#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002118 else if (proto_version == PY_SSL_VERSION_SSL3)
2119 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002120#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002121#ifndef OPENSSL_NO_SSL2
2122 else if (proto_version == PY_SSL_VERSION_SSL2)
2123 ctx = SSL_CTX_new(SSLv2_method());
2124#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002125 else if (proto_version == PY_SSL_VERSION_TLS)
2126 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002127 else
2128 proto_version = -1;
2129 PySSL_END_ALLOW_THREADS
2130
2131 if (proto_version == -1) {
2132 PyErr_SetString(PyExc_ValueError,
2133 "invalid protocol version");
2134 return NULL;
2135 }
2136 if (ctx == NULL) {
2137 PyErr_SetString(PySSLErrorObject,
2138 "failed to allocate SSL context");
2139 return NULL;
2140 }
2141
2142 assert(type != NULL && type->tp_alloc != NULL);
2143 self = (PySSLContext *) type->tp_alloc(type, 0);
2144 if (self == NULL) {
2145 SSL_CTX_free(ctx);
2146 return NULL;
2147 }
2148 self->ctx = ctx;
2149#ifdef OPENSSL_NPN_NEGOTIATED
2150 self->npn_protocols = NULL;
2151#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002152#ifdef HAVE_ALPN
2153 self->alpn_protocols = NULL;
2154#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002155#ifndef OPENSSL_NO_TLSEXT
2156 self->set_hostname = NULL;
2157#endif
2158 /* Don't check host name by default */
2159 self->check_hostname = 0;
2160 /* Defaults */
2161 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2162 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2163 if (proto_version != PY_SSL_VERSION_SSL2)
2164 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002165 if (proto_version != PY_SSL_VERSION_SSL3)
2166 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002167 SSL_CTX_set_options(self->ctx, options);
2168
2169#ifndef OPENSSL_NO_ECDH
2170 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2171 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002172 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2173 */
2174#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002175 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2176#else
2177 {
2178 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2179 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2180 EC_KEY_free(key);
2181 }
2182#endif
2183#endif
2184
2185#define SID_CTX "Python"
2186 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2187 sizeof(SID_CTX));
2188#undef SID_CTX
2189
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002190#ifdef X509_V_FLAG_TRUSTED_FIRST
2191 {
2192 /* Improve trust chain building when cross-signed intermediate
2193 certificates are present. See https://bugs.python.org/issue23476. */
2194 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2195 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2196 }
2197#endif
2198
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002199 return (PyObject *)self;
2200}
2201
2202static int
2203context_traverse(PySSLContext *self, visitproc visit, void *arg)
2204{
2205#ifndef OPENSSL_NO_TLSEXT
2206 Py_VISIT(self->set_hostname);
2207#endif
2208 return 0;
2209}
2210
2211static int
2212context_clear(PySSLContext *self)
2213{
2214#ifndef OPENSSL_NO_TLSEXT
2215 Py_CLEAR(self->set_hostname);
2216#endif
2217 return 0;
2218}
2219
2220static void
2221context_dealloc(PySSLContext *self)
2222{
2223 context_clear(self);
2224 SSL_CTX_free(self->ctx);
2225#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002226 PyMem_FREE(self->npn_protocols);
2227#endif
2228#ifdef HAVE_ALPN
2229 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002230#endif
2231 Py_TYPE(self)->tp_free(self);
2232}
2233
2234static PyObject *
2235set_ciphers(PySSLContext *self, PyObject *args)
2236{
2237 int ret;
2238 const char *cipherlist;
2239
2240 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2241 return NULL;
2242 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2243 if (ret == 0) {
2244 /* Clearing the error queue is necessary on some OpenSSL versions,
2245 otherwise the error will be reported again when another SSL call
2246 is done. */
2247 ERR_clear_error();
2248 PyErr_SetString(PySSLErrorObject,
2249 "No cipher can be selected.");
2250 return NULL;
2251 }
2252 Py_RETURN_NONE;
2253}
2254
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002255#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002256static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002257do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2258 const unsigned char *server_protocols, unsigned int server_protocols_len,
2259 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002260{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002261 int ret;
2262 if (client_protocols == NULL) {
2263 client_protocols = (unsigned char *)"";
2264 client_protocols_len = 0;
2265 }
2266 if (server_protocols == NULL) {
2267 server_protocols = (unsigned char *)"";
2268 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002269 }
2270
Benjamin Petersonaa707582015-01-23 17:30:26 -05002271 ret = SSL_select_next_proto(out, outlen,
2272 server_protocols, server_protocols_len,
2273 client_protocols, client_protocols_len);
2274 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2275 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002276
2277 return SSL_TLSEXT_ERR_OK;
2278}
2279
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002280/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2281static int
2282_advertiseNPN_cb(SSL *s,
2283 const unsigned char **data, unsigned int *len,
2284 void *args)
2285{
2286 PySSLContext *ssl_ctx = (PySSLContext *) args;
2287
2288 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002289 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002290 *len = 0;
2291 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002292 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002293 *len = ssl_ctx->npn_protocols_len;
2294 }
2295
2296 return SSL_TLSEXT_ERR_OK;
2297}
2298/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2299static int
2300_selectNPN_cb(SSL *s,
2301 unsigned char **out, unsigned char *outlen,
2302 const unsigned char *server, unsigned int server_len,
2303 void *args)
2304{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002305 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002306 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002307 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002308}
2309#endif
2310
2311static PyObject *
2312_set_npn_protocols(PySSLContext *self, PyObject *args)
2313{
2314#ifdef OPENSSL_NPN_NEGOTIATED
2315 Py_buffer protos;
2316
2317 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2318 return NULL;
2319
2320 if (self->npn_protocols != NULL) {
2321 PyMem_Free(self->npn_protocols);
2322 }
2323
2324 self->npn_protocols = PyMem_Malloc(protos.len);
2325 if (self->npn_protocols == NULL) {
2326 PyBuffer_Release(&protos);
2327 return PyErr_NoMemory();
2328 }
2329 memcpy(self->npn_protocols, protos.buf, protos.len);
2330 self->npn_protocols_len = (int) protos.len;
2331
2332 /* set both server and client callbacks, because the context can
2333 * be used to create both types of sockets */
2334 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2335 _advertiseNPN_cb,
2336 self);
2337 SSL_CTX_set_next_proto_select_cb(self->ctx,
2338 _selectNPN_cb,
2339 self);
2340
2341 PyBuffer_Release(&protos);
2342 Py_RETURN_NONE;
2343#else
2344 PyErr_SetString(PyExc_NotImplementedError,
2345 "The NPN extension requires OpenSSL 1.0.1 or later.");
2346 return NULL;
2347#endif
2348}
2349
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002350#ifdef HAVE_ALPN
2351static int
2352_selectALPN_cb(SSL *s,
2353 const unsigned char **out, unsigned char *outlen,
2354 const unsigned char *client_protocols, unsigned int client_protocols_len,
2355 void *args)
2356{
2357 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002358 return do_protocol_selection(1, (unsigned char **)out, outlen,
2359 ctx->alpn_protocols, ctx->alpn_protocols_len,
2360 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002361}
2362#endif
2363
2364static PyObject *
2365_set_alpn_protocols(PySSLContext *self, PyObject *args)
2366{
2367#ifdef HAVE_ALPN
2368 Py_buffer protos;
2369
2370 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2371 return NULL;
2372
2373 PyMem_FREE(self->alpn_protocols);
2374 self->alpn_protocols = PyMem_Malloc(protos.len);
2375 if (!self->alpn_protocols)
2376 return PyErr_NoMemory();
2377 memcpy(self->alpn_protocols, protos.buf, protos.len);
2378 self->alpn_protocols_len = protos.len;
2379 PyBuffer_Release(&protos);
2380
2381 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2382 return PyErr_NoMemory();
2383 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2384
2385 PyBuffer_Release(&protos);
2386 Py_RETURN_NONE;
2387#else
2388 PyErr_SetString(PyExc_NotImplementedError,
2389 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2390 return NULL;
2391#endif
2392}
2393
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002394static PyObject *
2395get_verify_mode(PySSLContext *self, void *c)
2396{
2397 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2398 case SSL_VERIFY_NONE:
2399 return PyLong_FromLong(PY_SSL_CERT_NONE);
2400 case SSL_VERIFY_PEER:
2401 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2402 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2403 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2404 }
2405 PyErr_SetString(PySSLErrorObject,
2406 "invalid return value from SSL_CTX_get_verify_mode");
2407 return NULL;
2408}
2409
2410static int
2411set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2412{
2413 int n, mode;
2414 if (!PyArg_Parse(arg, "i", &n))
2415 return -1;
2416 if (n == PY_SSL_CERT_NONE)
2417 mode = SSL_VERIFY_NONE;
2418 else if (n == PY_SSL_CERT_OPTIONAL)
2419 mode = SSL_VERIFY_PEER;
2420 else if (n == PY_SSL_CERT_REQUIRED)
2421 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2422 else {
2423 PyErr_SetString(PyExc_ValueError,
2424 "invalid value for verify_mode");
2425 return -1;
2426 }
2427 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2428 PyErr_SetString(PyExc_ValueError,
2429 "Cannot set verify_mode to CERT_NONE when "
2430 "check_hostname is enabled.");
2431 return -1;
2432 }
2433 SSL_CTX_set_verify(self->ctx, mode, NULL);
2434 return 0;
2435}
2436
2437#ifdef HAVE_OPENSSL_VERIFY_PARAM
2438static PyObject *
2439get_verify_flags(PySSLContext *self, void *c)
2440{
2441 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002442 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002443 unsigned long flags;
2444
2445 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002446 param = X509_STORE_get0_param(store);
2447 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002448 return PyLong_FromUnsignedLong(flags);
2449}
2450
2451static int
2452set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2453{
2454 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002455 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002456 unsigned long new_flags, flags, set, clear;
2457
2458 if (!PyArg_Parse(arg, "k", &new_flags))
2459 return -1;
2460 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002461 param = X509_STORE_get0_param(store);
2462 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002463 clear = flags & ~new_flags;
2464 set = ~flags & new_flags;
2465 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002466 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002467 _setSSLError(NULL, 0, __FILE__, __LINE__);
2468 return -1;
2469 }
2470 }
2471 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002472 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002473 _setSSLError(NULL, 0, __FILE__, __LINE__);
2474 return -1;
2475 }
2476 }
2477 return 0;
2478}
2479#endif
2480
2481static PyObject *
2482get_options(PySSLContext *self, void *c)
2483{
2484 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2485}
2486
2487static int
2488set_options(PySSLContext *self, PyObject *arg, void *c)
2489{
2490 long new_opts, opts, set, clear;
2491 if (!PyArg_Parse(arg, "l", &new_opts))
2492 return -1;
2493 opts = SSL_CTX_get_options(self->ctx);
2494 clear = opts & ~new_opts;
2495 set = ~opts & new_opts;
2496 if (clear) {
2497#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2498 SSL_CTX_clear_options(self->ctx, clear);
2499#else
2500 PyErr_SetString(PyExc_ValueError,
2501 "can't clear options before OpenSSL 0.9.8m");
2502 return -1;
2503#endif
2504 }
2505 if (set)
2506 SSL_CTX_set_options(self->ctx, set);
2507 return 0;
2508}
2509
2510static PyObject *
2511get_check_hostname(PySSLContext *self, void *c)
2512{
2513 return PyBool_FromLong(self->check_hostname);
2514}
2515
2516static int
2517set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2518{
2519 PyObject *py_check_hostname;
2520 int check_hostname;
2521 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2522 return -1;
2523
2524 check_hostname = PyObject_IsTrue(py_check_hostname);
2525 if (check_hostname < 0)
2526 return -1;
2527 if (check_hostname &&
2528 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2529 PyErr_SetString(PyExc_ValueError,
2530 "check_hostname needs a SSL context with either "
2531 "CERT_OPTIONAL or CERT_REQUIRED");
2532 return -1;
2533 }
2534 self->check_hostname = check_hostname;
2535 return 0;
2536}
2537
2538
2539typedef struct {
2540 PyThreadState *thread_state;
2541 PyObject *callable;
2542 char *password;
2543 int size;
2544 int error;
2545} _PySSLPasswordInfo;
2546
2547static int
2548_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2549 const char *bad_type_error)
2550{
2551 /* Set the password and size fields of a _PySSLPasswordInfo struct
2552 from a unicode, bytes, or byte array object.
2553 The password field will be dynamically allocated and must be freed
2554 by the caller */
2555 PyObject *password_bytes = NULL;
2556 const char *data = NULL;
2557 Py_ssize_t size;
2558
2559 if (PyUnicode_Check(password)) {
2560 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2561 if (!password_bytes) {
2562 goto error;
2563 }
2564 data = PyBytes_AS_STRING(password_bytes);
2565 size = PyBytes_GET_SIZE(password_bytes);
2566 } else if (PyBytes_Check(password)) {
2567 data = PyBytes_AS_STRING(password);
2568 size = PyBytes_GET_SIZE(password);
2569 } else if (PyByteArray_Check(password)) {
2570 data = PyByteArray_AS_STRING(password);
2571 size = PyByteArray_GET_SIZE(password);
2572 } else {
2573 PyErr_SetString(PyExc_TypeError, bad_type_error);
2574 goto error;
2575 }
2576
2577 if (size > (Py_ssize_t)INT_MAX) {
2578 PyErr_Format(PyExc_ValueError,
2579 "password cannot be longer than %d bytes", INT_MAX);
2580 goto error;
2581 }
2582
2583 PyMem_Free(pw_info->password);
2584 pw_info->password = PyMem_Malloc(size);
2585 if (!pw_info->password) {
2586 PyErr_SetString(PyExc_MemoryError,
2587 "unable to allocate password buffer");
2588 goto error;
2589 }
2590 memcpy(pw_info->password, data, size);
2591 pw_info->size = (int)size;
2592
2593 Py_XDECREF(password_bytes);
2594 return 1;
2595
2596error:
2597 Py_XDECREF(password_bytes);
2598 return 0;
2599}
2600
2601static int
2602_password_callback(char *buf, int size, int rwflag, void *userdata)
2603{
2604 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2605 PyObject *fn_ret = NULL;
2606
2607 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2608
2609 if (pw_info->callable) {
2610 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2611 if (!fn_ret) {
2612 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2613 core python API, so we could use it to add a frame here */
2614 goto error;
2615 }
2616
2617 if (!_pwinfo_set(pw_info, fn_ret,
2618 "password callback must return a string")) {
2619 goto error;
2620 }
2621 Py_CLEAR(fn_ret);
2622 }
2623
2624 if (pw_info->size > size) {
2625 PyErr_Format(PyExc_ValueError,
2626 "password cannot be longer than %d bytes", size);
2627 goto error;
2628 }
2629
2630 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2631 memcpy(buf, pw_info->password, pw_info->size);
2632 return pw_info->size;
2633
2634error:
2635 Py_XDECREF(fn_ret);
2636 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2637 pw_info->error = 1;
2638 return -1;
2639}
2640
2641static PyObject *
2642load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2643{
2644 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002645 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2646 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002647 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2648 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002649 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2650 int r;
2651
2652 errno = 0;
2653 ERR_clear_error();
2654 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002655 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002656 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002657 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002658 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002659
2660 if (keyfile && keyfile != Py_None) {
2661 if (PyString_Check(keyfile)) {
2662 Py_INCREF(keyfile);
2663 keyfile_bytes = keyfile;
2664 } else {
2665 PyObject *u = PyUnicode_FromObject(keyfile);
2666 if (!u)
2667 goto error;
2668 keyfile_bytes = PyUnicode_AsEncodedString(
2669 u, Py_FileSystemDefaultEncoding, NULL);
2670 Py_DECREF(u);
2671 if (!keyfile_bytes)
2672 goto error;
2673 }
2674 }
2675
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002676 if (password && password != Py_None) {
2677 if (PyCallable_Check(password)) {
2678 pw_info.callable = password;
2679 } else if (!_pwinfo_set(&pw_info, password,
2680 "password should be a string or callable")) {
2681 goto error;
2682 }
2683 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2684 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2685 }
2686 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2687 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2688 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2689 if (r != 1) {
2690 if (pw_info.error) {
2691 ERR_clear_error();
2692 /* the password callback has already set the error information */
2693 }
2694 else if (errno != 0) {
2695 ERR_clear_error();
2696 PyErr_SetFromErrno(PyExc_IOError);
2697 }
2698 else {
2699 _setSSLError(NULL, 0, __FILE__, __LINE__);
2700 }
2701 goto error;
2702 }
2703 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2704 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002705 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002706 SSL_FILETYPE_PEM);
2707 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2708 if (r != 1) {
2709 if (pw_info.error) {
2710 ERR_clear_error();
2711 /* the password callback has already set the error information */
2712 }
2713 else if (errno != 0) {
2714 ERR_clear_error();
2715 PyErr_SetFromErrno(PyExc_IOError);
2716 }
2717 else {
2718 _setSSLError(NULL, 0, __FILE__, __LINE__);
2719 }
2720 goto error;
2721 }
2722 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2723 r = SSL_CTX_check_private_key(self->ctx);
2724 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2725 if (r != 1) {
2726 _setSSLError(NULL, 0, __FILE__, __LINE__);
2727 goto error;
2728 }
2729 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2730 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002731 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002732 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002733 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002734 Py_RETURN_NONE;
2735
2736error:
2737 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2738 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002739 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002740 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002741 PyMem_Free(certfile_bytes);
2742 return NULL;
2743}
2744
2745/* internal helper function, returns -1 on error
2746 */
2747static int
2748_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2749 int filetype)
2750{
2751 BIO *biobuf = NULL;
2752 X509_STORE *store;
2753 int retval = 0, err, loaded = 0;
2754
2755 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2756
2757 if (len <= 0) {
2758 PyErr_SetString(PyExc_ValueError,
2759 "Empty certificate data");
2760 return -1;
2761 } else if (len > INT_MAX) {
2762 PyErr_SetString(PyExc_OverflowError,
2763 "Certificate data is too long.");
2764 return -1;
2765 }
2766
2767 biobuf = BIO_new_mem_buf(data, (int)len);
2768 if (biobuf == NULL) {
2769 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2770 return -1;
2771 }
2772
2773 store = SSL_CTX_get_cert_store(self->ctx);
2774 assert(store != NULL);
2775
2776 while (1) {
2777 X509 *cert = NULL;
2778 int r;
2779
2780 if (filetype == SSL_FILETYPE_ASN1) {
2781 cert = d2i_X509_bio(biobuf, NULL);
2782 } else {
2783 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002784 SSL_CTX_get_default_passwd_cb(self->ctx),
2785 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2786 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002787 }
2788 if (cert == NULL) {
2789 break;
2790 }
2791 r = X509_STORE_add_cert(store, cert);
2792 X509_free(cert);
2793 if (!r) {
2794 err = ERR_peek_last_error();
2795 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2796 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2797 /* cert already in hash table, not an error */
2798 ERR_clear_error();
2799 } else {
2800 break;
2801 }
2802 }
2803 loaded++;
2804 }
2805
2806 err = ERR_peek_last_error();
2807 if ((filetype == SSL_FILETYPE_ASN1) &&
2808 (loaded > 0) &&
2809 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2810 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2811 /* EOF ASN1 file, not an error */
2812 ERR_clear_error();
2813 retval = 0;
2814 } else if ((filetype == SSL_FILETYPE_PEM) &&
2815 (loaded > 0) &&
2816 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2817 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2818 /* EOF PEM file, not an error */
2819 ERR_clear_error();
2820 retval = 0;
2821 } else {
2822 _setSSLError(NULL, 0, __FILE__, __LINE__);
2823 retval = -1;
2824 }
2825
2826 BIO_free(biobuf);
2827 return retval;
2828}
2829
2830
2831static PyObject *
2832load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2833{
2834 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2835 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2836 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2837 const char *cafile_buf = NULL, *capath_buf = NULL;
2838 int r = 0, ok = 1;
2839
2840 errno = 0;
2841 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2842 "|OOO:load_verify_locations", kwlist,
2843 &cafile, &capath, &cadata))
2844 return NULL;
2845
2846 if (cafile == Py_None)
2847 cafile = NULL;
2848 if (capath == Py_None)
2849 capath = NULL;
2850 if (cadata == Py_None)
2851 cadata = NULL;
2852
2853 if (cafile == NULL && capath == NULL && cadata == NULL) {
2854 PyErr_SetString(PyExc_TypeError,
2855 "cafile, capath and cadata cannot be all omitted");
2856 goto error;
2857 }
2858
2859 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002860 if (PyString_Check(cafile)) {
2861 Py_INCREF(cafile);
2862 cafile_bytes = cafile;
2863 } else {
2864 PyObject *u = PyUnicode_FromObject(cafile);
2865 if (!u)
2866 goto error;
2867 cafile_bytes = PyUnicode_AsEncodedString(
2868 u, Py_FileSystemDefaultEncoding, NULL);
2869 Py_DECREF(u);
2870 if (!cafile_bytes)
2871 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002872 }
2873 }
2874 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002875 if (PyString_Check(capath)) {
2876 Py_INCREF(capath);
2877 capath_bytes = capath;
2878 } else {
2879 PyObject *u = PyUnicode_FromObject(capath);
2880 if (!u)
2881 goto error;
2882 capath_bytes = PyUnicode_AsEncodedString(
2883 u, Py_FileSystemDefaultEncoding, NULL);
2884 Py_DECREF(u);
2885 if (!capath_bytes)
2886 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002887 }
2888 }
2889
2890 /* validata cadata type and load cadata */
2891 if (cadata) {
2892 Py_buffer buf;
2893 PyObject *cadata_ascii = NULL;
2894
2895 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2896 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2897 PyBuffer_Release(&buf);
2898 PyErr_SetString(PyExc_TypeError,
2899 "cadata should be a contiguous buffer with "
2900 "a single dimension");
2901 goto error;
2902 }
2903 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2904 PyBuffer_Release(&buf);
2905 if (r == -1) {
2906 goto error;
2907 }
2908 } else {
2909 PyErr_Clear();
2910 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2911 if (cadata_ascii == NULL) {
2912 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002913 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002914 "bytes-like object");
2915 goto error;
2916 }
2917 r = _add_ca_certs(self,
2918 PyBytes_AS_STRING(cadata_ascii),
2919 PyBytes_GET_SIZE(cadata_ascii),
2920 SSL_FILETYPE_PEM);
2921 Py_DECREF(cadata_ascii);
2922 if (r == -1) {
2923 goto error;
2924 }
2925 }
2926 }
2927
2928 /* load cafile or capath */
2929 if (cafile_bytes || capath_bytes) {
2930 if (cafile)
2931 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2932 if (capath)
2933 capath_buf = PyBytes_AS_STRING(capath_bytes);
2934 PySSL_BEGIN_ALLOW_THREADS
2935 r = SSL_CTX_load_verify_locations(
2936 self->ctx,
2937 cafile_buf,
2938 capath_buf);
2939 PySSL_END_ALLOW_THREADS
2940 if (r != 1) {
2941 ok = 0;
2942 if (errno != 0) {
2943 ERR_clear_error();
2944 PyErr_SetFromErrno(PyExc_IOError);
2945 }
2946 else {
2947 _setSSLError(NULL, 0, __FILE__, __LINE__);
2948 }
2949 goto error;
2950 }
2951 }
2952 goto end;
2953
2954 error:
2955 ok = 0;
2956 end:
2957 Py_XDECREF(cafile_bytes);
2958 Py_XDECREF(capath_bytes);
2959 if (ok) {
2960 Py_RETURN_NONE;
2961 } else {
2962 return NULL;
2963 }
2964}
2965
2966static PyObject *
2967load_dh_params(PySSLContext *self, PyObject *filepath)
2968{
2969 BIO *bio;
2970 DH *dh;
2971 char *path = PyBytes_AsString(filepath);
2972 if (!path) {
2973 return NULL;
2974 }
2975
2976 bio = BIO_new_file(path, "r");
2977 if (bio == NULL) {
2978 ERR_clear_error();
2979 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2980 return NULL;
2981 }
2982 errno = 0;
2983 PySSL_BEGIN_ALLOW_THREADS
2984 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2985 BIO_free(bio);
2986 PySSL_END_ALLOW_THREADS
2987 if (dh == NULL) {
2988 if (errno != 0) {
2989 ERR_clear_error();
2990 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2991 }
2992 else {
2993 _setSSLError(NULL, 0, __FILE__, __LINE__);
2994 }
2995 return NULL;
2996 }
2997 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2998 _setSSLError(NULL, 0, __FILE__, __LINE__);
2999 DH_free(dh);
3000 Py_RETURN_NONE;
3001}
3002
3003static PyObject *
3004context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3005{
3006 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3007 PySocketSockObject *sock;
3008 int server_side = 0;
3009 char *hostname = NULL;
3010 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3011
3012 /* server_hostname is either None (or absent), or to be encoded
3013 using the idna encoding. */
3014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3015 PySocketModule.Sock_Type,
3016 &sock, &server_side,
3017 Py_TYPE(Py_None), &hostname_obj,
3018 &ssl_sock)) {
3019 PyErr_Clear();
3020 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3021 PySocketModule.Sock_Type,
3022 &sock, &server_side,
3023 "idna", &hostname, &ssl_sock))
3024 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003025 }
3026
3027 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3028 hostname, ssl_sock);
3029 if (hostname != NULL)
3030 PyMem_Free(hostname);
3031 return res;
3032}
3033
3034static PyObject *
3035session_stats(PySSLContext *self, PyObject *unused)
3036{
3037 int r;
3038 PyObject *value, *stats = PyDict_New();
3039 if (!stats)
3040 return NULL;
3041
3042#define ADD_STATS(SSL_NAME, KEY_NAME) \
3043 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3044 if (value == NULL) \
3045 goto error; \
3046 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3047 Py_DECREF(value); \
3048 if (r < 0) \
3049 goto error;
3050
3051 ADD_STATS(number, "number");
3052 ADD_STATS(connect, "connect");
3053 ADD_STATS(connect_good, "connect_good");
3054 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3055 ADD_STATS(accept, "accept");
3056 ADD_STATS(accept_good, "accept_good");
3057 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3058 ADD_STATS(accept, "accept");
3059 ADD_STATS(hits, "hits");
3060 ADD_STATS(misses, "misses");
3061 ADD_STATS(timeouts, "timeouts");
3062 ADD_STATS(cache_full, "cache_full");
3063
3064#undef ADD_STATS
3065
3066 return stats;
3067
3068error:
3069 Py_DECREF(stats);
3070 return NULL;
3071}
3072
3073static PyObject *
3074set_default_verify_paths(PySSLContext *self, PyObject *unused)
3075{
3076 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3077 _setSSLError(NULL, 0, __FILE__, __LINE__);
3078 return NULL;
3079 }
3080 Py_RETURN_NONE;
3081}
3082
3083#ifndef OPENSSL_NO_ECDH
3084static PyObject *
3085set_ecdh_curve(PySSLContext *self, PyObject *name)
3086{
3087 char *name_bytes;
3088 int nid;
3089 EC_KEY *key;
3090
3091 name_bytes = PyBytes_AsString(name);
3092 if (!name_bytes) {
3093 return NULL;
3094 }
3095 nid = OBJ_sn2nid(name_bytes);
3096 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003097 PyObject *r = PyObject_Repr(name);
3098 if (!r)
3099 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003100 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003101 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3102 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003103 return NULL;
3104 }
3105 key = EC_KEY_new_by_curve_name(nid);
3106 if (key == NULL) {
3107 _setSSLError(NULL, 0, __FILE__, __LINE__);
3108 return NULL;
3109 }
3110 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3111 EC_KEY_free(key);
3112 Py_RETURN_NONE;
3113}
3114#endif
3115
3116#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3117static int
3118_servername_callback(SSL *s, int *al, void *args)
3119{
3120 int ret;
3121 PySSLContext *ssl_ctx = (PySSLContext *) args;
3122 PySSLSocket *ssl;
3123 PyObject *servername_o;
3124 PyObject *servername_idna;
3125 PyObject *result;
3126 /* The high-level ssl.SSLSocket object */
3127 PyObject *ssl_socket;
3128 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3129#ifdef WITH_THREAD
3130 PyGILState_STATE gstate = PyGILState_Ensure();
3131#endif
3132
3133 if (ssl_ctx->set_hostname == NULL) {
3134 /* remove race condition in this the call back while if removing the
3135 * callback is in progress */
3136#ifdef WITH_THREAD
3137 PyGILState_Release(gstate);
3138#endif
3139 return SSL_TLSEXT_ERR_OK;
3140 }
3141
3142 ssl = SSL_get_app_data(s);
3143 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003144 if (ssl->ssl_sock == NULL) {
3145 ssl_socket = Py_None;
3146 } else {
3147 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3148 Py_INCREF(ssl_socket);
3149 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003150 if (ssl_socket == Py_None) {
3151 goto error;
3152 }
3153
3154 if (servername == NULL) {
3155 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3156 Py_None, ssl_ctx, NULL);
3157 }
3158 else {
3159 servername_o = PyBytes_FromString(servername);
3160 if (servername_o == NULL) {
3161 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3162 goto error;
3163 }
3164 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3165 if (servername_idna == NULL) {
3166 PyErr_WriteUnraisable(servername_o);
3167 Py_DECREF(servername_o);
3168 goto error;
3169 }
3170 Py_DECREF(servername_o);
3171 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3172 servername_idna, ssl_ctx, NULL);
3173 Py_DECREF(servername_idna);
3174 }
3175 Py_DECREF(ssl_socket);
3176
3177 if (result == NULL) {
3178 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3179 *al = SSL_AD_HANDSHAKE_FAILURE;
3180 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3181 }
3182 else {
3183 if (result != Py_None) {
3184 *al = (int) PyLong_AsLong(result);
3185 if (PyErr_Occurred()) {
3186 PyErr_WriteUnraisable(result);
3187 *al = SSL_AD_INTERNAL_ERROR;
3188 }
3189 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3190 }
3191 else {
3192 ret = SSL_TLSEXT_ERR_OK;
3193 }
3194 Py_DECREF(result);
3195 }
3196
3197#ifdef WITH_THREAD
3198 PyGILState_Release(gstate);
3199#endif
3200 return ret;
3201
3202error:
3203 Py_DECREF(ssl_socket);
3204 *al = SSL_AD_INTERNAL_ERROR;
3205 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3206#ifdef WITH_THREAD
3207 PyGILState_Release(gstate);
3208#endif
3209 return ret;
3210}
3211#endif
3212
3213PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3214"set_servername_callback(method)\n\
3215\n\
3216This sets a callback that will be called when a server name is provided by\n\
3217the SSL/TLS client in the SNI extension.\n\
3218\n\
3219If the argument is None then the callback is disabled. The method is called\n\
3220with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3221See RFC 6066 for details of the SNI extension.");
3222
3223static PyObject *
3224set_servername_callback(PySSLContext *self, PyObject *args)
3225{
3226#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3227 PyObject *cb;
3228
3229 if (!PyArg_ParseTuple(args, "O", &cb))
3230 return NULL;
3231
3232 Py_CLEAR(self->set_hostname);
3233 if (cb == Py_None) {
3234 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3235 }
3236 else {
3237 if (!PyCallable_Check(cb)) {
3238 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3239 PyErr_SetString(PyExc_TypeError,
3240 "not a callable object");
3241 return NULL;
3242 }
3243 Py_INCREF(cb);
3244 self->set_hostname = cb;
3245 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3246 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3247 }
3248 Py_RETURN_NONE;
3249#else
3250 PyErr_SetString(PyExc_NotImplementedError,
3251 "The TLS extension servername callback, "
3252 "SSL_CTX_set_tlsext_servername_callback, "
3253 "is not in the current OpenSSL library.");
3254 return NULL;
3255#endif
3256}
3257
3258PyDoc_STRVAR(PySSL_get_stats_doc,
3259"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3260\n\
3261Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3262CA extension and certificate revocation lists inside the context's cert\n\
3263store.\n\
3264NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3265been used at least once.");
3266
3267static PyObject *
3268cert_store_stats(PySSLContext *self)
3269{
3270 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003271 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003272 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003273 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003274
3275 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003276 objs = X509_STORE_get0_objects(store);
3277 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3278 obj = sk_X509_OBJECT_value(objs, i);
3279 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003280 case X509_LU_X509:
3281 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003282 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003283 ca++;
3284 }
3285 break;
3286 case X509_LU_CRL:
3287 crl++;
3288 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003289 default:
3290 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3291 * As far as I can tell they are internal states and never
3292 * stored in a cert store */
3293 break;
3294 }
3295 }
3296 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3297 "x509_ca", ca);
3298}
3299
3300PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3301"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3302\n\
3303Returns a list of dicts with information of loaded CA certs. If the\n\
3304optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3305NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3306been used at least once.");
3307
3308static PyObject *
3309get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3310{
3311 char *kwlist[] = {"binary_form", NULL};
3312 X509_STORE *store;
3313 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003314 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003315 int i;
3316 int binary_mode = 0;
3317
3318 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3319 kwlist, &py_binary_mode)) {
3320 return NULL;
3321 }
3322 binary_mode = PyObject_IsTrue(py_binary_mode);
3323 if (binary_mode < 0) {
3324 return NULL;
3325 }
3326
3327 if ((rlist = PyList_New(0)) == NULL) {
3328 return NULL;
3329 }
3330
3331 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003332 objs = X509_STORE_get0_objects(store);
3333 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003334 X509_OBJECT *obj;
3335 X509 *cert;
3336
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003337 obj = sk_X509_OBJECT_value(objs, i);
3338 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003339 /* not a x509 cert */
3340 continue;
3341 }
3342 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003343 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003344 if (!X509_check_ca(cert)) {
3345 continue;
3346 }
3347 if (binary_mode) {
3348 ci = _certificate_to_der(cert);
3349 } else {
3350 ci = _decode_certificate(cert);
3351 }
3352 if (ci == NULL) {
3353 goto error;
3354 }
3355 if (PyList_Append(rlist, ci) == -1) {
3356 goto error;
3357 }
3358 Py_CLEAR(ci);
3359 }
3360 return rlist;
3361
3362 error:
3363 Py_XDECREF(ci);
3364 Py_XDECREF(rlist);
3365 return NULL;
3366}
3367
3368
3369static PyGetSetDef context_getsetlist[] = {
3370 {"check_hostname", (getter) get_check_hostname,
3371 (setter) set_check_hostname, NULL},
3372 {"options", (getter) get_options,
3373 (setter) set_options, NULL},
3374#ifdef HAVE_OPENSSL_VERIFY_PARAM
3375 {"verify_flags", (getter) get_verify_flags,
3376 (setter) set_verify_flags, NULL},
3377#endif
3378 {"verify_mode", (getter) get_verify_mode,
3379 (setter) set_verify_mode, NULL},
3380 {NULL}, /* sentinel */
3381};
3382
3383static struct PyMethodDef context_methods[] = {
3384 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3385 METH_VARARGS | METH_KEYWORDS, NULL},
3386 {"set_ciphers", (PyCFunction) set_ciphers,
3387 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003388 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3389 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003390 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3391 METH_VARARGS, NULL},
3392 {"load_cert_chain", (PyCFunction) load_cert_chain,
3393 METH_VARARGS | METH_KEYWORDS, NULL},
3394 {"load_dh_params", (PyCFunction) load_dh_params,
3395 METH_O, NULL},
3396 {"load_verify_locations", (PyCFunction) load_verify_locations,
3397 METH_VARARGS | METH_KEYWORDS, NULL},
3398 {"session_stats", (PyCFunction) session_stats,
3399 METH_NOARGS, NULL},
3400 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3401 METH_NOARGS, NULL},
3402#ifndef OPENSSL_NO_ECDH
3403 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3404 METH_O, NULL},
3405#endif
3406 {"set_servername_callback", (PyCFunction) set_servername_callback,
3407 METH_VARARGS, PySSL_set_servername_callback_doc},
3408 {"cert_store_stats", (PyCFunction) cert_store_stats,
3409 METH_NOARGS, PySSL_get_stats_doc},
3410 {"get_ca_certs", (PyCFunction) get_ca_certs,
3411 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3412 {NULL, NULL} /* sentinel */
3413};
3414
3415static PyTypeObject PySSLContext_Type = {
3416 PyVarObject_HEAD_INIT(NULL, 0)
3417 "_ssl._SSLContext", /*tp_name*/
3418 sizeof(PySSLContext), /*tp_basicsize*/
3419 0, /*tp_itemsize*/
3420 (destructor)context_dealloc, /*tp_dealloc*/
3421 0, /*tp_print*/
3422 0, /*tp_getattr*/
3423 0, /*tp_setattr*/
3424 0, /*tp_reserved*/
3425 0, /*tp_repr*/
3426 0, /*tp_as_number*/
3427 0, /*tp_as_sequence*/
3428 0, /*tp_as_mapping*/
3429 0, /*tp_hash*/
3430 0, /*tp_call*/
3431 0, /*tp_str*/
3432 0, /*tp_getattro*/
3433 0, /*tp_setattro*/
3434 0, /*tp_as_buffer*/
3435 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3436 0, /*tp_doc*/
3437 (traverseproc) context_traverse, /*tp_traverse*/
3438 (inquiry) context_clear, /*tp_clear*/
3439 0, /*tp_richcompare*/
3440 0, /*tp_weaklistoffset*/
3441 0, /*tp_iter*/
3442 0, /*tp_iternext*/
3443 context_methods, /*tp_methods*/
3444 0, /*tp_members*/
3445 context_getsetlist, /*tp_getset*/
3446 0, /*tp_base*/
3447 0, /*tp_dict*/
3448 0, /*tp_descr_get*/
3449 0, /*tp_descr_set*/
3450 0, /*tp_dictoffset*/
3451 0, /*tp_init*/
3452 0, /*tp_alloc*/
3453 context_new, /*tp_new*/
3454};
3455
3456
3457
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003458#ifdef HAVE_OPENSSL_RAND
3459
3460/* helper routines for seeding the SSL PRNG */
3461static PyObject *
3462PySSL_RAND_add(PyObject *self, PyObject *args)
3463{
3464 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003465 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003466 double entropy;
3467
3468 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003469 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003470 do {
3471 if (len >= INT_MAX) {
3472 written = INT_MAX;
3473 } else {
3474 written = len;
3475 }
3476 RAND_add(buf, (int)written, entropy);
3477 buf += written;
3478 len -= written;
3479 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003480 Py_INCREF(Py_None);
3481 return Py_None;
3482}
3483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003484PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003485"RAND_add(string, entropy)\n\
3486\n\
3487Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003488bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003489
3490static PyObject *
3491PySSL_RAND_status(PyObject *self)
3492{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003493 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003494}
3495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003496PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003497"RAND_status() -> 0 or 1\n\
3498\n\
3499Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3500It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003501using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003502
Victor Stinner7c906672015-01-06 13:53:37 +01003503#endif /* HAVE_OPENSSL_RAND */
3504
3505
Benjamin Peterson42e10292016-07-07 00:02:31 -07003506#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003507
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003508static PyObject *
3509PySSL_RAND_egd(PyObject *self, PyObject *arg)
3510{
3511 int bytes;
3512
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003513 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003514 return PyErr_Format(PyExc_TypeError,
3515 "RAND_egd() expected string, found %s",
3516 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003517 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003518 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003519 PyErr_SetString(PySSLErrorObject,
3520 "EGD connection failed or EGD did not return "
3521 "enough data to seed the PRNG");
3522 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003523 }
3524 return PyInt_FromLong(bytes);
3525}
3526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003527PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003528"RAND_egd(path) -> bytes\n\
3529\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003530Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3531Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003532fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003533
Benjamin Peterson42e10292016-07-07 00:02:31 -07003534#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003535
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003536
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003537PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3538"get_default_verify_paths() -> tuple\n\
3539\n\
3540Return search paths and environment vars that are used by SSLContext's\n\
3541set_default_verify_paths() to load default CAs. The values are\n\
3542'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3543
3544static PyObject *
3545PySSL_get_default_verify_paths(PyObject *self)
3546{
3547 PyObject *ofile_env = NULL;
3548 PyObject *ofile = NULL;
3549 PyObject *odir_env = NULL;
3550 PyObject *odir = NULL;
3551
Benjamin Peterson65192c12015-07-18 10:59:13 -07003552#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003553 const char *tmp = (info); \
3554 target = NULL; \
3555 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3556 else { target = PyBytes_FromString(tmp); } \
3557 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003558 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003559
Benjamin Peterson65192c12015-07-18 10:59:13 -07003560 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3561 CONVERT(X509_get_default_cert_file(), ofile);
3562 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3563 CONVERT(X509_get_default_cert_dir(), odir);
3564#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003565
3566 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3567
3568 error:
3569 Py_XDECREF(ofile_env);
3570 Py_XDECREF(ofile);
3571 Py_XDECREF(odir_env);
3572 Py_XDECREF(odir);
3573 return NULL;
3574}
3575
3576static PyObject*
3577asn1obj2py(ASN1_OBJECT *obj)
3578{
3579 int nid;
3580 const char *ln, *sn;
3581 char buf[100];
3582 Py_ssize_t buflen;
3583
3584 nid = OBJ_obj2nid(obj);
3585 if (nid == NID_undef) {
3586 PyErr_Format(PyExc_ValueError, "Unknown object");
3587 return NULL;
3588 }
3589 sn = OBJ_nid2sn(nid);
3590 ln = OBJ_nid2ln(nid);
3591 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3592 if (buflen < 0) {
3593 _setSSLError(NULL, 0, __FILE__, __LINE__);
3594 return NULL;
3595 }
3596 if (buflen) {
3597 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3598 } else {
3599 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3600 }
3601}
3602
3603PyDoc_STRVAR(PySSL_txt2obj_doc,
3604"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3605\n\
3606Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3607objects are looked up by OID. With name=True short and long name are also\n\
3608matched.");
3609
3610static PyObject*
3611PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3612{
3613 char *kwlist[] = {"txt", "name", NULL};
3614 PyObject *result = NULL;
3615 char *txt;
3616 PyObject *pyname = Py_None;
3617 int name = 0;
3618 ASN1_OBJECT *obj;
3619
3620 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3621 kwlist, &txt, &pyname)) {
3622 return NULL;
3623 }
3624 name = PyObject_IsTrue(pyname);
3625 if (name < 0)
3626 return NULL;
3627 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3628 if (obj == NULL) {
3629 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3630 return NULL;
3631 }
3632 result = asn1obj2py(obj);
3633 ASN1_OBJECT_free(obj);
3634 return result;
3635}
3636
3637PyDoc_STRVAR(PySSL_nid2obj_doc,
3638"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3639\n\
3640Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3641
3642static PyObject*
3643PySSL_nid2obj(PyObject *self, PyObject *args)
3644{
3645 PyObject *result = NULL;
3646 int nid;
3647 ASN1_OBJECT *obj;
3648
3649 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3650 return NULL;
3651 }
3652 if (nid < NID_undef) {
3653 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3654 return NULL;
3655 }
3656 obj = OBJ_nid2obj(nid);
3657 if (obj == NULL) {
3658 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3659 return NULL;
3660 }
3661 result = asn1obj2py(obj);
3662 ASN1_OBJECT_free(obj);
3663 return result;
3664}
3665
3666#ifdef _MSC_VER
3667
3668static PyObject*
3669certEncodingType(DWORD encodingType)
3670{
3671 static PyObject *x509_asn = NULL;
3672 static PyObject *pkcs_7_asn = NULL;
3673
3674 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003675 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003676 if (x509_asn == NULL)
3677 return NULL;
3678 }
3679 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003680 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003681 if (pkcs_7_asn == NULL)
3682 return NULL;
3683 }
3684 switch(encodingType) {
3685 case X509_ASN_ENCODING:
3686 Py_INCREF(x509_asn);
3687 return x509_asn;
3688 case PKCS_7_ASN_ENCODING:
3689 Py_INCREF(pkcs_7_asn);
3690 return pkcs_7_asn;
3691 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003692 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003693 }
3694}
3695
3696static PyObject*
3697parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3698{
3699 CERT_ENHKEY_USAGE *usage;
3700 DWORD size, error, i;
3701 PyObject *retval;
3702
3703 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3704 error = GetLastError();
3705 if (error == CRYPT_E_NOT_FOUND) {
3706 Py_RETURN_TRUE;
3707 }
3708 return PyErr_SetFromWindowsErr(error);
3709 }
3710
3711 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3712 if (usage == NULL) {
3713 return PyErr_NoMemory();
3714 }
3715
3716 /* Now get the actual enhanced usage property */
3717 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3718 PyMem_Free(usage);
3719 error = GetLastError();
3720 if (error == CRYPT_E_NOT_FOUND) {
3721 Py_RETURN_TRUE;
3722 }
3723 return PyErr_SetFromWindowsErr(error);
3724 }
3725 retval = PySet_New(NULL);
3726 if (retval == NULL) {
3727 goto error;
3728 }
3729 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3730 if (usage->rgpszUsageIdentifier[i]) {
3731 PyObject *oid;
3732 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003733 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003734 if (oid == NULL) {
3735 Py_CLEAR(retval);
3736 goto error;
3737 }
3738 err = PySet_Add(retval, oid);
3739 Py_DECREF(oid);
3740 if (err == -1) {
3741 Py_CLEAR(retval);
3742 goto error;
3743 }
3744 }
3745 }
3746 error:
3747 PyMem_Free(usage);
3748 return retval;
3749}
3750
3751PyDoc_STRVAR(PySSL_enum_certificates_doc,
3752"enum_certificates(store_name) -> []\n\
3753\n\
3754Retrieve certificates from Windows' cert store. store_name may be one of\n\
3755'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3756The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3757encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3758PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3759boolean True.");
3760
3761static PyObject *
3762PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3763{
3764 char *kwlist[] = {"store_name", NULL};
3765 char *store_name;
3766 HCERTSTORE hStore = NULL;
3767 PCCERT_CONTEXT pCertCtx = NULL;
3768 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3769 PyObject *result = NULL;
3770
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003771 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003772 kwlist, &store_name)) {
3773 return NULL;
3774 }
3775 result = PyList_New(0);
3776 if (result == NULL) {
3777 return NULL;
3778 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003779 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3780 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3781 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003782 if (hStore == NULL) {
3783 Py_DECREF(result);
3784 return PyErr_SetFromWindowsErr(GetLastError());
3785 }
3786
3787 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3788 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3789 pCertCtx->cbCertEncoded);
3790 if (!cert) {
3791 Py_CLEAR(result);
3792 break;
3793 }
3794 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3795 Py_CLEAR(result);
3796 break;
3797 }
3798 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3799 if (keyusage == Py_True) {
3800 Py_DECREF(keyusage);
3801 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3802 }
3803 if (keyusage == NULL) {
3804 Py_CLEAR(result);
3805 break;
3806 }
3807 if ((tup = PyTuple_New(3)) == NULL) {
3808 Py_CLEAR(result);
3809 break;
3810 }
3811 PyTuple_SET_ITEM(tup, 0, cert);
3812 cert = NULL;
3813 PyTuple_SET_ITEM(tup, 1, enc);
3814 enc = NULL;
3815 PyTuple_SET_ITEM(tup, 2, keyusage);
3816 keyusage = NULL;
3817 if (PyList_Append(result, tup) < 0) {
3818 Py_CLEAR(result);
3819 break;
3820 }
3821 Py_CLEAR(tup);
3822 }
3823 if (pCertCtx) {
3824 /* loop ended with an error, need to clean up context manually */
3825 CertFreeCertificateContext(pCertCtx);
3826 }
3827
3828 /* In error cases cert, enc and tup may not be NULL */
3829 Py_XDECREF(cert);
3830 Py_XDECREF(enc);
3831 Py_XDECREF(keyusage);
3832 Py_XDECREF(tup);
3833
3834 if (!CertCloseStore(hStore, 0)) {
3835 /* This error case might shadow another exception.*/
3836 Py_XDECREF(result);
3837 return PyErr_SetFromWindowsErr(GetLastError());
3838 }
3839 return result;
3840}
3841
3842PyDoc_STRVAR(PySSL_enum_crls_doc,
3843"enum_crls(store_name) -> []\n\
3844\n\
3845Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3846'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3847The function returns a list of (bytes, encoding_type) tuples. The\n\
3848encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3849PKCS_7_ASN_ENCODING.");
3850
3851static PyObject *
3852PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3853{
3854 char *kwlist[] = {"store_name", NULL};
3855 char *store_name;
3856 HCERTSTORE hStore = NULL;
3857 PCCRL_CONTEXT pCrlCtx = NULL;
3858 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3859 PyObject *result = NULL;
3860
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003861 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003862 kwlist, &store_name)) {
3863 return NULL;
3864 }
3865 result = PyList_New(0);
3866 if (result == NULL) {
3867 return NULL;
3868 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003869 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3870 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3871 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003872 if (hStore == NULL) {
3873 Py_DECREF(result);
3874 return PyErr_SetFromWindowsErr(GetLastError());
3875 }
3876
3877 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3878 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3879 pCrlCtx->cbCrlEncoded);
3880 if (!crl) {
3881 Py_CLEAR(result);
3882 break;
3883 }
3884 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3885 Py_CLEAR(result);
3886 break;
3887 }
3888 if ((tup = PyTuple_New(2)) == NULL) {
3889 Py_CLEAR(result);
3890 break;
3891 }
3892 PyTuple_SET_ITEM(tup, 0, crl);
3893 crl = NULL;
3894 PyTuple_SET_ITEM(tup, 1, enc);
3895 enc = NULL;
3896
3897 if (PyList_Append(result, tup) < 0) {
3898 Py_CLEAR(result);
3899 break;
3900 }
3901 Py_CLEAR(tup);
3902 }
3903 if (pCrlCtx) {
3904 /* loop ended with an error, need to clean up context manually */
3905 CertFreeCRLContext(pCrlCtx);
3906 }
3907
3908 /* In error cases cert, enc and tup may not be NULL */
3909 Py_XDECREF(crl);
3910 Py_XDECREF(enc);
3911 Py_XDECREF(tup);
3912
3913 if (!CertCloseStore(hStore, 0)) {
3914 /* This error case might shadow another exception.*/
3915 Py_XDECREF(result);
3916 return PyErr_SetFromWindowsErr(GetLastError());
3917 }
3918 return result;
3919}
3920
3921#endif /* _MSC_VER */
3922
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003923/* List of functions exported by this module. */
3924
3925static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003926 {"_test_decode_cert", PySSL_test_decode_certificate,
3927 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003928#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003929 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3930 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003931 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3932 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003933#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003934#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003935 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3936 PySSL_RAND_egd_doc},
3937#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003938 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3939 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3940#ifdef _MSC_VER
3941 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3942 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3943 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3944 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3945#endif
3946 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3947 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3948 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3949 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003950 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003951};
3952
3953
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003954#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003955
3956/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003957 * of the Python C thread library
3958 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3959 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003960
3961static PyThread_type_lock *_ssl_locks = NULL;
3962
Christian Heimes10107812013-08-19 17:36:29 +02003963#if OPENSSL_VERSION_NUMBER >= 0x10000000
3964/* use new CRYPTO_THREADID API. */
3965static void
3966_ssl_threadid_callback(CRYPTO_THREADID *id)
3967{
3968 CRYPTO_THREADID_set_numeric(id,
3969 (unsigned long)PyThread_get_thread_ident());
3970}
3971#else
3972/* deprecated CRYPTO_set_id_callback() API. */
3973static unsigned long
3974_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003975 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003976}
Christian Heimes10107812013-08-19 17:36:29 +02003977#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003978
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003979static void _ssl_thread_locking_function
3980 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003981 /* this function is needed to perform locking on shared data
3982 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003983 structures that will be implicitly shared whenever multiple
3984 threads use OpenSSL.) Multi-threaded applications will
3985 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003986
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003987 locking_function() must be able to handle up to
3988 CRYPTO_num_locks() different mutex locks. It sets the n-th
3989 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003990
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003991 file and line are the file number of the function setting the
3992 lock. They can be useful for debugging.
3993 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003994
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003995 if ((_ssl_locks == NULL) ||
3996 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3997 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003998
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003999 if (mode & CRYPTO_LOCK) {
4000 PyThread_acquire_lock(_ssl_locks[n], 1);
4001 } else {
4002 PyThread_release_lock(_ssl_locks[n]);
4003 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004004}
4005
4006static int _setup_ssl_threads(void) {
4007
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004008 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004009
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004010 if (_ssl_locks == NULL) {
4011 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004012 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4013 if (_ssl_locks == NULL) {
4014 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004015 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004016 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004017 memset(_ssl_locks, 0,
4018 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004019 for (i = 0; i < _ssl_locks_count; i++) {
4020 _ssl_locks[i] = PyThread_allocate_lock();
4021 if (_ssl_locks[i] == NULL) {
4022 unsigned int j;
4023 for (j = 0; j < i; j++) {
4024 PyThread_free_lock(_ssl_locks[j]);
4025 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004026 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004027 return 0;
4028 }
4029 }
4030 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004031#if OPENSSL_VERSION_NUMBER >= 0x10000000
4032 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4033#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004034 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004035#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004036 }
4037 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004038}
4039
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004040#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004042PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004043"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004044for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004045
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004046
4047
4048
4049static void
4050parse_openssl_version(unsigned long libver,
4051 unsigned int *major, unsigned int *minor,
4052 unsigned int *fix, unsigned int *patch,
4053 unsigned int *status)
4054{
4055 *status = libver & 0xF;
4056 libver >>= 4;
4057 *patch = libver & 0xFF;
4058 libver >>= 8;
4059 *fix = libver & 0xFF;
4060 libver >>= 8;
4061 *minor = libver & 0xFF;
4062 libver >>= 8;
4063 *major = libver & 0xFF;
4064}
4065
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004066PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004067init_ssl(void)
4068{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004069 PyObject *m, *d, *r;
4070 unsigned long libver;
4071 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004072 struct py_ssl_error_code *errcode;
4073 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004074
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004075 if (PyType_Ready(&PySSLContext_Type) < 0)
4076 return;
4077 if (PyType_Ready(&PySSLSocket_Type) < 0)
4078 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004079
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004080 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4081 if (m == NULL)
4082 return;
4083 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004084
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004085 /* Load _socket module and its C API */
4086 if (PySocketModule_ImportModuleAndAPI())
4087 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004088
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004089 /* Init OpenSSL */
4090 SSL_load_error_strings();
4091 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00004092#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004093#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004094 /* note that this will start threading if not already started */
4095 if (!_setup_ssl_threads()) {
4096 return;
4097 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004098#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4099 /* OpenSSL 1.1.0 builtin thread support is enabled */
4100 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004101#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004102#endif /* WITH_THREAD */
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004103 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004104
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004105 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004106 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4107 "ssl.SSLError", SSLError_doc,
4108 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004109 if (PySSLErrorObject == NULL)
4110 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004111 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4112
4113 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4114 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4115 PySSLErrorObject, NULL);
4116 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4117 "ssl.SSLWantReadError", SSLWantReadError_doc,
4118 PySSLErrorObject, NULL);
4119 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4120 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4121 PySSLErrorObject, NULL);
4122 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4123 "ssl.SSLSyscallError", SSLSyscallError_doc,
4124 PySSLErrorObject, NULL);
4125 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4126 "ssl.SSLEOFError", SSLEOFError_doc,
4127 PySSLErrorObject, NULL);
4128 if (PySSLZeroReturnErrorObject == NULL
4129 || PySSLWantReadErrorObject == NULL
4130 || PySSLWantWriteErrorObject == NULL
4131 || PySSLSyscallErrorObject == NULL
4132 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004133 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004134
4135 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4136 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4137 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4138 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4139 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4140
4141 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4142 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4143 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4144 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4145 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4146 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4147 return;
4148 if (PyDict_SetItemString(d, "_SSLContext",
4149 (PyObject *)&PySSLContext_Type) != 0)
4150 return;
4151 if (PyDict_SetItemString(d, "_SSLSocket",
4152 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004153 return;
4154 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4155 PY_SSL_ERROR_ZERO_RETURN);
4156 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4157 PY_SSL_ERROR_WANT_READ);
4158 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4159 PY_SSL_ERROR_WANT_WRITE);
4160 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4161 PY_SSL_ERROR_WANT_X509_LOOKUP);
4162 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4163 PY_SSL_ERROR_SYSCALL);
4164 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4165 PY_SSL_ERROR_SSL);
4166 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4167 PY_SSL_ERROR_WANT_CONNECT);
4168 /* non ssl.h errorcodes */
4169 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4170 PY_SSL_ERROR_EOF);
4171 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4172 PY_SSL_ERROR_INVALID_ERROR_CODE);
4173 /* cert requirements */
4174 PyModule_AddIntConstant(m, "CERT_NONE",
4175 PY_SSL_CERT_NONE);
4176 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4177 PY_SSL_CERT_OPTIONAL);
4178 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4179 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004180 /* CRL verification for verification_flags */
4181 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4182 0);
4183 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4184 X509_V_FLAG_CRL_CHECK);
4185 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4186 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4187 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4188 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004189#ifdef X509_V_FLAG_TRUSTED_FIRST
4190 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4191 X509_V_FLAG_TRUSTED_FIRST);
4192#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004193
4194 /* Alert Descriptions from ssl.h */
4195 /* note RESERVED constants no longer intended for use have been removed */
4196 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4197
4198#define ADD_AD_CONSTANT(s) \
4199 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4200 SSL_AD_##s)
4201
4202 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4203 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4204 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4205 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4206 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4207 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4208 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4209 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4210 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4211 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4212 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4213 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4214 ADD_AD_CONSTANT(UNKNOWN_CA);
4215 ADD_AD_CONSTANT(ACCESS_DENIED);
4216 ADD_AD_CONSTANT(DECODE_ERROR);
4217 ADD_AD_CONSTANT(DECRYPT_ERROR);
4218 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4219 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4220 ADD_AD_CONSTANT(INTERNAL_ERROR);
4221 ADD_AD_CONSTANT(USER_CANCELLED);
4222 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4223 /* Not all constants are in old OpenSSL versions */
4224#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4225 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4226#endif
4227#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4228 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4229#endif
4230#ifdef SSL_AD_UNRECOGNIZED_NAME
4231 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4232#endif
4233#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4234 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4235#endif
4236#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4237 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4238#endif
4239#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4240 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4241#endif
4242
4243#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004244
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004245 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004246#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004247 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4248 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004249#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004250#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004251 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4252 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004253#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004254 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004255 PY_SSL_VERSION_TLS);
4256 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4257 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004258 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4259 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004260#if HAVE_TLSv1_2
4261 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4262 PY_SSL_VERSION_TLS1_1);
4263 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4264 PY_SSL_VERSION_TLS1_2);
4265#endif
4266
4267 /* protocol options */
4268 PyModule_AddIntConstant(m, "OP_ALL",
4269 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4270 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4271 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4272 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4273#if HAVE_TLSv1_2
4274 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4275 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4276#endif
4277 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4278 SSL_OP_CIPHER_SERVER_PREFERENCE);
4279 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4280#ifdef SSL_OP_SINGLE_ECDH_USE
4281 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4282#endif
4283#ifdef SSL_OP_NO_COMPRESSION
4284 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4285 SSL_OP_NO_COMPRESSION);
4286#endif
4287
4288#if HAVE_SNI
4289 r = Py_True;
4290#else
4291 r = Py_False;
4292#endif
4293 Py_INCREF(r);
4294 PyModule_AddObject(m, "HAS_SNI", r);
4295
4296#if HAVE_OPENSSL_FINISHED
4297 r = Py_True;
4298#else
4299 r = Py_False;
4300#endif
4301 Py_INCREF(r);
4302 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4303
4304#ifdef OPENSSL_NO_ECDH
4305 r = Py_False;
4306#else
4307 r = Py_True;
4308#endif
4309 Py_INCREF(r);
4310 PyModule_AddObject(m, "HAS_ECDH", r);
4311
4312#ifdef OPENSSL_NPN_NEGOTIATED
4313 r = Py_True;
4314#else
4315 r = Py_False;
4316#endif
4317 Py_INCREF(r);
4318 PyModule_AddObject(m, "HAS_NPN", r);
4319
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004320#ifdef HAVE_ALPN
4321 r = Py_True;
4322#else
4323 r = Py_False;
4324#endif
4325 Py_INCREF(r);
4326 PyModule_AddObject(m, "HAS_ALPN", r);
4327
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004328 /* Mappings for error codes */
4329 err_codes_to_names = PyDict_New();
4330 err_names_to_codes = PyDict_New();
4331 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4332 return;
4333 errcode = error_codes;
4334 while (errcode->mnemonic != NULL) {
4335 PyObject *mnemo, *key;
4336 mnemo = PyUnicode_FromString(errcode->mnemonic);
4337 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4338 if (mnemo == NULL || key == NULL)
4339 return;
4340 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4341 return;
4342 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4343 return;
4344 Py_DECREF(key);
4345 Py_DECREF(mnemo);
4346 errcode++;
4347 }
4348 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4349 return;
4350 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4351 return;
4352
4353 lib_codes_to_names = PyDict_New();
4354 if (lib_codes_to_names == NULL)
4355 return;
4356 libcode = library_codes;
4357 while (libcode->library != NULL) {
4358 PyObject *mnemo, *key;
4359 key = PyLong_FromLong(libcode->code);
4360 mnemo = PyUnicode_FromString(libcode->library);
4361 if (key == NULL || mnemo == NULL)
4362 return;
4363 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4364 return;
4365 Py_DECREF(key);
4366 Py_DECREF(mnemo);
4367 libcode++;
4368 }
4369 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4370 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004371
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004372 /* OpenSSL version */
4373 /* SSLeay() gives us the version of the library linked against,
4374 which could be different from the headers version.
4375 */
4376 libver = SSLeay();
4377 r = PyLong_FromUnsignedLong(libver);
4378 if (r == NULL)
4379 return;
4380 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4381 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004382 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004383 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4384 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4385 return;
4386 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4387 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4388 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004389
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004390 libver = OPENSSL_VERSION_NUMBER;
4391 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4392 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4393 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4394 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004395}