blob: 45a1d0123109eba71fe2638bdcffa29402c4cb1c [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 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001129
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001130 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001131 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001132
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001133 lst = PyList_New(0);
1134 if (lst == NULL)
1135 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001136
1137 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1138 DIST_POINT *dp;
1139 STACK_OF(GENERAL_NAME) *gns;
1140
1141 dp = sk_DIST_POINT_value(dps, i);
1142 gns = dp->distpoint->name.fullname;
1143
1144 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1145 GENERAL_NAME *gn;
1146 ASN1_IA5STRING *uri;
1147 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001148 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001149
1150 gn = sk_GENERAL_NAME_value(gns, j);
1151 if (gn->type != GEN_URI) {
1152 continue;
1153 }
1154 uri = gn->d.uniformResourceIdentifier;
1155 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1156 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001157 if (ouri == NULL)
1158 goto done;
1159
1160 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001161 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001162 if (err < 0)
1163 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001164 }
1165 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001166
1167 /* Convert to tuple. */
1168 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1169
1170 done:
1171 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001172 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001173 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001174}
1175
1176static PyObject *
1177_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001178
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001179 PyObject *retval = NULL;
1180 BIO *biobuf = NULL;
1181 PyObject *peer;
1182 PyObject *peer_alt_names = NULL;
1183 PyObject *issuer;
1184 PyObject *version;
1185 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001186 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001187 ASN1_INTEGER *serialNumber;
1188 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001189 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001190 ASN1_TIME *notBefore, *notAfter;
1191 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001192
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001193 retval = PyDict_New();
1194 if (retval == NULL)
1195 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001196
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001197 peer = _create_tuple_for_X509_NAME(
1198 X509_get_subject_name(certificate));
1199 if (peer == NULL)
1200 goto fail0;
1201 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1202 Py_DECREF(peer);
1203 goto fail0;
1204 }
1205 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001206
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001207 issuer = _create_tuple_for_X509_NAME(
1208 X509_get_issuer_name(certificate));
1209 if (issuer == NULL)
1210 goto fail0;
1211 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001212 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001213 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001214 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001215 Py_DECREF(issuer);
1216
1217 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1218 if (version == NULL)
1219 goto fail0;
1220 if (PyDict_SetItemString(retval, "version", version) < 0) {
1221 Py_DECREF(version);
1222 goto fail0;
1223 }
1224 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001225
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001226 /* get a memory buffer */
1227 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001228
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001229 (void) BIO_reset(biobuf);
1230 serialNumber = X509_get_serialNumber(certificate);
1231 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1232 i2a_ASN1_INTEGER(biobuf, serialNumber);
1233 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1234 if (len < 0) {
1235 _setSSLError(NULL, 0, __FILE__, __LINE__);
1236 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001237 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001238 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1239 if (sn_obj == NULL)
1240 goto fail1;
1241 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1242 Py_DECREF(sn_obj);
1243 goto fail1;
1244 }
1245 Py_DECREF(sn_obj);
1246
1247 (void) BIO_reset(biobuf);
1248 notBefore = X509_get_notBefore(certificate);
1249 ASN1_TIME_print(biobuf, notBefore);
1250 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1251 if (len < 0) {
1252 _setSSLError(NULL, 0, __FILE__, __LINE__);
1253 goto fail1;
1254 }
1255 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1256 if (pnotBefore == NULL)
1257 goto fail1;
1258 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1259 Py_DECREF(pnotBefore);
1260 goto fail1;
1261 }
1262 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001263
1264 (void) BIO_reset(biobuf);
1265 notAfter = X509_get_notAfter(certificate);
1266 ASN1_TIME_print(biobuf, notAfter);
1267 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1268 if (len < 0) {
1269 _setSSLError(NULL, 0, __FILE__, __LINE__);
1270 goto fail1;
1271 }
1272 pnotAfter = PyString_FromStringAndSize(buf, len);
1273 if (pnotAfter == NULL)
1274 goto fail1;
1275 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1276 Py_DECREF(pnotAfter);
1277 goto fail1;
1278 }
1279 Py_DECREF(pnotAfter);
1280
1281 /* Now look for subjectAltName */
1282
1283 peer_alt_names = _get_peer_alt_names(certificate);
1284 if (peer_alt_names == NULL)
1285 goto fail1;
1286 else if (peer_alt_names != Py_None) {
1287 if (PyDict_SetItemString(retval, "subjectAltName",
1288 peer_alt_names) < 0) {
1289 Py_DECREF(peer_alt_names);
1290 goto fail1;
1291 }
1292 Py_DECREF(peer_alt_names);
1293 }
1294
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001295 /* Authority Information Access: OCSP URIs */
1296 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1297 if (obj == NULL) {
1298 goto fail1;
1299 } else if (obj != Py_None) {
1300 result = PyDict_SetItemString(retval, "OCSP", obj);
1301 Py_DECREF(obj);
1302 if (result < 0) {
1303 goto fail1;
1304 }
1305 }
1306
1307 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1308 if (obj == NULL) {
1309 goto fail1;
1310 } else if (obj != Py_None) {
1311 result = PyDict_SetItemString(retval, "caIssuers", obj);
1312 Py_DECREF(obj);
1313 if (result < 0) {
1314 goto fail1;
1315 }
1316 }
1317
1318 /* CDP (CRL distribution points) */
1319 obj = _get_crl_dp(certificate);
1320 if (obj == NULL) {
1321 goto fail1;
1322 } else if (obj != Py_None) {
1323 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1324 Py_DECREF(obj);
1325 if (result < 0) {
1326 goto fail1;
1327 }
1328 }
1329
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001330 BIO_free(biobuf);
1331 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001332
1333 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001334 if (biobuf != NULL)
1335 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001336 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001337 Py_XDECREF(retval);
1338 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001339}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001340
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001341static PyObject *
1342_certificate_to_der(X509 *certificate)
1343{
1344 unsigned char *bytes_buf = NULL;
1345 int len;
1346 PyObject *retval;
1347
1348 bytes_buf = NULL;
1349 len = i2d_X509(certificate, &bytes_buf);
1350 if (len < 0) {
1351 _setSSLError(NULL, 0, __FILE__, __LINE__);
1352 return NULL;
1353 }
1354 /* this is actually an immutable bytes sequence */
1355 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1356 OPENSSL_free(bytes_buf);
1357 return retval;
1358}
Bill Janssen98d19da2007-09-10 21:51:02 +00001359
1360static PyObject *
1361PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1362
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001363 PyObject *retval = NULL;
1364 char *filename = NULL;
1365 X509 *x=NULL;
1366 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001367
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001368 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001369 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001370
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001371 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001372 PyErr_SetString(PySSLErrorObject,
1373 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001374 goto fail0;
1375 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001376
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001377 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001378 PyErr_SetString(PySSLErrorObject,
1379 "Can't open 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 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1384 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001385 PyErr_SetString(PySSLErrorObject,
1386 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001387 goto fail0;
1388 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001389
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001390 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001391 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001392
1393 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001394
1395 if (cert != NULL) BIO_free(cert);
1396 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001397}
1398
1399
1400static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001401PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001402{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001403 int verification;
1404 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001405 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001406
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001407 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1408 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001409
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001410 if (!self->handshake_done) {
1411 PyErr_SetString(PyExc_ValueError,
1412 "handshake not done yet");
1413 return NULL;
1414 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001415 if (!self->peer_cert)
1416 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001417
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001418 b = PyObject_IsTrue(binary_mode);
1419 if (b < 0)
1420 return NULL;
1421 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001422 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001423 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001424 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001425 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001426 if ((verification & SSL_VERIFY_PEER) == 0)
1427 return PyDict_New();
1428 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001429 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001430 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001431}
1432
1433PyDoc_STRVAR(PySSL_peercert_doc,
1434"peer_certificate([der=False]) -> certificate\n\
1435\n\
1436Returns the certificate for the peer. If no certificate was provided,\n\
1437returns None. If a certificate was provided, but not validated, returns\n\
1438an empty dictionary. Otherwise returns a dict containing information\n\
1439about the peer certificate.\n\
1440\n\
1441If the optional argument is True, returns a DER-encoded copy of the\n\
1442peer certificate, or None if no certificate was provided. This will\n\
1443return the certificate even if it wasn't validated.");
1444
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001445static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001446
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001447 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001448 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001449 char *cipher_name;
1450 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001453 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001454 current = SSL_get_current_cipher(self->ssl);
1455 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001456 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001457
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001458 retval = PyTuple_New(3);
1459 if (retval == NULL)
1460 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001461
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001462 cipher_name = (char *) SSL_CIPHER_get_name(current);
1463 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001464 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001465 PyTuple_SET_ITEM(retval, 0, Py_None);
1466 } else {
1467 v = PyString_FromString(cipher_name);
1468 if (v == NULL)
1469 goto fail0;
1470 PyTuple_SET_ITEM(retval, 0, v);
1471 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001472 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001473 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001474 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001475 PyTuple_SET_ITEM(retval, 1, Py_None);
1476 } else {
1477 v = PyString_FromString(cipher_protocol);
1478 if (v == NULL)
1479 goto fail0;
1480 PyTuple_SET_ITEM(retval, 1, v);
1481 }
1482 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1483 if (v == NULL)
1484 goto fail0;
1485 PyTuple_SET_ITEM(retval, 2, v);
1486 return retval;
1487
Bill Janssen98d19da2007-09-10 21:51:02 +00001488 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001489 Py_DECREF(retval);
1490 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001491}
1492
Alex Gaynore98205d2014-09-04 13:33:22 -07001493static PyObject *PySSL_version(PySSLSocket *self)
1494{
1495 const char *version;
1496
1497 if (self->ssl == NULL)
1498 Py_RETURN_NONE;
1499 version = SSL_get_version(self->ssl);
1500 if (!strcmp(version, "unknown"))
1501 Py_RETURN_NONE;
1502 return PyUnicode_FromString(version);
1503}
1504
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001505#ifdef OPENSSL_NPN_NEGOTIATED
1506static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1507 const unsigned char *out;
1508 unsigned int outlen;
1509
1510 SSL_get0_next_proto_negotiated(self->ssl,
1511 &out, &outlen);
1512
1513 if (out == NULL)
1514 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001515 return PyString_FromStringAndSize((char *)out, outlen);
1516}
1517#endif
1518
1519#ifdef HAVE_ALPN
1520static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1521 const unsigned char *out;
1522 unsigned int outlen;
1523
1524 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1525
1526 if (out == NULL)
1527 Py_RETURN_NONE;
1528 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001529}
1530#endif
1531
1532static PyObject *PySSL_compression(PySSLSocket *self) {
1533#ifdef OPENSSL_NO_COMP
1534 Py_RETURN_NONE;
1535#else
1536 const COMP_METHOD *comp_method;
1537 const char *short_name;
1538
1539 if (self->ssl == NULL)
1540 Py_RETURN_NONE;
1541 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001542 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001543 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001544 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001545 if (short_name == NULL)
1546 Py_RETURN_NONE;
1547 return PyBytes_FromString(short_name);
1548#endif
1549}
1550
1551static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1552 Py_INCREF(self->ctx);
1553 return self->ctx;
1554}
1555
1556static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1557 void *closure) {
1558
1559 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1560#if !HAVE_SNI
1561 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1562 "context is not supported by your OpenSSL library");
1563 return -1;
1564#else
1565 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001566 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001567 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1568#endif
1569 } else {
1570 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1571 return -1;
1572 }
1573
1574 return 0;
1575}
1576
1577PyDoc_STRVAR(PySSL_set_context_doc,
1578"_setter_context(ctx)\n\
1579\
1580This changes the context associated with the SSLSocket. This is typically\n\
1581used from within a callback function set by the set_servername_callback\n\
1582on the SSLContext to change the certificate information associated with the\n\
1583SSLSocket before the cryptographic exchange handshake messages\n");
1584
1585
1586
1587static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001589 if (self->peer_cert) /* Possible not to have one? */
1590 X509_free (self->peer_cert);
1591 if (self->ssl)
1592 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001593 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001594 Py_XDECREF(self->ssl_sock);
1595 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001596 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001597}
1598
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001599/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001600 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001601 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001602 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001603
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001604static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001605check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001606{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001607 fd_set fds;
1608 struct timeval tv;
1609 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001610
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001611 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1612 if (s->sock_timeout < 0.0)
1613 return SOCKET_IS_BLOCKING;
1614 else if (s->sock_timeout == 0.0)
1615 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001616
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001617 /* Guard against closed socket */
1618 if (s->sock_fd < 0)
1619 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001620
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001621 /* Prefer poll, if available, since you can poll() any fd
1622 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001623#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001624 {
1625 struct pollfd pollfd;
1626 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001627
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001628 pollfd.fd = s->sock_fd;
1629 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001630
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001631 /* s->sock_timeout is in seconds, timeout in ms */
1632 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1633 PySSL_BEGIN_ALLOW_THREADS
1634 rc = poll(&pollfd, 1, timeout);
1635 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001636
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001637 goto normal_return;
1638 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001639#endif
1640
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001641 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001642 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001643 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001644
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001645 /* Construct the arguments to select */
1646 tv.tv_sec = (int)s->sock_timeout;
1647 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1648 FD_ZERO(&fds);
1649 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001650
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001651 /* See if the socket is ready */
1652 PySSL_BEGIN_ALLOW_THREADS
1653 if (writing)
1654 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1655 else
1656 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1657 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001658
Bill Janssen934b16d2008-06-28 22:19:33 +00001659#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001660normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001661#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001662 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1663 (when we are able to write or when there's something to read) */
1664 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001665}
1666
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001667static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001668{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001669 Py_buffer buf;
1670 int len;
1671 int sockstate;
1672 int err;
1673 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001674 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001676 Py_INCREF(sock);
1677
1678 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1679 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001680 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001681 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001682
Victor Stinnerc1a44262013-06-25 00:48:02 +02001683 if (buf.len > INT_MAX) {
1684 PyErr_Format(PyExc_OverflowError,
1685 "string longer than %d bytes", INT_MAX);
1686 goto error;
1687 }
1688
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001689 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001691 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1692 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001693
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001694 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001695 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1696 PyErr_SetString(PySSLErrorObject,
1697 "The write operation timed out");
1698 goto error;
1699 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1700 PyErr_SetString(PySSLErrorObject,
1701 "Underlying socket has been closed.");
1702 goto error;
1703 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1704 PyErr_SetString(PySSLErrorObject,
1705 "Underlying socket too large for select().");
1706 goto error;
1707 }
1708 do {
1709 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001710 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001711 err = SSL_get_error(self->ssl, len);
1712 PySSL_END_ALLOW_THREADS
1713 if (PyErr_CheckSignals()) {
1714 goto error;
1715 }
1716 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001717 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001719 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 } else {
1721 sockstate = SOCKET_OPERATION_OK;
1722 }
1723 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1724 PyErr_SetString(PySSLErrorObject,
1725 "The write operation timed out");
1726 goto error;
1727 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1728 PyErr_SetString(PySSLErrorObject,
1729 "Underlying socket has been closed.");
1730 goto error;
1731 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1732 break;
1733 }
1734 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001735
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001736 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001737 PyBuffer_Release(&buf);
1738 if (len > 0)
1739 return PyInt_FromLong(len);
1740 else
1741 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001742
1743error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001744 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001745 PyBuffer_Release(&buf);
1746 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747}
1748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750"write(s) -> len\n\
1751\n\
1752Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001755static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001756{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001757 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001758
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001759 PySSL_BEGIN_ALLOW_THREADS
1760 count = SSL_pending(self->ssl);
1761 PySSL_END_ALLOW_THREADS
1762 if (count < 0)
1763 return PySSL_SetError(self, count, __FILE__, __LINE__);
1764 else
1765 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001766}
1767
1768PyDoc_STRVAR(PySSL_SSLpending_doc,
1769"pending() -> count\n\
1770\n\
1771Returns the number of already decrypted bytes available for read,\n\
1772pending on the connection.\n");
1773
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001774static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001775{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001776 PyObject *dest = NULL;
1777 Py_buffer buf;
1778 char *mem;
1779 int len, count;
1780 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001781 int sockstate;
1782 int err;
1783 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001784 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001785
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001786 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001788 buf.obj = NULL;
1789 buf.buf = NULL;
1790 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1791 goto error;
1792
1793 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001794 if (len < 0) {
1795 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1796 goto error;
1797 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001798 dest = PyBytes_FromStringAndSize(NULL, len);
1799 if (dest == NULL)
1800 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001801 if (len == 0) {
1802 Py_XDECREF(sock);
1803 return dest;
1804 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001805 mem = PyBytes_AS_STRING(dest);
1806 }
1807 else {
1808 buf_passed = 1;
1809 mem = buf.buf;
1810 if (len <= 0 || len > buf.len) {
1811 len = (int) buf.len;
1812 if (buf.len != len) {
1813 PyErr_SetString(PyExc_OverflowError,
1814 "maximum length can't fit in a C 'int'");
1815 goto error;
1816 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001817 if (len == 0) {
1818 count = 0;
1819 goto done;
1820 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001821 }
1822 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001823
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001824 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001825 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001826 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1827 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001828
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001829 do {
1830 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001831 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001832 err = SSL_get_error(self->ssl, count);
1833 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001834 if (PyErr_CheckSignals())
1835 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001836 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001837 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001838 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001840 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1841 (SSL_get_shutdown(self->ssl) ==
1842 SSL_RECEIVED_SHUTDOWN))
1843 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844 count = 0;
1845 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001846 } else {
1847 sockstate = SOCKET_OPERATION_OK;
1848 }
1849 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1850 PyErr_SetString(PySSLErrorObject,
1851 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001852 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001853 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1854 break;
1855 }
1856 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1857 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858 PySSL_SetError(self, count, __FILE__, __LINE__);
1859 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001860 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001861
1862done:
1863 Py_DECREF(sock);
1864 if (!buf_passed) {
1865 _PyBytes_Resize(&dest, count);
1866 return dest;
1867 }
1868 else {
1869 PyBuffer_Release(&buf);
1870 return PyLong_FromLong(count);
1871 }
1872
1873error:
1874 Py_DECREF(sock);
1875 if (!buf_passed)
1876 Py_XDECREF(dest);
1877 else
1878 PyBuffer_Release(&buf);
1879 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001880}
1881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001882PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001883"read([len]) -> string\n\
1884\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001885Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001886
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001887static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001888{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001889 int err, ssl_err, sockstate, nonblocking;
1890 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001891 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001893 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001894 if (sock->sock_fd < 0) {
1895 _setSSLError("Underlying socket connection gone",
1896 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001897 return NULL;
1898 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001899 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001900
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001901 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001902 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001903 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1904 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001905
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001906 while (1) {
1907 PySSL_BEGIN_ALLOW_THREADS
1908 /* Disable read-ahead so that unwrap can work correctly.
1909 * Otherwise OpenSSL might read in too much data,
1910 * eating clear text data that happens to be
1911 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001912 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001913 * function is used and the shutdown_seen_zero != 0
1914 * condition is met.
1915 */
1916 if (self->shutdown_seen_zero)
1917 SSL_set_read_ahead(self->ssl, 0);
1918 err = SSL_shutdown(self->ssl);
1919 PySSL_END_ALLOW_THREADS
1920 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1921 if (err > 0)
1922 break;
1923 if (err == 0) {
1924 /* Don't loop endlessly; instead preserve legacy
1925 behaviour of trying SSL_shutdown() only twice.
1926 This looks necessary for OpenSSL < 0.9.8m */
1927 if (++zeros > 1)
1928 break;
1929 /* Shutdown was sent, now try receiving */
1930 self->shutdown_seen_zero = 1;
1931 continue;
1932 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001933
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001934 /* Possibly retry shutdown until timeout or failure */
1935 ssl_err = SSL_get_error(self->ssl, err);
1936 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001937 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001938 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001939 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001940 else
1941 break;
1942 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1943 if (ssl_err == SSL_ERROR_WANT_READ)
1944 PyErr_SetString(PySSLErrorObject,
1945 "The read operation timed out");
1946 else
1947 PyErr_SetString(PySSLErrorObject,
1948 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001949 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001950 }
1951 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1952 PyErr_SetString(PySSLErrorObject,
1953 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001954 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001955 }
1956 else if (sockstate != SOCKET_OPERATION_OK)
1957 /* Retain the SSL error code */
1958 break;
1959 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001960
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001961 if (err < 0) {
1962 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001963 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001964 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001965 else
1966 /* It's already INCREF'ed */
1967 return (PyObject *) sock;
1968
1969error:
1970 Py_DECREF(sock);
1971 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001972}
1973
1974PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1975"shutdown(s) -> socket\n\
1976\n\
1977Does the SSL shutdown handshake with the remote end, and returns\n\
1978the underlying socket object.");
1979
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001980#if HAVE_OPENSSL_FINISHED
1981static PyObject *
1982PySSL_tls_unique_cb(PySSLSocket *self)
1983{
1984 PyObject *retval = NULL;
1985 char buf[PySSL_CB_MAXLEN];
1986 size_t len;
1987
1988 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1989 /* if session is resumed XOR we are the client */
1990 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1991 }
1992 else {
1993 /* if a new session XOR we are the server */
1994 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1995 }
1996
1997 /* It cannot be negative in current OpenSSL version as of July 2011 */
1998 if (len == 0)
1999 Py_RETURN_NONE;
2000
2001 retval = PyBytes_FromStringAndSize(buf, len);
2002
2003 return retval;
2004}
2005
2006PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2007"tls_unique_cb() -> bytes\n\
2008\n\
2009Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2010\n\
2011If the TLS handshake is not yet complete, None is returned");
2012
2013#endif /* HAVE_OPENSSL_FINISHED */
2014
2015static PyGetSetDef ssl_getsetlist[] = {
2016 {"context", (getter) PySSL_get_context,
2017 (setter) PySSL_set_context, PySSL_set_context_doc},
2018 {NULL}, /* sentinel */
2019};
2020
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002021static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002022 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2023 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2024 PySSL_SSLwrite_doc},
2025 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2026 PySSL_SSLread_doc},
2027 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2028 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002029 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2030 PySSL_peercert_doc},
2031 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002032 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002033#ifdef OPENSSL_NPN_NEGOTIATED
2034 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2035#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002036#ifdef HAVE_ALPN
2037 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2038#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002039 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002040 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2041 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002042#if HAVE_OPENSSL_FINISHED
2043 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2044 PySSL_tls_unique_cb_doc},
2045#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002046 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002047};
2048
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002049static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002050 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002051 "_ssl._SSLSocket", /*tp_name*/
2052 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002053 0, /*tp_itemsize*/
2054 /* methods */
2055 (destructor)PySSL_dealloc, /*tp_dealloc*/
2056 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002057 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002058 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002059 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002060 0, /*tp_repr*/
2061 0, /*tp_as_number*/
2062 0, /*tp_as_sequence*/
2063 0, /*tp_as_mapping*/
2064 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002065 0, /*tp_call*/
2066 0, /*tp_str*/
2067 0, /*tp_getattro*/
2068 0, /*tp_setattro*/
2069 0, /*tp_as_buffer*/
2070 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2071 0, /*tp_doc*/
2072 0, /*tp_traverse*/
2073 0, /*tp_clear*/
2074 0, /*tp_richcompare*/
2075 0, /*tp_weaklistoffset*/
2076 0, /*tp_iter*/
2077 0, /*tp_iternext*/
2078 PySSLMethods, /*tp_methods*/
2079 0, /*tp_members*/
2080 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002081};
2082
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002083
2084/*
2085 * _SSLContext objects
2086 */
2087
2088static PyObject *
2089context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2090{
2091 char *kwlist[] = {"protocol", NULL};
2092 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002093 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002094 long options;
2095 SSL_CTX *ctx = NULL;
2096
2097 if (!PyArg_ParseTupleAndKeywords(
2098 args, kwds, "i:_SSLContext", kwlist,
2099 &proto_version))
2100 return NULL;
2101
2102 PySSL_BEGIN_ALLOW_THREADS
2103 if (proto_version == PY_SSL_VERSION_TLS1)
2104 ctx = SSL_CTX_new(TLSv1_method());
2105#if HAVE_TLSv1_2
2106 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2107 ctx = SSL_CTX_new(TLSv1_1_method());
2108 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2109 ctx = SSL_CTX_new(TLSv1_2_method());
2110#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002111#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002112 else if (proto_version == PY_SSL_VERSION_SSL3)
2113 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002114#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002115#ifndef OPENSSL_NO_SSL2
2116 else if (proto_version == PY_SSL_VERSION_SSL2)
2117 ctx = SSL_CTX_new(SSLv2_method());
2118#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002119 else if (proto_version == PY_SSL_VERSION_TLS)
2120 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002121 else
2122 proto_version = -1;
2123 PySSL_END_ALLOW_THREADS
2124
2125 if (proto_version == -1) {
2126 PyErr_SetString(PyExc_ValueError,
2127 "invalid protocol version");
2128 return NULL;
2129 }
2130 if (ctx == NULL) {
2131 PyErr_SetString(PySSLErrorObject,
2132 "failed to allocate SSL context");
2133 return NULL;
2134 }
2135
2136 assert(type != NULL && type->tp_alloc != NULL);
2137 self = (PySSLContext *) type->tp_alloc(type, 0);
2138 if (self == NULL) {
2139 SSL_CTX_free(ctx);
2140 return NULL;
2141 }
2142 self->ctx = ctx;
2143#ifdef OPENSSL_NPN_NEGOTIATED
2144 self->npn_protocols = NULL;
2145#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002146#ifdef HAVE_ALPN
2147 self->alpn_protocols = NULL;
2148#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002149#ifndef OPENSSL_NO_TLSEXT
2150 self->set_hostname = NULL;
2151#endif
2152 /* Don't check host name by default */
2153 self->check_hostname = 0;
2154 /* Defaults */
2155 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2156 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2157 if (proto_version != PY_SSL_VERSION_SSL2)
2158 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002159 if (proto_version != PY_SSL_VERSION_SSL3)
2160 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002161 SSL_CTX_set_options(self->ctx, options);
2162
Donald Stufftf1a696e2017-03-02 12:37:07 -05002163#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002164 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2165 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002166 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2167 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002168#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002169 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2170#else
2171 {
2172 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2173 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2174 EC_KEY_free(key);
2175 }
2176#endif
2177#endif
2178
2179#define SID_CTX "Python"
2180 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2181 sizeof(SID_CTX));
2182#undef SID_CTX
2183
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002184#ifdef X509_V_FLAG_TRUSTED_FIRST
2185 {
2186 /* Improve trust chain building when cross-signed intermediate
2187 certificates are present. See https://bugs.python.org/issue23476. */
2188 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2189 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2190 }
2191#endif
2192
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002193 return (PyObject *)self;
2194}
2195
2196static int
2197context_traverse(PySSLContext *self, visitproc visit, void *arg)
2198{
2199#ifndef OPENSSL_NO_TLSEXT
2200 Py_VISIT(self->set_hostname);
2201#endif
2202 return 0;
2203}
2204
2205static int
2206context_clear(PySSLContext *self)
2207{
2208#ifndef OPENSSL_NO_TLSEXT
2209 Py_CLEAR(self->set_hostname);
2210#endif
2211 return 0;
2212}
2213
2214static void
2215context_dealloc(PySSLContext *self)
2216{
2217 context_clear(self);
2218 SSL_CTX_free(self->ctx);
2219#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002220 PyMem_FREE(self->npn_protocols);
2221#endif
2222#ifdef HAVE_ALPN
2223 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002224#endif
2225 Py_TYPE(self)->tp_free(self);
2226}
2227
2228static PyObject *
2229set_ciphers(PySSLContext *self, PyObject *args)
2230{
2231 int ret;
2232 const char *cipherlist;
2233
2234 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2235 return NULL;
2236 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2237 if (ret == 0) {
2238 /* Clearing the error queue is necessary on some OpenSSL versions,
2239 otherwise the error will be reported again when another SSL call
2240 is done. */
2241 ERR_clear_error();
2242 PyErr_SetString(PySSLErrorObject,
2243 "No cipher can be selected.");
2244 return NULL;
2245 }
2246 Py_RETURN_NONE;
2247}
2248
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002249#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002250static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002251do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2252 const unsigned char *server_protocols, unsigned int server_protocols_len,
2253 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002254{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002255 int ret;
2256 if (client_protocols == NULL) {
2257 client_protocols = (unsigned char *)"";
2258 client_protocols_len = 0;
2259 }
2260 if (server_protocols == NULL) {
2261 server_protocols = (unsigned char *)"";
2262 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002263 }
2264
Benjamin Petersonaa707582015-01-23 17:30:26 -05002265 ret = SSL_select_next_proto(out, outlen,
2266 server_protocols, server_protocols_len,
2267 client_protocols, client_protocols_len);
2268 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2269 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002270
2271 return SSL_TLSEXT_ERR_OK;
2272}
2273
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002274/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2275static int
2276_advertiseNPN_cb(SSL *s,
2277 const unsigned char **data, unsigned int *len,
2278 void *args)
2279{
2280 PySSLContext *ssl_ctx = (PySSLContext *) args;
2281
2282 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002283 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002284 *len = 0;
2285 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002286 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002287 *len = ssl_ctx->npn_protocols_len;
2288 }
2289
2290 return SSL_TLSEXT_ERR_OK;
2291}
2292/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2293static int
2294_selectNPN_cb(SSL *s,
2295 unsigned char **out, unsigned char *outlen,
2296 const unsigned char *server, unsigned int server_len,
2297 void *args)
2298{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002299 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002300 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002301 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002302}
2303#endif
2304
2305static PyObject *
2306_set_npn_protocols(PySSLContext *self, PyObject *args)
2307{
2308#ifdef OPENSSL_NPN_NEGOTIATED
2309 Py_buffer protos;
2310
2311 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2312 return NULL;
2313
2314 if (self->npn_protocols != NULL) {
2315 PyMem_Free(self->npn_protocols);
2316 }
2317
2318 self->npn_protocols = PyMem_Malloc(protos.len);
2319 if (self->npn_protocols == NULL) {
2320 PyBuffer_Release(&protos);
2321 return PyErr_NoMemory();
2322 }
2323 memcpy(self->npn_protocols, protos.buf, protos.len);
2324 self->npn_protocols_len = (int) protos.len;
2325
2326 /* set both server and client callbacks, because the context can
2327 * be used to create both types of sockets */
2328 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2329 _advertiseNPN_cb,
2330 self);
2331 SSL_CTX_set_next_proto_select_cb(self->ctx,
2332 _selectNPN_cb,
2333 self);
2334
2335 PyBuffer_Release(&protos);
2336 Py_RETURN_NONE;
2337#else
2338 PyErr_SetString(PyExc_NotImplementedError,
2339 "The NPN extension requires OpenSSL 1.0.1 or later.");
2340 return NULL;
2341#endif
2342}
2343
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002344#ifdef HAVE_ALPN
2345static int
2346_selectALPN_cb(SSL *s,
2347 const unsigned char **out, unsigned char *outlen,
2348 const unsigned char *client_protocols, unsigned int client_protocols_len,
2349 void *args)
2350{
2351 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002352 return do_protocol_selection(1, (unsigned char **)out, outlen,
2353 ctx->alpn_protocols, ctx->alpn_protocols_len,
2354 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002355}
2356#endif
2357
2358static PyObject *
2359_set_alpn_protocols(PySSLContext *self, PyObject *args)
2360{
2361#ifdef HAVE_ALPN
2362 Py_buffer protos;
2363
2364 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2365 return NULL;
2366
2367 PyMem_FREE(self->alpn_protocols);
2368 self->alpn_protocols = PyMem_Malloc(protos.len);
2369 if (!self->alpn_protocols)
2370 return PyErr_NoMemory();
2371 memcpy(self->alpn_protocols, protos.buf, protos.len);
2372 self->alpn_protocols_len = protos.len;
2373 PyBuffer_Release(&protos);
2374
2375 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2376 return PyErr_NoMemory();
2377 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2378
2379 PyBuffer_Release(&protos);
2380 Py_RETURN_NONE;
2381#else
2382 PyErr_SetString(PyExc_NotImplementedError,
2383 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2384 return NULL;
2385#endif
2386}
2387
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002388static PyObject *
2389get_verify_mode(PySSLContext *self, void *c)
2390{
2391 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2392 case SSL_VERIFY_NONE:
2393 return PyLong_FromLong(PY_SSL_CERT_NONE);
2394 case SSL_VERIFY_PEER:
2395 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2396 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2397 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2398 }
2399 PyErr_SetString(PySSLErrorObject,
2400 "invalid return value from SSL_CTX_get_verify_mode");
2401 return NULL;
2402}
2403
2404static int
2405set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2406{
2407 int n, mode;
2408 if (!PyArg_Parse(arg, "i", &n))
2409 return -1;
2410 if (n == PY_SSL_CERT_NONE)
2411 mode = SSL_VERIFY_NONE;
2412 else if (n == PY_SSL_CERT_OPTIONAL)
2413 mode = SSL_VERIFY_PEER;
2414 else if (n == PY_SSL_CERT_REQUIRED)
2415 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2416 else {
2417 PyErr_SetString(PyExc_ValueError,
2418 "invalid value for verify_mode");
2419 return -1;
2420 }
2421 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2422 PyErr_SetString(PyExc_ValueError,
2423 "Cannot set verify_mode to CERT_NONE when "
2424 "check_hostname is enabled.");
2425 return -1;
2426 }
2427 SSL_CTX_set_verify(self->ctx, mode, NULL);
2428 return 0;
2429}
2430
2431#ifdef HAVE_OPENSSL_VERIFY_PARAM
2432static PyObject *
2433get_verify_flags(PySSLContext *self, void *c)
2434{
2435 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002436 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002437 unsigned long flags;
2438
2439 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002440 param = X509_STORE_get0_param(store);
2441 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002442 return PyLong_FromUnsignedLong(flags);
2443}
2444
2445static int
2446set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2447{
2448 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002449 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002450 unsigned long new_flags, flags, set, clear;
2451
2452 if (!PyArg_Parse(arg, "k", &new_flags))
2453 return -1;
2454 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002455 param = X509_STORE_get0_param(store);
2456 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002457 clear = flags & ~new_flags;
2458 set = ~flags & new_flags;
2459 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002460 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002461 _setSSLError(NULL, 0, __FILE__, __LINE__);
2462 return -1;
2463 }
2464 }
2465 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002466 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002467 _setSSLError(NULL, 0, __FILE__, __LINE__);
2468 return -1;
2469 }
2470 }
2471 return 0;
2472}
2473#endif
2474
2475static PyObject *
2476get_options(PySSLContext *self, void *c)
2477{
2478 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2479}
2480
2481static int
2482set_options(PySSLContext *self, PyObject *arg, void *c)
2483{
2484 long new_opts, opts, set, clear;
2485 if (!PyArg_Parse(arg, "l", &new_opts))
2486 return -1;
2487 opts = SSL_CTX_get_options(self->ctx);
2488 clear = opts & ~new_opts;
2489 set = ~opts & new_opts;
2490 if (clear) {
2491#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2492 SSL_CTX_clear_options(self->ctx, clear);
2493#else
2494 PyErr_SetString(PyExc_ValueError,
2495 "can't clear options before OpenSSL 0.9.8m");
2496 return -1;
2497#endif
2498 }
2499 if (set)
2500 SSL_CTX_set_options(self->ctx, set);
2501 return 0;
2502}
2503
2504static PyObject *
2505get_check_hostname(PySSLContext *self, void *c)
2506{
2507 return PyBool_FromLong(self->check_hostname);
2508}
2509
2510static int
2511set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2512{
2513 PyObject *py_check_hostname;
2514 int check_hostname;
2515 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2516 return -1;
2517
2518 check_hostname = PyObject_IsTrue(py_check_hostname);
2519 if (check_hostname < 0)
2520 return -1;
2521 if (check_hostname &&
2522 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2523 PyErr_SetString(PyExc_ValueError,
2524 "check_hostname needs a SSL context with either "
2525 "CERT_OPTIONAL or CERT_REQUIRED");
2526 return -1;
2527 }
2528 self->check_hostname = check_hostname;
2529 return 0;
2530}
2531
2532
2533typedef struct {
2534 PyThreadState *thread_state;
2535 PyObject *callable;
2536 char *password;
2537 int size;
2538 int error;
2539} _PySSLPasswordInfo;
2540
2541static int
2542_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2543 const char *bad_type_error)
2544{
2545 /* Set the password and size fields of a _PySSLPasswordInfo struct
2546 from a unicode, bytes, or byte array object.
2547 The password field will be dynamically allocated and must be freed
2548 by the caller */
2549 PyObject *password_bytes = NULL;
2550 const char *data = NULL;
2551 Py_ssize_t size;
2552
2553 if (PyUnicode_Check(password)) {
2554 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2555 if (!password_bytes) {
2556 goto error;
2557 }
2558 data = PyBytes_AS_STRING(password_bytes);
2559 size = PyBytes_GET_SIZE(password_bytes);
2560 } else if (PyBytes_Check(password)) {
2561 data = PyBytes_AS_STRING(password);
2562 size = PyBytes_GET_SIZE(password);
2563 } else if (PyByteArray_Check(password)) {
2564 data = PyByteArray_AS_STRING(password);
2565 size = PyByteArray_GET_SIZE(password);
2566 } else {
2567 PyErr_SetString(PyExc_TypeError, bad_type_error);
2568 goto error;
2569 }
2570
2571 if (size > (Py_ssize_t)INT_MAX) {
2572 PyErr_Format(PyExc_ValueError,
2573 "password cannot be longer than %d bytes", INT_MAX);
2574 goto error;
2575 }
2576
2577 PyMem_Free(pw_info->password);
2578 pw_info->password = PyMem_Malloc(size);
2579 if (!pw_info->password) {
2580 PyErr_SetString(PyExc_MemoryError,
2581 "unable to allocate password buffer");
2582 goto error;
2583 }
2584 memcpy(pw_info->password, data, size);
2585 pw_info->size = (int)size;
2586
2587 Py_XDECREF(password_bytes);
2588 return 1;
2589
2590error:
2591 Py_XDECREF(password_bytes);
2592 return 0;
2593}
2594
2595static int
2596_password_callback(char *buf, int size, int rwflag, void *userdata)
2597{
2598 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2599 PyObject *fn_ret = NULL;
2600
2601 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2602
2603 if (pw_info->callable) {
2604 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2605 if (!fn_ret) {
2606 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2607 core python API, so we could use it to add a frame here */
2608 goto error;
2609 }
2610
2611 if (!_pwinfo_set(pw_info, fn_ret,
2612 "password callback must return a string")) {
2613 goto error;
2614 }
2615 Py_CLEAR(fn_ret);
2616 }
2617
2618 if (pw_info->size > size) {
2619 PyErr_Format(PyExc_ValueError,
2620 "password cannot be longer than %d bytes", size);
2621 goto error;
2622 }
2623
2624 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2625 memcpy(buf, pw_info->password, pw_info->size);
2626 return pw_info->size;
2627
2628error:
2629 Py_XDECREF(fn_ret);
2630 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2631 pw_info->error = 1;
2632 return -1;
2633}
2634
2635static PyObject *
2636load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2637{
2638 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002639 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2640 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002641 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2642 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002643 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2644 int r;
2645
2646 errno = 0;
2647 ERR_clear_error();
2648 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002649 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002650 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002651 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002652 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002653
2654 if (keyfile && keyfile != Py_None) {
2655 if (PyString_Check(keyfile)) {
2656 Py_INCREF(keyfile);
2657 keyfile_bytes = keyfile;
2658 } else {
2659 PyObject *u = PyUnicode_FromObject(keyfile);
2660 if (!u)
2661 goto error;
2662 keyfile_bytes = PyUnicode_AsEncodedString(
2663 u, Py_FileSystemDefaultEncoding, NULL);
2664 Py_DECREF(u);
2665 if (!keyfile_bytes)
2666 goto error;
2667 }
2668 }
2669
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002670 if (password && password != Py_None) {
2671 if (PyCallable_Check(password)) {
2672 pw_info.callable = password;
2673 } else if (!_pwinfo_set(&pw_info, password,
2674 "password should be a string or callable")) {
2675 goto error;
2676 }
2677 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2678 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2679 }
2680 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2681 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2682 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2683 if (r != 1) {
2684 if (pw_info.error) {
2685 ERR_clear_error();
2686 /* the password callback has already set the error information */
2687 }
2688 else if (errno != 0) {
2689 ERR_clear_error();
2690 PyErr_SetFromErrno(PyExc_IOError);
2691 }
2692 else {
2693 _setSSLError(NULL, 0, __FILE__, __LINE__);
2694 }
2695 goto error;
2696 }
2697 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2698 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002699 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002700 SSL_FILETYPE_PEM);
2701 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2702 if (r != 1) {
2703 if (pw_info.error) {
2704 ERR_clear_error();
2705 /* the password callback has already set the error information */
2706 }
2707 else if (errno != 0) {
2708 ERR_clear_error();
2709 PyErr_SetFromErrno(PyExc_IOError);
2710 }
2711 else {
2712 _setSSLError(NULL, 0, __FILE__, __LINE__);
2713 }
2714 goto error;
2715 }
2716 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2717 r = SSL_CTX_check_private_key(self->ctx);
2718 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2719 if (r != 1) {
2720 _setSSLError(NULL, 0, __FILE__, __LINE__);
2721 goto error;
2722 }
2723 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2724 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002725 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002726 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002727 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002728 Py_RETURN_NONE;
2729
2730error:
2731 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2732 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002733 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002734 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002735 PyMem_Free(certfile_bytes);
2736 return NULL;
2737}
2738
2739/* internal helper function, returns -1 on error
2740 */
2741static int
2742_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2743 int filetype)
2744{
2745 BIO *biobuf = NULL;
2746 X509_STORE *store;
2747 int retval = 0, err, loaded = 0;
2748
2749 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2750
2751 if (len <= 0) {
2752 PyErr_SetString(PyExc_ValueError,
2753 "Empty certificate data");
2754 return -1;
2755 } else if (len > INT_MAX) {
2756 PyErr_SetString(PyExc_OverflowError,
2757 "Certificate data is too long.");
2758 return -1;
2759 }
2760
2761 biobuf = BIO_new_mem_buf(data, (int)len);
2762 if (biobuf == NULL) {
2763 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2764 return -1;
2765 }
2766
2767 store = SSL_CTX_get_cert_store(self->ctx);
2768 assert(store != NULL);
2769
2770 while (1) {
2771 X509 *cert = NULL;
2772 int r;
2773
2774 if (filetype == SSL_FILETYPE_ASN1) {
2775 cert = d2i_X509_bio(biobuf, NULL);
2776 } else {
2777 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002778 SSL_CTX_get_default_passwd_cb(self->ctx),
2779 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2780 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002781 }
2782 if (cert == NULL) {
2783 break;
2784 }
2785 r = X509_STORE_add_cert(store, cert);
2786 X509_free(cert);
2787 if (!r) {
2788 err = ERR_peek_last_error();
2789 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2790 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2791 /* cert already in hash table, not an error */
2792 ERR_clear_error();
2793 } else {
2794 break;
2795 }
2796 }
2797 loaded++;
2798 }
2799
2800 err = ERR_peek_last_error();
2801 if ((filetype == SSL_FILETYPE_ASN1) &&
2802 (loaded > 0) &&
2803 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2804 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2805 /* EOF ASN1 file, not an error */
2806 ERR_clear_error();
2807 retval = 0;
2808 } else if ((filetype == SSL_FILETYPE_PEM) &&
2809 (loaded > 0) &&
2810 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2811 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2812 /* EOF PEM file, not an error */
2813 ERR_clear_error();
2814 retval = 0;
2815 } else {
2816 _setSSLError(NULL, 0, __FILE__, __LINE__);
2817 retval = -1;
2818 }
2819
2820 BIO_free(biobuf);
2821 return retval;
2822}
2823
2824
2825static PyObject *
2826load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2827{
2828 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2829 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2830 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2831 const char *cafile_buf = NULL, *capath_buf = NULL;
2832 int r = 0, ok = 1;
2833
2834 errno = 0;
2835 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2836 "|OOO:load_verify_locations", kwlist,
2837 &cafile, &capath, &cadata))
2838 return NULL;
2839
2840 if (cafile == Py_None)
2841 cafile = NULL;
2842 if (capath == Py_None)
2843 capath = NULL;
2844 if (cadata == Py_None)
2845 cadata = NULL;
2846
2847 if (cafile == NULL && capath == NULL && cadata == NULL) {
2848 PyErr_SetString(PyExc_TypeError,
2849 "cafile, capath and cadata cannot be all omitted");
2850 goto error;
2851 }
2852
2853 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002854 if (PyString_Check(cafile)) {
2855 Py_INCREF(cafile);
2856 cafile_bytes = cafile;
2857 } else {
2858 PyObject *u = PyUnicode_FromObject(cafile);
2859 if (!u)
2860 goto error;
2861 cafile_bytes = PyUnicode_AsEncodedString(
2862 u, Py_FileSystemDefaultEncoding, NULL);
2863 Py_DECREF(u);
2864 if (!cafile_bytes)
2865 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002866 }
2867 }
2868 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002869 if (PyString_Check(capath)) {
2870 Py_INCREF(capath);
2871 capath_bytes = capath;
2872 } else {
2873 PyObject *u = PyUnicode_FromObject(capath);
2874 if (!u)
2875 goto error;
2876 capath_bytes = PyUnicode_AsEncodedString(
2877 u, Py_FileSystemDefaultEncoding, NULL);
2878 Py_DECREF(u);
2879 if (!capath_bytes)
2880 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002881 }
2882 }
2883
2884 /* validata cadata type and load cadata */
2885 if (cadata) {
2886 Py_buffer buf;
2887 PyObject *cadata_ascii = NULL;
2888
2889 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2890 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2891 PyBuffer_Release(&buf);
2892 PyErr_SetString(PyExc_TypeError,
2893 "cadata should be a contiguous buffer with "
2894 "a single dimension");
2895 goto error;
2896 }
2897 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2898 PyBuffer_Release(&buf);
2899 if (r == -1) {
2900 goto error;
2901 }
2902 } else {
2903 PyErr_Clear();
2904 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2905 if (cadata_ascii == NULL) {
2906 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002907 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002908 "bytes-like object");
2909 goto error;
2910 }
2911 r = _add_ca_certs(self,
2912 PyBytes_AS_STRING(cadata_ascii),
2913 PyBytes_GET_SIZE(cadata_ascii),
2914 SSL_FILETYPE_PEM);
2915 Py_DECREF(cadata_ascii);
2916 if (r == -1) {
2917 goto error;
2918 }
2919 }
2920 }
2921
2922 /* load cafile or capath */
2923 if (cafile_bytes || capath_bytes) {
2924 if (cafile)
2925 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2926 if (capath)
2927 capath_buf = PyBytes_AS_STRING(capath_bytes);
2928 PySSL_BEGIN_ALLOW_THREADS
2929 r = SSL_CTX_load_verify_locations(
2930 self->ctx,
2931 cafile_buf,
2932 capath_buf);
2933 PySSL_END_ALLOW_THREADS
2934 if (r != 1) {
2935 ok = 0;
2936 if (errno != 0) {
2937 ERR_clear_error();
2938 PyErr_SetFromErrno(PyExc_IOError);
2939 }
2940 else {
2941 _setSSLError(NULL, 0, __FILE__, __LINE__);
2942 }
2943 goto error;
2944 }
2945 }
2946 goto end;
2947
2948 error:
2949 ok = 0;
2950 end:
2951 Py_XDECREF(cafile_bytes);
2952 Py_XDECREF(capath_bytes);
2953 if (ok) {
2954 Py_RETURN_NONE;
2955 } else {
2956 return NULL;
2957 }
2958}
2959
2960static PyObject *
2961load_dh_params(PySSLContext *self, PyObject *filepath)
2962{
2963 BIO *bio;
2964 DH *dh;
2965 char *path = PyBytes_AsString(filepath);
2966 if (!path) {
2967 return NULL;
2968 }
2969
2970 bio = BIO_new_file(path, "r");
2971 if (bio == NULL) {
2972 ERR_clear_error();
2973 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2974 return NULL;
2975 }
2976 errno = 0;
2977 PySSL_BEGIN_ALLOW_THREADS
2978 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2979 BIO_free(bio);
2980 PySSL_END_ALLOW_THREADS
2981 if (dh == NULL) {
2982 if (errno != 0) {
2983 ERR_clear_error();
2984 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2985 }
2986 else {
2987 _setSSLError(NULL, 0, __FILE__, __LINE__);
2988 }
2989 return NULL;
2990 }
2991 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2992 _setSSLError(NULL, 0, __FILE__, __LINE__);
2993 DH_free(dh);
2994 Py_RETURN_NONE;
2995}
2996
2997static PyObject *
2998context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2999{
3000 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3001 PySocketSockObject *sock;
3002 int server_side = 0;
3003 char *hostname = NULL;
3004 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3005
3006 /* server_hostname is either None (or absent), or to be encoded
3007 using the idna encoding. */
3008 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3009 PySocketModule.Sock_Type,
3010 &sock, &server_side,
3011 Py_TYPE(Py_None), &hostname_obj,
3012 &ssl_sock)) {
3013 PyErr_Clear();
3014 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3015 PySocketModule.Sock_Type,
3016 &sock, &server_side,
3017 "idna", &hostname, &ssl_sock))
3018 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003019 }
3020
3021 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3022 hostname, ssl_sock);
3023 if (hostname != NULL)
3024 PyMem_Free(hostname);
3025 return res;
3026}
3027
3028static PyObject *
3029session_stats(PySSLContext *self, PyObject *unused)
3030{
3031 int r;
3032 PyObject *value, *stats = PyDict_New();
3033 if (!stats)
3034 return NULL;
3035
3036#define ADD_STATS(SSL_NAME, KEY_NAME) \
3037 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3038 if (value == NULL) \
3039 goto error; \
3040 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3041 Py_DECREF(value); \
3042 if (r < 0) \
3043 goto error;
3044
3045 ADD_STATS(number, "number");
3046 ADD_STATS(connect, "connect");
3047 ADD_STATS(connect_good, "connect_good");
3048 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3049 ADD_STATS(accept, "accept");
3050 ADD_STATS(accept_good, "accept_good");
3051 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3052 ADD_STATS(accept, "accept");
3053 ADD_STATS(hits, "hits");
3054 ADD_STATS(misses, "misses");
3055 ADD_STATS(timeouts, "timeouts");
3056 ADD_STATS(cache_full, "cache_full");
3057
3058#undef ADD_STATS
3059
3060 return stats;
3061
3062error:
3063 Py_DECREF(stats);
3064 return NULL;
3065}
3066
3067static PyObject *
3068set_default_verify_paths(PySSLContext *self, PyObject *unused)
3069{
3070 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3071 _setSSLError(NULL, 0, __FILE__, __LINE__);
3072 return NULL;
3073 }
3074 Py_RETURN_NONE;
3075}
3076
3077#ifndef OPENSSL_NO_ECDH
3078static PyObject *
3079set_ecdh_curve(PySSLContext *self, PyObject *name)
3080{
3081 char *name_bytes;
3082 int nid;
3083 EC_KEY *key;
3084
3085 name_bytes = PyBytes_AsString(name);
3086 if (!name_bytes) {
3087 return NULL;
3088 }
3089 nid = OBJ_sn2nid(name_bytes);
3090 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003091 PyObject *r = PyObject_Repr(name);
3092 if (!r)
3093 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003094 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003095 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3096 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003097 return NULL;
3098 }
3099 key = EC_KEY_new_by_curve_name(nid);
3100 if (key == NULL) {
3101 _setSSLError(NULL, 0, __FILE__, __LINE__);
3102 return NULL;
3103 }
3104 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3105 EC_KEY_free(key);
3106 Py_RETURN_NONE;
3107}
3108#endif
3109
3110#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3111static int
3112_servername_callback(SSL *s, int *al, void *args)
3113{
3114 int ret;
3115 PySSLContext *ssl_ctx = (PySSLContext *) args;
3116 PySSLSocket *ssl;
3117 PyObject *servername_o;
3118 PyObject *servername_idna;
3119 PyObject *result;
3120 /* The high-level ssl.SSLSocket object */
3121 PyObject *ssl_socket;
3122 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3123#ifdef WITH_THREAD
3124 PyGILState_STATE gstate = PyGILState_Ensure();
3125#endif
3126
3127 if (ssl_ctx->set_hostname == NULL) {
3128 /* remove race condition in this the call back while if removing the
3129 * callback is in progress */
3130#ifdef WITH_THREAD
3131 PyGILState_Release(gstate);
3132#endif
3133 return SSL_TLSEXT_ERR_OK;
3134 }
3135
3136 ssl = SSL_get_app_data(s);
3137 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003138 if (ssl->ssl_sock == NULL) {
3139 ssl_socket = Py_None;
3140 } else {
3141 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3142 Py_INCREF(ssl_socket);
3143 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003144 if (ssl_socket == Py_None) {
3145 goto error;
3146 }
3147
3148 if (servername == NULL) {
3149 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3150 Py_None, ssl_ctx, NULL);
3151 }
3152 else {
3153 servername_o = PyBytes_FromString(servername);
3154 if (servername_o == NULL) {
3155 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3156 goto error;
3157 }
3158 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3159 if (servername_idna == NULL) {
3160 PyErr_WriteUnraisable(servername_o);
3161 Py_DECREF(servername_o);
3162 goto error;
3163 }
3164 Py_DECREF(servername_o);
3165 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3166 servername_idna, ssl_ctx, NULL);
3167 Py_DECREF(servername_idna);
3168 }
3169 Py_DECREF(ssl_socket);
3170
3171 if (result == NULL) {
3172 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3173 *al = SSL_AD_HANDSHAKE_FAILURE;
3174 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3175 }
3176 else {
3177 if (result != Py_None) {
3178 *al = (int) PyLong_AsLong(result);
3179 if (PyErr_Occurred()) {
3180 PyErr_WriteUnraisable(result);
3181 *al = SSL_AD_INTERNAL_ERROR;
3182 }
3183 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3184 }
3185 else {
3186 ret = SSL_TLSEXT_ERR_OK;
3187 }
3188 Py_DECREF(result);
3189 }
3190
3191#ifdef WITH_THREAD
3192 PyGILState_Release(gstate);
3193#endif
3194 return ret;
3195
3196error:
3197 Py_DECREF(ssl_socket);
3198 *al = SSL_AD_INTERNAL_ERROR;
3199 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3200#ifdef WITH_THREAD
3201 PyGILState_Release(gstate);
3202#endif
3203 return ret;
3204}
3205#endif
3206
3207PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3208"set_servername_callback(method)\n\
3209\n\
3210This sets a callback that will be called when a server name is provided by\n\
3211the SSL/TLS client in the SNI extension.\n\
3212\n\
3213If the argument is None then the callback is disabled. The method is called\n\
3214with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3215See RFC 6066 for details of the SNI extension.");
3216
3217static PyObject *
3218set_servername_callback(PySSLContext *self, PyObject *args)
3219{
3220#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3221 PyObject *cb;
3222
3223 if (!PyArg_ParseTuple(args, "O", &cb))
3224 return NULL;
3225
3226 Py_CLEAR(self->set_hostname);
3227 if (cb == Py_None) {
3228 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3229 }
3230 else {
3231 if (!PyCallable_Check(cb)) {
3232 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3233 PyErr_SetString(PyExc_TypeError,
3234 "not a callable object");
3235 return NULL;
3236 }
3237 Py_INCREF(cb);
3238 self->set_hostname = cb;
3239 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3240 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3241 }
3242 Py_RETURN_NONE;
3243#else
3244 PyErr_SetString(PyExc_NotImplementedError,
3245 "The TLS extension servername callback, "
3246 "SSL_CTX_set_tlsext_servername_callback, "
3247 "is not in the current OpenSSL library.");
3248 return NULL;
3249#endif
3250}
3251
3252PyDoc_STRVAR(PySSL_get_stats_doc,
3253"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3254\n\
3255Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3256CA extension and certificate revocation lists inside the context's cert\n\
3257store.\n\
3258NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3259been used at least once.");
3260
3261static PyObject *
3262cert_store_stats(PySSLContext *self)
3263{
3264 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003265 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003266 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003267 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003268
3269 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003270 objs = X509_STORE_get0_objects(store);
3271 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3272 obj = sk_X509_OBJECT_value(objs, i);
3273 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003274 case X509_LU_X509:
3275 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003276 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003277 ca++;
3278 }
3279 break;
3280 case X509_LU_CRL:
3281 crl++;
3282 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003283 default:
3284 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3285 * As far as I can tell they are internal states and never
3286 * stored in a cert store */
3287 break;
3288 }
3289 }
3290 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3291 "x509_ca", ca);
3292}
3293
3294PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3295"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3296\n\
3297Returns a list of dicts with information of loaded CA certs. If the\n\
3298optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3299NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3300been used at least once.");
3301
3302static PyObject *
3303get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3304{
3305 char *kwlist[] = {"binary_form", NULL};
3306 X509_STORE *store;
3307 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003308 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003309 int i;
3310 int binary_mode = 0;
3311
3312 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3313 kwlist, &py_binary_mode)) {
3314 return NULL;
3315 }
3316 binary_mode = PyObject_IsTrue(py_binary_mode);
3317 if (binary_mode < 0) {
3318 return NULL;
3319 }
3320
3321 if ((rlist = PyList_New(0)) == NULL) {
3322 return NULL;
3323 }
3324
3325 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003326 objs = X509_STORE_get0_objects(store);
3327 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003328 X509_OBJECT *obj;
3329 X509 *cert;
3330
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003331 obj = sk_X509_OBJECT_value(objs, i);
3332 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003333 /* not a x509 cert */
3334 continue;
3335 }
3336 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003337 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003338 if (!X509_check_ca(cert)) {
3339 continue;
3340 }
3341 if (binary_mode) {
3342 ci = _certificate_to_der(cert);
3343 } else {
3344 ci = _decode_certificate(cert);
3345 }
3346 if (ci == NULL) {
3347 goto error;
3348 }
3349 if (PyList_Append(rlist, ci) == -1) {
3350 goto error;
3351 }
3352 Py_CLEAR(ci);
3353 }
3354 return rlist;
3355
3356 error:
3357 Py_XDECREF(ci);
3358 Py_XDECREF(rlist);
3359 return NULL;
3360}
3361
3362
3363static PyGetSetDef context_getsetlist[] = {
3364 {"check_hostname", (getter) get_check_hostname,
3365 (setter) set_check_hostname, NULL},
3366 {"options", (getter) get_options,
3367 (setter) set_options, NULL},
3368#ifdef HAVE_OPENSSL_VERIFY_PARAM
3369 {"verify_flags", (getter) get_verify_flags,
3370 (setter) set_verify_flags, NULL},
3371#endif
3372 {"verify_mode", (getter) get_verify_mode,
3373 (setter) set_verify_mode, NULL},
3374 {NULL}, /* sentinel */
3375};
3376
3377static struct PyMethodDef context_methods[] = {
3378 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3379 METH_VARARGS | METH_KEYWORDS, NULL},
3380 {"set_ciphers", (PyCFunction) set_ciphers,
3381 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003382 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3383 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003384 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3385 METH_VARARGS, NULL},
3386 {"load_cert_chain", (PyCFunction) load_cert_chain,
3387 METH_VARARGS | METH_KEYWORDS, NULL},
3388 {"load_dh_params", (PyCFunction) load_dh_params,
3389 METH_O, NULL},
3390 {"load_verify_locations", (PyCFunction) load_verify_locations,
3391 METH_VARARGS | METH_KEYWORDS, NULL},
3392 {"session_stats", (PyCFunction) session_stats,
3393 METH_NOARGS, NULL},
3394 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3395 METH_NOARGS, NULL},
3396#ifndef OPENSSL_NO_ECDH
3397 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3398 METH_O, NULL},
3399#endif
3400 {"set_servername_callback", (PyCFunction) set_servername_callback,
3401 METH_VARARGS, PySSL_set_servername_callback_doc},
3402 {"cert_store_stats", (PyCFunction) cert_store_stats,
3403 METH_NOARGS, PySSL_get_stats_doc},
3404 {"get_ca_certs", (PyCFunction) get_ca_certs,
3405 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3406 {NULL, NULL} /* sentinel */
3407};
3408
3409static PyTypeObject PySSLContext_Type = {
3410 PyVarObject_HEAD_INIT(NULL, 0)
3411 "_ssl._SSLContext", /*tp_name*/
3412 sizeof(PySSLContext), /*tp_basicsize*/
3413 0, /*tp_itemsize*/
3414 (destructor)context_dealloc, /*tp_dealloc*/
3415 0, /*tp_print*/
3416 0, /*tp_getattr*/
3417 0, /*tp_setattr*/
3418 0, /*tp_reserved*/
3419 0, /*tp_repr*/
3420 0, /*tp_as_number*/
3421 0, /*tp_as_sequence*/
3422 0, /*tp_as_mapping*/
3423 0, /*tp_hash*/
3424 0, /*tp_call*/
3425 0, /*tp_str*/
3426 0, /*tp_getattro*/
3427 0, /*tp_setattro*/
3428 0, /*tp_as_buffer*/
3429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3430 0, /*tp_doc*/
3431 (traverseproc) context_traverse, /*tp_traverse*/
3432 (inquiry) context_clear, /*tp_clear*/
3433 0, /*tp_richcompare*/
3434 0, /*tp_weaklistoffset*/
3435 0, /*tp_iter*/
3436 0, /*tp_iternext*/
3437 context_methods, /*tp_methods*/
3438 0, /*tp_members*/
3439 context_getsetlist, /*tp_getset*/
3440 0, /*tp_base*/
3441 0, /*tp_dict*/
3442 0, /*tp_descr_get*/
3443 0, /*tp_descr_set*/
3444 0, /*tp_dictoffset*/
3445 0, /*tp_init*/
3446 0, /*tp_alloc*/
3447 context_new, /*tp_new*/
3448};
3449
3450
3451
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003452#ifdef HAVE_OPENSSL_RAND
3453
3454/* helper routines for seeding the SSL PRNG */
3455static PyObject *
3456PySSL_RAND_add(PyObject *self, PyObject *args)
3457{
3458 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003459 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003460 double entropy;
3461
3462 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003463 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003464 do {
3465 if (len >= INT_MAX) {
3466 written = INT_MAX;
3467 } else {
3468 written = len;
3469 }
3470 RAND_add(buf, (int)written, entropy);
3471 buf += written;
3472 len -= written;
3473 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003474 Py_INCREF(Py_None);
3475 return Py_None;
3476}
3477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003478PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003479"RAND_add(string, entropy)\n\
3480\n\
3481Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003482bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003483
3484static PyObject *
3485PySSL_RAND_status(PyObject *self)
3486{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003487 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003488}
3489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003490PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003491"RAND_status() -> 0 or 1\n\
3492\n\
3493Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3494It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003495using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003496
Victor Stinner7c906672015-01-06 13:53:37 +01003497#endif /* HAVE_OPENSSL_RAND */
3498
3499
Benjamin Peterson42e10292016-07-07 00:02:31 -07003500#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003501
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003502static PyObject *
3503PySSL_RAND_egd(PyObject *self, PyObject *arg)
3504{
3505 int bytes;
3506
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003507 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003508 return PyErr_Format(PyExc_TypeError,
3509 "RAND_egd() expected string, found %s",
3510 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003511 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003512 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003513 PyErr_SetString(PySSLErrorObject,
3514 "EGD connection failed or EGD did not return "
3515 "enough data to seed the PRNG");
3516 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003517 }
3518 return PyInt_FromLong(bytes);
3519}
3520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003521PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003522"RAND_egd(path) -> bytes\n\
3523\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003524Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3525Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003526fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003527
Benjamin Peterson42e10292016-07-07 00:02:31 -07003528#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003529
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003530
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003531PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3532"get_default_verify_paths() -> tuple\n\
3533\n\
3534Return search paths and environment vars that are used by SSLContext's\n\
3535set_default_verify_paths() to load default CAs. The values are\n\
3536'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3537
3538static PyObject *
3539PySSL_get_default_verify_paths(PyObject *self)
3540{
3541 PyObject *ofile_env = NULL;
3542 PyObject *ofile = NULL;
3543 PyObject *odir_env = NULL;
3544 PyObject *odir = NULL;
3545
Benjamin Peterson65192c12015-07-18 10:59:13 -07003546#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003547 const char *tmp = (info); \
3548 target = NULL; \
3549 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3550 else { target = PyBytes_FromString(tmp); } \
3551 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003552 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003553
Benjamin Peterson65192c12015-07-18 10:59:13 -07003554 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3555 CONVERT(X509_get_default_cert_file(), ofile);
3556 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3557 CONVERT(X509_get_default_cert_dir(), odir);
3558#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003559
3560 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3561
3562 error:
3563 Py_XDECREF(ofile_env);
3564 Py_XDECREF(ofile);
3565 Py_XDECREF(odir_env);
3566 Py_XDECREF(odir);
3567 return NULL;
3568}
3569
3570static PyObject*
3571asn1obj2py(ASN1_OBJECT *obj)
3572{
3573 int nid;
3574 const char *ln, *sn;
3575 char buf[100];
3576 Py_ssize_t buflen;
3577
3578 nid = OBJ_obj2nid(obj);
3579 if (nid == NID_undef) {
3580 PyErr_Format(PyExc_ValueError, "Unknown object");
3581 return NULL;
3582 }
3583 sn = OBJ_nid2sn(nid);
3584 ln = OBJ_nid2ln(nid);
3585 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3586 if (buflen < 0) {
3587 _setSSLError(NULL, 0, __FILE__, __LINE__);
3588 return NULL;
3589 }
3590 if (buflen) {
3591 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3592 } else {
3593 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3594 }
3595}
3596
3597PyDoc_STRVAR(PySSL_txt2obj_doc,
3598"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3599\n\
3600Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3601objects are looked up by OID. With name=True short and long name are also\n\
3602matched.");
3603
3604static PyObject*
3605PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3606{
3607 char *kwlist[] = {"txt", "name", NULL};
3608 PyObject *result = NULL;
3609 char *txt;
3610 PyObject *pyname = Py_None;
3611 int name = 0;
3612 ASN1_OBJECT *obj;
3613
3614 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3615 kwlist, &txt, &pyname)) {
3616 return NULL;
3617 }
3618 name = PyObject_IsTrue(pyname);
3619 if (name < 0)
3620 return NULL;
3621 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3622 if (obj == NULL) {
3623 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3624 return NULL;
3625 }
3626 result = asn1obj2py(obj);
3627 ASN1_OBJECT_free(obj);
3628 return result;
3629}
3630
3631PyDoc_STRVAR(PySSL_nid2obj_doc,
3632"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3633\n\
3634Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3635
3636static PyObject*
3637PySSL_nid2obj(PyObject *self, PyObject *args)
3638{
3639 PyObject *result = NULL;
3640 int nid;
3641 ASN1_OBJECT *obj;
3642
3643 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3644 return NULL;
3645 }
3646 if (nid < NID_undef) {
3647 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3648 return NULL;
3649 }
3650 obj = OBJ_nid2obj(nid);
3651 if (obj == NULL) {
3652 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3653 return NULL;
3654 }
3655 result = asn1obj2py(obj);
3656 ASN1_OBJECT_free(obj);
3657 return result;
3658}
3659
3660#ifdef _MSC_VER
3661
3662static PyObject*
3663certEncodingType(DWORD encodingType)
3664{
3665 static PyObject *x509_asn = NULL;
3666 static PyObject *pkcs_7_asn = NULL;
3667
3668 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003669 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003670 if (x509_asn == NULL)
3671 return NULL;
3672 }
3673 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003674 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003675 if (pkcs_7_asn == NULL)
3676 return NULL;
3677 }
3678 switch(encodingType) {
3679 case X509_ASN_ENCODING:
3680 Py_INCREF(x509_asn);
3681 return x509_asn;
3682 case PKCS_7_ASN_ENCODING:
3683 Py_INCREF(pkcs_7_asn);
3684 return pkcs_7_asn;
3685 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003686 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003687 }
3688}
3689
3690static PyObject*
3691parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3692{
3693 CERT_ENHKEY_USAGE *usage;
3694 DWORD size, error, i;
3695 PyObject *retval;
3696
3697 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3698 error = GetLastError();
3699 if (error == CRYPT_E_NOT_FOUND) {
3700 Py_RETURN_TRUE;
3701 }
3702 return PyErr_SetFromWindowsErr(error);
3703 }
3704
3705 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3706 if (usage == NULL) {
3707 return PyErr_NoMemory();
3708 }
3709
3710 /* Now get the actual enhanced usage property */
3711 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3712 PyMem_Free(usage);
3713 error = GetLastError();
3714 if (error == CRYPT_E_NOT_FOUND) {
3715 Py_RETURN_TRUE;
3716 }
3717 return PyErr_SetFromWindowsErr(error);
3718 }
3719 retval = PySet_New(NULL);
3720 if (retval == NULL) {
3721 goto error;
3722 }
3723 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3724 if (usage->rgpszUsageIdentifier[i]) {
3725 PyObject *oid;
3726 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003727 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003728 if (oid == NULL) {
3729 Py_CLEAR(retval);
3730 goto error;
3731 }
3732 err = PySet_Add(retval, oid);
3733 Py_DECREF(oid);
3734 if (err == -1) {
3735 Py_CLEAR(retval);
3736 goto error;
3737 }
3738 }
3739 }
3740 error:
3741 PyMem_Free(usage);
3742 return retval;
3743}
3744
3745PyDoc_STRVAR(PySSL_enum_certificates_doc,
3746"enum_certificates(store_name) -> []\n\
3747\n\
3748Retrieve certificates from Windows' cert store. store_name may be one of\n\
3749'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3750The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3751encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3752PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3753boolean True.");
3754
3755static PyObject *
3756PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3757{
3758 char *kwlist[] = {"store_name", NULL};
3759 char *store_name;
3760 HCERTSTORE hStore = NULL;
3761 PCCERT_CONTEXT pCertCtx = NULL;
3762 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3763 PyObject *result = NULL;
3764
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003765 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003766 kwlist, &store_name)) {
3767 return NULL;
3768 }
3769 result = PyList_New(0);
3770 if (result == NULL) {
3771 return NULL;
3772 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003773 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3774 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3775 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003776 if (hStore == NULL) {
3777 Py_DECREF(result);
3778 return PyErr_SetFromWindowsErr(GetLastError());
3779 }
3780
3781 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3782 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3783 pCertCtx->cbCertEncoded);
3784 if (!cert) {
3785 Py_CLEAR(result);
3786 break;
3787 }
3788 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3789 Py_CLEAR(result);
3790 break;
3791 }
3792 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3793 if (keyusage == Py_True) {
3794 Py_DECREF(keyusage);
3795 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3796 }
3797 if (keyusage == NULL) {
3798 Py_CLEAR(result);
3799 break;
3800 }
3801 if ((tup = PyTuple_New(3)) == NULL) {
3802 Py_CLEAR(result);
3803 break;
3804 }
3805 PyTuple_SET_ITEM(tup, 0, cert);
3806 cert = NULL;
3807 PyTuple_SET_ITEM(tup, 1, enc);
3808 enc = NULL;
3809 PyTuple_SET_ITEM(tup, 2, keyusage);
3810 keyusage = NULL;
3811 if (PyList_Append(result, tup) < 0) {
3812 Py_CLEAR(result);
3813 break;
3814 }
3815 Py_CLEAR(tup);
3816 }
3817 if (pCertCtx) {
3818 /* loop ended with an error, need to clean up context manually */
3819 CertFreeCertificateContext(pCertCtx);
3820 }
3821
3822 /* In error cases cert, enc and tup may not be NULL */
3823 Py_XDECREF(cert);
3824 Py_XDECREF(enc);
3825 Py_XDECREF(keyusage);
3826 Py_XDECREF(tup);
3827
3828 if (!CertCloseStore(hStore, 0)) {
3829 /* This error case might shadow another exception.*/
3830 Py_XDECREF(result);
3831 return PyErr_SetFromWindowsErr(GetLastError());
3832 }
3833 return result;
3834}
3835
3836PyDoc_STRVAR(PySSL_enum_crls_doc,
3837"enum_crls(store_name) -> []\n\
3838\n\
3839Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3840'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3841The function returns a list of (bytes, encoding_type) tuples. The\n\
3842encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3843PKCS_7_ASN_ENCODING.");
3844
3845static PyObject *
3846PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3847{
3848 char *kwlist[] = {"store_name", NULL};
3849 char *store_name;
3850 HCERTSTORE hStore = NULL;
3851 PCCRL_CONTEXT pCrlCtx = NULL;
3852 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3853 PyObject *result = NULL;
3854
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003855 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003856 kwlist, &store_name)) {
3857 return NULL;
3858 }
3859 result = PyList_New(0);
3860 if (result == NULL) {
3861 return NULL;
3862 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003863 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3864 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3865 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003866 if (hStore == NULL) {
3867 Py_DECREF(result);
3868 return PyErr_SetFromWindowsErr(GetLastError());
3869 }
3870
3871 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3872 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3873 pCrlCtx->cbCrlEncoded);
3874 if (!crl) {
3875 Py_CLEAR(result);
3876 break;
3877 }
3878 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3879 Py_CLEAR(result);
3880 break;
3881 }
3882 if ((tup = PyTuple_New(2)) == NULL) {
3883 Py_CLEAR(result);
3884 break;
3885 }
3886 PyTuple_SET_ITEM(tup, 0, crl);
3887 crl = NULL;
3888 PyTuple_SET_ITEM(tup, 1, enc);
3889 enc = NULL;
3890
3891 if (PyList_Append(result, tup) < 0) {
3892 Py_CLEAR(result);
3893 break;
3894 }
3895 Py_CLEAR(tup);
3896 }
3897 if (pCrlCtx) {
3898 /* loop ended with an error, need to clean up context manually */
3899 CertFreeCRLContext(pCrlCtx);
3900 }
3901
3902 /* In error cases cert, enc and tup may not be NULL */
3903 Py_XDECREF(crl);
3904 Py_XDECREF(enc);
3905 Py_XDECREF(tup);
3906
3907 if (!CertCloseStore(hStore, 0)) {
3908 /* This error case might shadow another exception.*/
3909 Py_XDECREF(result);
3910 return PyErr_SetFromWindowsErr(GetLastError());
3911 }
3912 return result;
3913}
3914
3915#endif /* _MSC_VER */
3916
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003917/* List of functions exported by this module. */
3918
3919static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003920 {"_test_decode_cert", PySSL_test_decode_certificate,
3921 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003922#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003923 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3924 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003925 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3926 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003927#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003928#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003929 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3930 PySSL_RAND_egd_doc},
3931#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003932 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3933 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3934#ifdef _MSC_VER
3935 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3936 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3937 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3938 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3939#endif
3940 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3941 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3942 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3943 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003944 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003945};
3946
3947
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003948#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003949
3950/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003951 * of the Python C thread library
3952 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3953 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003954
3955static PyThread_type_lock *_ssl_locks = NULL;
3956
Christian Heimes10107812013-08-19 17:36:29 +02003957#if OPENSSL_VERSION_NUMBER >= 0x10000000
3958/* use new CRYPTO_THREADID API. */
3959static void
3960_ssl_threadid_callback(CRYPTO_THREADID *id)
3961{
3962 CRYPTO_THREADID_set_numeric(id,
3963 (unsigned long)PyThread_get_thread_ident());
3964}
3965#else
3966/* deprecated CRYPTO_set_id_callback() API. */
3967static unsigned long
3968_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003969 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003970}
Christian Heimes10107812013-08-19 17:36:29 +02003971#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003972
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003973static void _ssl_thread_locking_function
3974 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003975 /* this function is needed to perform locking on shared data
3976 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003977 structures that will be implicitly shared whenever multiple
3978 threads use OpenSSL.) Multi-threaded applications will
3979 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003980
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003981 locking_function() must be able to handle up to
3982 CRYPTO_num_locks() different mutex locks. It sets the n-th
3983 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003984
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003985 file and line are the file number of the function setting the
3986 lock. They can be useful for debugging.
3987 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003988
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003989 if ((_ssl_locks == NULL) ||
3990 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3991 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003992
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003993 if (mode & CRYPTO_LOCK) {
3994 PyThread_acquire_lock(_ssl_locks[n], 1);
3995 } else {
3996 PyThread_release_lock(_ssl_locks[n]);
3997 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003998}
3999
4000static int _setup_ssl_threads(void) {
4001
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004002 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004003
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004004 if (_ssl_locks == NULL) {
4005 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004006 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4007 if (_ssl_locks == NULL) {
4008 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004009 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004010 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004011 memset(_ssl_locks, 0,
4012 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004013 for (i = 0; i < _ssl_locks_count; i++) {
4014 _ssl_locks[i] = PyThread_allocate_lock();
4015 if (_ssl_locks[i] == NULL) {
4016 unsigned int j;
4017 for (j = 0; j < i; j++) {
4018 PyThread_free_lock(_ssl_locks[j]);
4019 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004020 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004021 return 0;
4022 }
4023 }
4024 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004025#if OPENSSL_VERSION_NUMBER >= 0x10000000
4026 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4027#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004028 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004029#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004030 }
4031 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004032}
4033
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004034#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004036PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004037"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004038for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004039
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004040
4041
4042
4043static void
4044parse_openssl_version(unsigned long libver,
4045 unsigned int *major, unsigned int *minor,
4046 unsigned int *fix, unsigned int *patch,
4047 unsigned int *status)
4048{
4049 *status = libver & 0xF;
4050 libver >>= 4;
4051 *patch = libver & 0xFF;
4052 libver >>= 8;
4053 *fix = libver & 0xFF;
4054 libver >>= 8;
4055 *minor = libver & 0xFF;
4056 libver >>= 8;
4057 *major = libver & 0xFF;
4058}
4059
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004060PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004061init_ssl(void)
4062{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004063 PyObject *m, *d, *r;
4064 unsigned long libver;
4065 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004066 struct py_ssl_error_code *errcode;
4067 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004068
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004069 if (PyType_Ready(&PySSLContext_Type) < 0)
4070 return;
4071 if (PyType_Ready(&PySSLSocket_Type) < 0)
4072 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004073
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004074 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4075 if (m == NULL)
4076 return;
4077 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004078
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004079 /* Load _socket module and its C API */
4080 if (PySocketModule_ImportModuleAndAPI())
4081 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004082
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004083 /* Init OpenSSL */
4084 SSL_load_error_strings();
4085 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00004086#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004087#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004088 /* note that this will start threading if not already started */
4089 if (!_setup_ssl_threads()) {
4090 return;
4091 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004092#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4093 /* OpenSSL 1.1.0 builtin thread support is enabled */
4094 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004095#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004096#endif /* WITH_THREAD */
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004097 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004098
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004099 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004100 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4101 "ssl.SSLError", SSLError_doc,
4102 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004103 if (PySSLErrorObject == NULL)
4104 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004105 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4106
4107 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4108 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4109 PySSLErrorObject, NULL);
4110 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4111 "ssl.SSLWantReadError", SSLWantReadError_doc,
4112 PySSLErrorObject, NULL);
4113 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4114 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4115 PySSLErrorObject, NULL);
4116 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4117 "ssl.SSLSyscallError", SSLSyscallError_doc,
4118 PySSLErrorObject, NULL);
4119 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4120 "ssl.SSLEOFError", SSLEOFError_doc,
4121 PySSLErrorObject, NULL);
4122 if (PySSLZeroReturnErrorObject == NULL
4123 || PySSLWantReadErrorObject == NULL
4124 || PySSLWantWriteErrorObject == NULL
4125 || PySSLSyscallErrorObject == NULL
4126 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004127 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004128
4129 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4130 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4131 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4132 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4133 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4134
4135 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4136 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4137 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4138 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4139 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4140 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4141 return;
4142 if (PyDict_SetItemString(d, "_SSLContext",
4143 (PyObject *)&PySSLContext_Type) != 0)
4144 return;
4145 if (PyDict_SetItemString(d, "_SSLSocket",
4146 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004147 return;
4148 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4149 PY_SSL_ERROR_ZERO_RETURN);
4150 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4151 PY_SSL_ERROR_WANT_READ);
4152 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4153 PY_SSL_ERROR_WANT_WRITE);
4154 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4155 PY_SSL_ERROR_WANT_X509_LOOKUP);
4156 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4157 PY_SSL_ERROR_SYSCALL);
4158 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4159 PY_SSL_ERROR_SSL);
4160 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4161 PY_SSL_ERROR_WANT_CONNECT);
4162 /* non ssl.h errorcodes */
4163 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4164 PY_SSL_ERROR_EOF);
4165 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4166 PY_SSL_ERROR_INVALID_ERROR_CODE);
4167 /* cert requirements */
4168 PyModule_AddIntConstant(m, "CERT_NONE",
4169 PY_SSL_CERT_NONE);
4170 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4171 PY_SSL_CERT_OPTIONAL);
4172 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4173 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004174 /* CRL verification for verification_flags */
4175 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4176 0);
4177 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4178 X509_V_FLAG_CRL_CHECK);
4179 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4180 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4181 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4182 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004183#ifdef X509_V_FLAG_TRUSTED_FIRST
4184 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4185 X509_V_FLAG_TRUSTED_FIRST);
4186#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004187
4188 /* Alert Descriptions from ssl.h */
4189 /* note RESERVED constants no longer intended for use have been removed */
4190 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4191
4192#define ADD_AD_CONSTANT(s) \
4193 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4194 SSL_AD_##s)
4195
4196 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4197 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4198 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4199 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4200 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4201 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4202 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4203 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4204 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4205 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4206 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4207 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4208 ADD_AD_CONSTANT(UNKNOWN_CA);
4209 ADD_AD_CONSTANT(ACCESS_DENIED);
4210 ADD_AD_CONSTANT(DECODE_ERROR);
4211 ADD_AD_CONSTANT(DECRYPT_ERROR);
4212 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4213 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4214 ADD_AD_CONSTANT(INTERNAL_ERROR);
4215 ADD_AD_CONSTANT(USER_CANCELLED);
4216 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4217 /* Not all constants are in old OpenSSL versions */
4218#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4219 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4220#endif
4221#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4222 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4223#endif
4224#ifdef SSL_AD_UNRECOGNIZED_NAME
4225 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4226#endif
4227#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4228 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4229#endif
4230#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4231 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4232#endif
4233#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4234 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4235#endif
4236
4237#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004238
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004239 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004240#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004241 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4242 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004243#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004244#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004245 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4246 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004247#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004248 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004249 PY_SSL_VERSION_TLS);
4250 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4251 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004252 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4253 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004254#if HAVE_TLSv1_2
4255 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4256 PY_SSL_VERSION_TLS1_1);
4257 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4258 PY_SSL_VERSION_TLS1_2);
4259#endif
4260
4261 /* protocol options */
4262 PyModule_AddIntConstant(m, "OP_ALL",
4263 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4264 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4265 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4266 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4267#if HAVE_TLSv1_2
4268 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4269 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4270#endif
4271 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4272 SSL_OP_CIPHER_SERVER_PREFERENCE);
4273 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4274#ifdef SSL_OP_SINGLE_ECDH_USE
4275 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4276#endif
4277#ifdef SSL_OP_NO_COMPRESSION
4278 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4279 SSL_OP_NO_COMPRESSION);
4280#endif
4281
4282#if HAVE_SNI
4283 r = Py_True;
4284#else
4285 r = Py_False;
4286#endif
4287 Py_INCREF(r);
4288 PyModule_AddObject(m, "HAS_SNI", r);
4289
4290#if HAVE_OPENSSL_FINISHED
4291 r = Py_True;
4292#else
4293 r = Py_False;
4294#endif
4295 Py_INCREF(r);
4296 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4297
4298#ifdef OPENSSL_NO_ECDH
4299 r = Py_False;
4300#else
4301 r = Py_True;
4302#endif
4303 Py_INCREF(r);
4304 PyModule_AddObject(m, "HAS_ECDH", r);
4305
4306#ifdef OPENSSL_NPN_NEGOTIATED
4307 r = Py_True;
4308#else
4309 r = Py_False;
4310#endif
4311 Py_INCREF(r);
4312 PyModule_AddObject(m, "HAS_NPN", r);
4313
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004314#ifdef HAVE_ALPN
4315 r = Py_True;
4316#else
4317 r = Py_False;
4318#endif
4319 Py_INCREF(r);
4320 PyModule_AddObject(m, "HAS_ALPN", r);
4321
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004322 /* Mappings for error codes */
4323 err_codes_to_names = PyDict_New();
4324 err_names_to_codes = PyDict_New();
4325 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4326 return;
4327 errcode = error_codes;
4328 while (errcode->mnemonic != NULL) {
4329 PyObject *mnemo, *key;
4330 mnemo = PyUnicode_FromString(errcode->mnemonic);
4331 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4332 if (mnemo == NULL || key == NULL)
4333 return;
4334 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4335 return;
4336 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4337 return;
4338 Py_DECREF(key);
4339 Py_DECREF(mnemo);
4340 errcode++;
4341 }
4342 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4343 return;
4344 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4345 return;
4346
4347 lib_codes_to_names = PyDict_New();
4348 if (lib_codes_to_names == NULL)
4349 return;
4350 libcode = library_codes;
4351 while (libcode->library != NULL) {
4352 PyObject *mnemo, *key;
4353 key = PyLong_FromLong(libcode->code);
4354 mnemo = PyUnicode_FromString(libcode->library);
4355 if (key == NULL || mnemo == NULL)
4356 return;
4357 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4358 return;
4359 Py_DECREF(key);
4360 Py_DECREF(mnemo);
4361 libcode++;
4362 }
4363 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4364 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004365
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004366 /* OpenSSL version */
4367 /* SSLeay() gives us the version of the library linked against,
4368 which could be different from the headers version.
4369 */
4370 libver = SSLeay();
4371 r = PyLong_FromUnsignedLong(libver);
4372 if (r == NULL)
4373 return;
4374 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4375 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004376 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004377 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4378 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4379 return;
4380 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4381 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4382 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004383
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004384 libver = OPENSSL_VERSION_NUMBER;
4385 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4386 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4387 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4388 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004389}