blob: 589ea70a513fc7815727a470804d4a83265a85cf [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 Heimes88b174c2013-08-17 00:54:47 +0200956 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000957 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200958 switch (gntype) {
959 /* check for new general name type */
960 case GEN_OTHERNAME:
961 case GEN_X400:
962 case GEN_EDIPARTY:
963 case GEN_IPADD:
964 case GEN_RID:
965 break;
966 default:
967 if (PyErr_Warn(PyExc_RuntimeWarning,
968 "Unknown general name type") == -1) {
969 goto fail;
970 }
971 break;
972 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000973 (void) BIO_reset(biobuf);
974 GENERAL_NAME_print(biobuf, name);
975 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
976 if (len < 0) {
977 _setSSLError(NULL, 0, __FILE__, __LINE__);
978 goto fail;
979 }
980 vptr = strchr(buf, ':');
981 if (vptr == NULL)
982 goto fail;
983 t = PyTuple_New(2);
984 if (t == NULL)
985 goto fail;
986 v = PyString_FromStringAndSize(buf, (vptr - buf));
987 if (v == NULL) {
988 Py_DECREF(t);
989 goto fail;
990 }
991 PyTuple_SET_ITEM(t, 0, v);
992 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
993 if (v == NULL) {
994 Py_DECREF(t);
995 goto fail;
996 }
997 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200998 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000999 }
1000
1001 /* and add that rendering to the list */
1002
1003 if (PyList_Append(peer_alt_names, t) < 0) {
1004 Py_DECREF(t);
1005 goto fail;
1006 }
1007 Py_DECREF(t);
1008 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001009 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001010 }
1011 BIO_free(biobuf);
1012 if (peer_alt_names != Py_None) {
1013 v = PyList_AsTuple(peer_alt_names);
1014 Py_DECREF(peer_alt_names);
1015 return v;
1016 } else {
1017 return peer_alt_names;
1018 }
1019
Bill Janssen98d19da2007-09-10 21:51:02 +00001020
1021 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001022 if (biobuf != NULL)
1023 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001024
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001025 if (peer_alt_names != Py_None) {
1026 Py_XDECREF(peer_alt_names);
1027 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001028
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001029 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001030}
1031
1032static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001033_get_aia_uri(X509 *certificate, int nid) {
1034 PyObject *lst = NULL, *ostr = NULL;
1035 int i, result;
1036 AUTHORITY_INFO_ACCESS *info;
1037
1038 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001039 if (info == NULL)
1040 return Py_None;
1041 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1042 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001043 return Py_None;
1044 }
1045
1046 if ((lst = PyList_New(0)) == NULL) {
1047 goto fail;
1048 }
1049
1050 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1051 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1052 ASN1_IA5STRING *uri;
1053
1054 if ((OBJ_obj2nid(ad->method) != nid) ||
1055 (ad->location->type != GEN_URI)) {
1056 continue;
1057 }
1058 uri = ad->location->d.uniformResourceIdentifier;
1059 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1060 uri->length);
1061 if (ostr == NULL) {
1062 goto fail;
1063 }
1064 result = PyList_Append(lst, ostr);
1065 Py_DECREF(ostr);
1066 if (result < 0) {
1067 goto fail;
1068 }
1069 }
1070 AUTHORITY_INFO_ACCESS_free(info);
1071
1072 /* convert to tuple or None */
1073 if (PyList_Size(lst) == 0) {
1074 Py_DECREF(lst);
1075 return Py_None;
1076 } else {
1077 PyObject *tup;
1078 tup = PyList_AsTuple(lst);
1079 Py_DECREF(lst);
1080 return tup;
1081 }
1082
1083 fail:
1084 AUTHORITY_INFO_ACCESS_free(info);
1085 Py_XDECREF(lst);
1086 return NULL;
1087}
1088
1089static PyObject *
1090_get_crl_dp(X509 *certificate) {
1091 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001092 int i, j;
1093 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001094
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001095#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001096 /* Calls x509v3_cache_extensions and sets up crldp */
1097 X509_check_ca(certificate);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001098#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001099 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001100
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001101 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001102 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001103
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001104 lst = PyList_New(0);
1105 if (lst == NULL)
1106 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001107
1108 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1109 DIST_POINT *dp;
1110 STACK_OF(GENERAL_NAME) *gns;
1111
1112 dp = sk_DIST_POINT_value(dps, i);
1113 gns = dp->distpoint->name.fullname;
1114
1115 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1116 GENERAL_NAME *gn;
1117 ASN1_IA5STRING *uri;
1118 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001119 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001120
1121 gn = sk_GENERAL_NAME_value(gns, j);
1122 if (gn->type != GEN_URI) {
1123 continue;
1124 }
1125 uri = gn->d.uniformResourceIdentifier;
1126 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1127 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001128 if (ouri == NULL)
1129 goto done;
1130
1131 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001132 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001133 if (err < 0)
1134 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001135 }
1136 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001137
1138 /* Convert to tuple. */
1139 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1140
1141 done:
1142 Py_XDECREF(lst);
1143#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersonb1c1e672015-11-14 00:09:22 -08001144 sk_DIST_POINT_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001145#endif
1146 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001147}
1148
1149static PyObject *
1150_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001151
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001152 PyObject *retval = NULL;
1153 BIO *biobuf = NULL;
1154 PyObject *peer;
1155 PyObject *peer_alt_names = NULL;
1156 PyObject *issuer;
1157 PyObject *version;
1158 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001159 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001160 ASN1_INTEGER *serialNumber;
1161 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001162 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001163 ASN1_TIME *notBefore, *notAfter;
1164 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001165
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001166 retval = PyDict_New();
1167 if (retval == NULL)
1168 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001169
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001170 peer = _create_tuple_for_X509_NAME(
1171 X509_get_subject_name(certificate));
1172 if (peer == NULL)
1173 goto fail0;
1174 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1175 Py_DECREF(peer);
1176 goto fail0;
1177 }
1178 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001179
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001180 issuer = _create_tuple_for_X509_NAME(
1181 X509_get_issuer_name(certificate));
1182 if (issuer == NULL)
1183 goto fail0;
1184 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001185 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001186 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001187 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001188 Py_DECREF(issuer);
1189
1190 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1191 if (version == NULL)
1192 goto fail0;
1193 if (PyDict_SetItemString(retval, "version", version) < 0) {
1194 Py_DECREF(version);
1195 goto fail0;
1196 }
1197 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001198
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001199 /* get a memory buffer */
1200 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001201
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001202 (void) BIO_reset(biobuf);
1203 serialNumber = X509_get_serialNumber(certificate);
1204 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1205 i2a_ASN1_INTEGER(biobuf, serialNumber);
1206 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1207 if (len < 0) {
1208 _setSSLError(NULL, 0, __FILE__, __LINE__);
1209 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001210 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001211 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1212 if (sn_obj == NULL)
1213 goto fail1;
1214 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1215 Py_DECREF(sn_obj);
1216 goto fail1;
1217 }
1218 Py_DECREF(sn_obj);
1219
1220 (void) BIO_reset(biobuf);
1221 notBefore = X509_get_notBefore(certificate);
1222 ASN1_TIME_print(biobuf, notBefore);
1223 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1224 if (len < 0) {
1225 _setSSLError(NULL, 0, __FILE__, __LINE__);
1226 goto fail1;
1227 }
1228 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1229 if (pnotBefore == NULL)
1230 goto fail1;
1231 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1232 Py_DECREF(pnotBefore);
1233 goto fail1;
1234 }
1235 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001236
1237 (void) BIO_reset(biobuf);
1238 notAfter = X509_get_notAfter(certificate);
1239 ASN1_TIME_print(biobuf, notAfter);
1240 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1241 if (len < 0) {
1242 _setSSLError(NULL, 0, __FILE__, __LINE__);
1243 goto fail1;
1244 }
1245 pnotAfter = PyString_FromStringAndSize(buf, len);
1246 if (pnotAfter == NULL)
1247 goto fail1;
1248 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1249 Py_DECREF(pnotAfter);
1250 goto fail1;
1251 }
1252 Py_DECREF(pnotAfter);
1253
1254 /* Now look for subjectAltName */
1255
1256 peer_alt_names = _get_peer_alt_names(certificate);
1257 if (peer_alt_names == NULL)
1258 goto fail1;
1259 else if (peer_alt_names != Py_None) {
1260 if (PyDict_SetItemString(retval, "subjectAltName",
1261 peer_alt_names) < 0) {
1262 Py_DECREF(peer_alt_names);
1263 goto fail1;
1264 }
1265 Py_DECREF(peer_alt_names);
1266 }
1267
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001268 /* Authority Information Access: OCSP URIs */
1269 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1270 if (obj == NULL) {
1271 goto fail1;
1272 } else if (obj != Py_None) {
1273 result = PyDict_SetItemString(retval, "OCSP", obj);
1274 Py_DECREF(obj);
1275 if (result < 0) {
1276 goto fail1;
1277 }
1278 }
1279
1280 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1281 if (obj == NULL) {
1282 goto fail1;
1283 } else if (obj != Py_None) {
1284 result = PyDict_SetItemString(retval, "caIssuers", obj);
1285 Py_DECREF(obj);
1286 if (result < 0) {
1287 goto fail1;
1288 }
1289 }
1290
1291 /* CDP (CRL distribution points) */
1292 obj = _get_crl_dp(certificate);
1293 if (obj == NULL) {
1294 goto fail1;
1295 } else if (obj != Py_None) {
1296 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1297 Py_DECREF(obj);
1298 if (result < 0) {
1299 goto fail1;
1300 }
1301 }
1302
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001303 BIO_free(biobuf);
1304 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001305
1306 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001307 if (biobuf != NULL)
1308 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001309 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001310 Py_XDECREF(retval);
1311 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001312}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001313
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001314static PyObject *
1315_certificate_to_der(X509 *certificate)
1316{
1317 unsigned char *bytes_buf = NULL;
1318 int len;
1319 PyObject *retval;
1320
1321 bytes_buf = NULL;
1322 len = i2d_X509(certificate, &bytes_buf);
1323 if (len < 0) {
1324 _setSSLError(NULL, 0, __FILE__, __LINE__);
1325 return NULL;
1326 }
1327 /* this is actually an immutable bytes sequence */
1328 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1329 OPENSSL_free(bytes_buf);
1330 return retval;
1331}
Bill Janssen98d19da2007-09-10 21:51:02 +00001332
1333static PyObject *
1334PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1335
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001336 PyObject *retval = NULL;
1337 char *filename = NULL;
1338 X509 *x=NULL;
1339 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001340
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001341 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001342 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001343
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001344 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001345 PyErr_SetString(PySSLErrorObject,
1346 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001347 goto fail0;
1348 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001349
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001350 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001351 PyErr_SetString(PySSLErrorObject,
1352 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001353 goto fail0;
1354 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001355
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001356 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1357 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001358 PyErr_SetString(PySSLErrorObject,
1359 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001360 goto fail0;
1361 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001362
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001363 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001364 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001365
1366 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001367
1368 if (cert != NULL) BIO_free(cert);
1369 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001370}
1371
1372
1373static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001374PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001375{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001376 int verification;
1377 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001378 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001379
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001380 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1381 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001382
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001383 if (!self->handshake_done) {
1384 PyErr_SetString(PyExc_ValueError,
1385 "handshake not done yet");
1386 return NULL;
1387 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001388 if (!self->peer_cert)
1389 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001390
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001391 b = PyObject_IsTrue(binary_mode);
1392 if (b < 0)
1393 return NULL;
1394 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001395 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001396 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001397 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001398 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001399 if ((verification & SSL_VERIFY_PEER) == 0)
1400 return PyDict_New();
1401 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001402 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001403 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001404}
1405
1406PyDoc_STRVAR(PySSL_peercert_doc,
1407"peer_certificate([der=False]) -> certificate\n\
1408\n\
1409Returns the certificate for the peer. If no certificate was provided,\n\
1410returns None. If a certificate was provided, but not validated, returns\n\
1411an empty dictionary. Otherwise returns a dict containing information\n\
1412about the peer certificate.\n\
1413\n\
1414If the optional argument is True, returns a DER-encoded copy of the\n\
1415peer certificate, or None if no certificate was provided. This will\n\
1416return the certificate even if it wasn't validated.");
1417
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001418static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001419
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001420 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001421 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001422 char *cipher_name;
1423 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001424
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001425 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001426 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001427 current = SSL_get_current_cipher(self->ssl);
1428 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001429 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001430
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001431 retval = PyTuple_New(3);
1432 if (retval == NULL)
1433 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001434
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001435 cipher_name = (char *) SSL_CIPHER_get_name(current);
1436 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001437 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001438 PyTuple_SET_ITEM(retval, 0, Py_None);
1439 } else {
1440 v = PyString_FromString(cipher_name);
1441 if (v == NULL)
1442 goto fail0;
1443 PyTuple_SET_ITEM(retval, 0, v);
1444 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001445 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001446 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001447 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001448 PyTuple_SET_ITEM(retval, 1, Py_None);
1449 } else {
1450 v = PyString_FromString(cipher_protocol);
1451 if (v == NULL)
1452 goto fail0;
1453 PyTuple_SET_ITEM(retval, 1, v);
1454 }
1455 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1456 if (v == NULL)
1457 goto fail0;
1458 PyTuple_SET_ITEM(retval, 2, v);
1459 return retval;
1460
Bill Janssen98d19da2007-09-10 21:51:02 +00001461 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001462 Py_DECREF(retval);
1463 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001464}
1465
Alex Gaynore98205d2014-09-04 13:33:22 -07001466static PyObject *PySSL_version(PySSLSocket *self)
1467{
1468 const char *version;
1469
1470 if (self->ssl == NULL)
1471 Py_RETURN_NONE;
1472 version = SSL_get_version(self->ssl);
1473 if (!strcmp(version, "unknown"))
1474 Py_RETURN_NONE;
1475 return PyUnicode_FromString(version);
1476}
1477
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001478#ifdef OPENSSL_NPN_NEGOTIATED
1479static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1480 const unsigned char *out;
1481 unsigned int outlen;
1482
1483 SSL_get0_next_proto_negotiated(self->ssl,
1484 &out, &outlen);
1485
1486 if (out == NULL)
1487 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001488 return PyString_FromStringAndSize((char *)out, outlen);
1489}
1490#endif
1491
1492#ifdef HAVE_ALPN
1493static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1494 const unsigned char *out;
1495 unsigned int outlen;
1496
1497 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1498
1499 if (out == NULL)
1500 Py_RETURN_NONE;
1501 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001502}
1503#endif
1504
1505static PyObject *PySSL_compression(PySSLSocket *self) {
1506#ifdef OPENSSL_NO_COMP
1507 Py_RETURN_NONE;
1508#else
1509 const COMP_METHOD *comp_method;
1510 const char *short_name;
1511
1512 if (self->ssl == NULL)
1513 Py_RETURN_NONE;
1514 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001515 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001516 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001517 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001518 if (short_name == NULL)
1519 Py_RETURN_NONE;
1520 return PyBytes_FromString(short_name);
1521#endif
1522}
1523
1524static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1525 Py_INCREF(self->ctx);
1526 return self->ctx;
1527}
1528
1529static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1530 void *closure) {
1531
1532 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1533#if !HAVE_SNI
1534 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1535 "context is not supported by your OpenSSL library");
1536 return -1;
1537#else
1538 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001539 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001540 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1541#endif
1542 } else {
1543 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1544 return -1;
1545 }
1546
1547 return 0;
1548}
1549
1550PyDoc_STRVAR(PySSL_set_context_doc,
1551"_setter_context(ctx)\n\
1552\
1553This changes the context associated with the SSLSocket. This is typically\n\
1554used from within a callback function set by the set_servername_callback\n\
1555on the SSLContext to change the certificate information associated with the\n\
1556SSLSocket before the cryptographic exchange handshake messages\n");
1557
1558
1559
1560static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001561{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001562 if (self->peer_cert) /* Possible not to have one? */
1563 X509_free (self->peer_cert);
1564 if (self->ssl)
1565 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001566 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001567 Py_XDECREF(self->ssl_sock);
1568 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001569 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001570}
1571
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001572/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001573 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001574 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001575 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001576
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001577static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001578check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001579{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001580 fd_set fds;
1581 struct timeval tv;
1582 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001583
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001584 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1585 if (s->sock_timeout < 0.0)
1586 return SOCKET_IS_BLOCKING;
1587 else if (s->sock_timeout == 0.0)
1588 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001589
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001590 /* Guard against closed socket */
1591 if (s->sock_fd < 0)
1592 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001593
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001594 /* Prefer poll, if available, since you can poll() any fd
1595 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001596#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001597 {
1598 struct pollfd pollfd;
1599 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001600
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001601 pollfd.fd = s->sock_fd;
1602 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001603
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001604 /* s->sock_timeout is in seconds, timeout in ms */
1605 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1606 PySSL_BEGIN_ALLOW_THREADS
1607 rc = poll(&pollfd, 1, timeout);
1608 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001609
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001610 goto normal_return;
1611 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001612#endif
1613
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001614 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001615 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001616 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001617
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001618 /* Construct the arguments to select */
1619 tv.tv_sec = (int)s->sock_timeout;
1620 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1621 FD_ZERO(&fds);
1622 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001623
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001624 /* See if the socket is ready */
1625 PySSL_BEGIN_ALLOW_THREADS
1626 if (writing)
1627 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1628 else
1629 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1630 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001631
Bill Janssen934b16d2008-06-28 22:19:33 +00001632#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001633normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001634#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001635 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1636 (when we are able to write or when there's something to read) */
1637 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001638}
1639
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001640static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001641{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001642 Py_buffer buf;
1643 int len;
1644 int sockstate;
1645 int err;
1646 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001647 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001648
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001649 Py_INCREF(sock);
1650
1651 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1652 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001653 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001654 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001655
Victor Stinnerc1a44262013-06-25 00:48:02 +02001656 if (buf.len > INT_MAX) {
1657 PyErr_Format(PyExc_OverflowError,
1658 "string longer than %d bytes", INT_MAX);
1659 goto error;
1660 }
1661
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001662 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001663 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001664 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1665 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001666
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001667 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001668 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1669 PyErr_SetString(PySSLErrorObject,
1670 "The write operation timed out");
1671 goto error;
1672 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1673 PyErr_SetString(PySSLErrorObject,
1674 "Underlying socket has been closed.");
1675 goto error;
1676 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1677 PyErr_SetString(PySSLErrorObject,
1678 "Underlying socket too large for select().");
1679 goto error;
1680 }
1681 do {
1682 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001683 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001684 err = SSL_get_error(self->ssl, len);
1685 PySSL_END_ALLOW_THREADS
1686 if (PyErr_CheckSignals()) {
1687 goto error;
1688 }
1689 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001691 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001692 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001693 } else {
1694 sockstate = SOCKET_OPERATION_OK;
1695 }
1696 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1697 PyErr_SetString(PySSLErrorObject,
1698 "The write operation timed out");
1699 goto error;
1700 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1701 PyErr_SetString(PySSLErrorObject,
1702 "Underlying socket has been closed.");
1703 goto error;
1704 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1705 break;
1706 }
1707 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001708
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001709 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001710 PyBuffer_Release(&buf);
1711 if (len > 0)
1712 return PyInt_FromLong(len);
1713 else
1714 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001715
1716error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001717 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 PyBuffer_Release(&buf);
1719 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001720}
1721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001722PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001723"write(s) -> len\n\
1724\n\
1725Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001726of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001727
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001728static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001729{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001730 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001731
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001732 PySSL_BEGIN_ALLOW_THREADS
1733 count = SSL_pending(self->ssl);
1734 PySSL_END_ALLOW_THREADS
1735 if (count < 0)
1736 return PySSL_SetError(self, count, __FILE__, __LINE__);
1737 else
1738 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001739}
1740
1741PyDoc_STRVAR(PySSL_SSLpending_doc,
1742"pending() -> count\n\
1743\n\
1744Returns the number of already decrypted bytes available for read,\n\
1745pending on the connection.\n");
1746
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001747static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001748{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001749 PyObject *dest = NULL;
1750 Py_buffer buf;
1751 char *mem;
1752 int len, count;
1753 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001754 int sockstate;
1755 int err;
1756 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001757 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001759 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001761 buf.obj = NULL;
1762 buf.buf = NULL;
1763 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1764 goto error;
1765
1766 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001767 if (len < 0) {
1768 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1769 goto error;
1770 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001771 dest = PyBytes_FromStringAndSize(NULL, len);
1772 if (dest == NULL)
1773 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001774 if (len == 0) {
1775 Py_XDECREF(sock);
1776 return dest;
1777 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001778 mem = PyBytes_AS_STRING(dest);
1779 }
1780 else {
1781 buf_passed = 1;
1782 mem = buf.buf;
1783 if (len <= 0 || len > buf.len) {
1784 len = (int) buf.len;
1785 if (buf.len != len) {
1786 PyErr_SetString(PyExc_OverflowError,
1787 "maximum length can't fit in a C 'int'");
1788 goto error;
1789 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001790 if (len == 0) {
1791 count = 0;
1792 goto done;
1793 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001794 }
1795 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001796
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001797 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001798 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001799 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1800 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001801
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001802 do {
1803 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001804 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001805 err = SSL_get_error(self->ssl, count);
1806 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001807 if (PyErr_CheckSignals())
1808 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001809 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001810 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001811 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001812 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001813 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1814 (SSL_get_shutdown(self->ssl) ==
1815 SSL_RECEIVED_SHUTDOWN))
1816 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001817 count = 0;
1818 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001819 } else {
1820 sockstate = SOCKET_OPERATION_OK;
1821 }
1822 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1823 PyErr_SetString(PySSLErrorObject,
1824 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001825 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001826 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1827 break;
1828 }
1829 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1830 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001831 PySSL_SetError(self, count, __FILE__, __LINE__);
1832 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001833 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001834
1835done:
1836 Py_DECREF(sock);
1837 if (!buf_passed) {
1838 _PyBytes_Resize(&dest, count);
1839 return dest;
1840 }
1841 else {
1842 PyBuffer_Release(&buf);
1843 return PyLong_FromLong(count);
1844 }
1845
1846error:
1847 Py_DECREF(sock);
1848 if (!buf_passed)
1849 Py_XDECREF(dest);
1850 else
1851 PyBuffer_Release(&buf);
1852 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001853}
1854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001855PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001856"read([len]) -> string\n\
1857\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001858Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001859
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001860static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001861{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001862 int err, ssl_err, sockstate, nonblocking;
1863 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001864 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001865
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001866 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001867 if (sock->sock_fd < 0) {
1868 _setSSLError("Underlying socket connection gone",
1869 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001870 return NULL;
1871 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001872 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001873
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001874 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001875 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001876 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1877 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001878
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001879 while (1) {
1880 PySSL_BEGIN_ALLOW_THREADS
1881 /* Disable read-ahead so that unwrap can work correctly.
1882 * Otherwise OpenSSL might read in too much data,
1883 * eating clear text data that happens to be
1884 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001885 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001886 * function is used and the shutdown_seen_zero != 0
1887 * condition is met.
1888 */
1889 if (self->shutdown_seen_zero)
1890 SSL_set_read_ahead(self->ssl, 0);
1891 err = SSL_shutdown(self->ssl);
1892 PySSL_END_ALLOW_THREADS
1893 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1894 if (err > 0)
1895 break;
1896 if (err == 0) {
1897 /* Don't loop endlessly; instead preserve legacy
1898 behaviour of trying SSL_shutdown() only twice.
1899 This looks necessary for OpenSSL < 0.9.8m */
1900 if (++zeros > 1)
1901 break;
1902 /* Shutdown was sent, now try receiving */
1903 self->shutdown_seen_zero = 1;
1904 continue;
1905 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001906
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 /* Possibly retry shutdown until timeout or failure */
1908 ssl_err = SSL_get_error(self->ssl, err);
1909 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001910 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001911 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001912 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001913 else
1914 break;
1915 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1916 if (ssl_err == SSL_ERROR_WANT_READ)
1917 PyErr_SetString(PySSLErrorObject,
1918 "The read operation timed out");
1919 else
1920 PyErr_SetString(PySSLErrorObject,
1921 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001922 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001923 }
1924 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1925 PyErr_SetString(PySSLErrorObject,
1926 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001927 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001928 }
1929 else if (sockstate != SOCKET_OPERATION_OK)
1930 /* Retain the SSL error code */
1931 break;
1932 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001933
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001934 if (err < 0) {
1935 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001936 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001937 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001938 else
1939 /* It's already INCREF'ed */
1940 return (PyObject *) sock;
1941
1942error:
1943 Py_DECREF(sock);
1944 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001945}
1946
1947PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1948"shutdown(s) -> socket\n\
1949\n\
1950Does the SSL shutdown handshake with the remote end, and returns\n\
1951the underlying socket object.");
1952
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001953#if HAVE_OPENSSL_FINISHED
1954static PyObject *
1955PySSL_tls_unique_cb(PySSLSocket *self)
1956{
1957 PyObject *retval = NULL;
1958 char buf[PySSL_CB_MAXLEN];
1959 size_t len;
1960
1961 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1962 /* if session is resumed XOR we are the client */
1963 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1964 }
1965 else {
1966 /* if a new session XOR we are the server */
1967 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1968 }
1969
1970 /* It cannot be negative in current OpenSSL version as of July 2011 */
1971 if (len == 0)
1972 Py_RETURN_NONE;
1973
1974 retval = PyBytes_FromStringAndSize(buf, len);
1975
1976 return retval;
1977}
1978
1979PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1980"tls_unique_cb() -> bytes\n\
1981\n\
1982Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1983\n\
1984If the TLS handshake is not yet complete, None is returned");
1985
1986#endif /* HAVE_OPENSSL_FINISHED */
1987
1988static PyGetSetDef ssl_getsetlist[] = {
1989 {"context", (getter) PySSL_get_context,
1990 (setter) PySSL_set_context, PySSL_set_context_doc},
1991 {NULL}, /* sentinel */
1992};
1993
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001994static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001995 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1996 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1997 PySSL_SSLwrite_doc},
1998 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1999 PySSL_SSLread_doc},
2000 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2001 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002002 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2003 PySSL_peercert_doc},
2004 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002005 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002006#ifdef OPENSSL_NPN_NEGOTIATED
2007 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2008#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002009#ifdef HAVE_ALPN
2010 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2011#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002012 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002013 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2014 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002015#if HAVE_OPENSSL_FINISHED
2016 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2017 PySSL_tls_unique_cb_doc},
2018#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002019 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002020};
2021
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002022static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002023 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002024 "_ssl._SSLSocket", /*tp_name*/
2025 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002026 0, /*tp_itemsize*/
2027 /* methods */
2028 (destructor)PySSL_dealloc, /*tp_dealloc*/
2029 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002030 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002031 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002032 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002033 0, /*tp_repr*/
2034 0, /*tp_as_number*/
2035 0, /*tp_as_sequence*/
2036 0, /*tp_as_mapping*/
2037 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002038 0, /*tp_call*/
2039 0, /*tp_str*/
2040 0, /*tp_getattro*/
2041 0, /*tp_setattro*/
2042 0, /*tp_as_buffer*/
2043 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2044 0, /*tp_doc*/
2045 0, /*tp_traverse*/
2046 0, /*tp_clear*/
2047 0, /*tp_richcompare*/
2048 0, /*tp_weaklistoffset*/
2049 0, /*tp_iter*/
2050 0, /*tp_iternext*/
2051 PySSLMethods, /*tp_methods*/
2052 0, /*tp_members*/
2053 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002054};
2055
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002056
2057/*
2058 * _SSLContext objects
2059 */
2060
2061static PyObject *
2062context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2063{
2064 char *kwlist[] = {"protocol", NULL};
2065 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002066 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002067 long options;
2068 SSL_CTX *ctx = NULL;
2069
2070 if (!PyArg_ParseTupleAndKeywords(
2071 args, kwds, "i:_SSLContext", kwlist,
2072 &proto_version))
2073 return NULL;
2074
2075 PySSL_BEGIN_ALLOW_THREADS
2076 if (proto_version == PY_SSL_VERSION_TLS1)
2077 ctx = SSL_CTX_new(TLSv1_method());
2078#if HAVE_TLSv1_2
2079 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2080 ctx = SSL_CTX_new(TLSv1_1_method());
2081 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2082 ctx = SSL_CTX_new(TLSv1_2_method());
2083#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002084#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002085 else if (proto_version == PY_SSL_VERSION_SSL3)
2086 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002087#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002088#ifndef OPENSSL_NO_SSL2
2089 else if (proto_version == PY_SSL_VERSION_SSL2)
2090 ctx = SSL_CTX_new(SSLv2_method());
2091#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002092 else if (proto_version == PY_SSL_VERSION_TLS)
2093 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002094 else
2095 proto_version = -1;
2096 PySSL_END_ALLOW_THREADS
2097
2098 if (proto_version == -1) {
2099 PyErr_SetString(PyExc_ValueError,
2100 "invalid protocol version");
2101 return NULL;
2102 }
2103 if (ctx == NULL) {
2104 PyErr_SetString(PySSLErrorObject,
2105 "failed to allocate SSL context");
2106 return NULL;
2107 }
2108
2109 assert(type != NULL && type->tp_alloc != NULL);
2110 self = (PySSLContext *) type->tp_alloc(type, 0);
2111 if (self == NULL) {
2112 SSL_CTX_free(ctx);
2113 return NULL;
2114 }
2115 self->ctx = ctx;
2116#ifdef OPENSSL_NPN_NEGOTIATED
2117 self->npn_protocols = NULL;
2118#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002119#ifdef HAVE_ALPN
2120 self->alpn_protocols = NULL;
2121#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002122#ifndef OPENSSL_NO_TLSEXT
2123 self->set_hostname = NULL;
2124#endif
2125 /* Don't check host name by default */
2126 self->check_hostname = 0;
2127 /* Defaults */
2128 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2129 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2130 if (proto_version != PY_SSL_VERSION_SSL2)
2131 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002132 if (proto_version != PY_SSL_VERSION_SSL3)
2133 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002134 SSL_CTX_set_options(self->ctx, options);
2135
2136#ifndef OPENSSL_NO_ECDH
2137 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2138 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002139 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2140 */
2141#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002142 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2143#else
2144 {
2145 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2146 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2147 EC_KEY_free(key);
2148 }
2149#endif
2150#endif
2151
2152#define SID_CTX "Python"
2153 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2154 sizeof(SID_CTX));
2155#undef SID_CTX
2156
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002157#ifdef X509_V_FLAG_TRUSTED_FIRST
2158 {
2159 /* Improve trust chain building when cross-signed intermediate
2160 certificates are present. See https://bugs.python.org/issue23476. */
2161 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2162 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2163 }
2164#endif
2165
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002166 return (PyObject *)self;
2167}
2168
2169static int
2170context_traverse(PySSLContext *self, visitproc visit, void *arg)
2171{
2172#ifndef OPENSSL_NO_TLSEXT
2173 Py_VISIT(self->set_hostname);
2174#endif
2175 return 0;
2176}
2177
2178static int
2179context_clear(PySSLContext *self)
2180{
2181#ifndef OPENSSL_NO_TLSEXT
2182 Py_CLEAR(self->set_hostname);
2183#endif
2184 return 0;
2185}
2186
2187static void
2188context_dealloc(PySSLContext *self)
2189{
2190 context_clear(self);
2191 SSL_CTX_free(self->ctx);
2192#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002193 PyMem_FREE(self->npn_protocols);
2194#endif
2195#ifdef HAVE_ALPN
2196 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002197#endif
2198 Py_TYPE(self)->tp_free(self);
2199}
2200
2201static PyObject *
2202set_ciphers(PySSLContext *self, PyObject *args)
2203{
2204 int ret;
2205 const char *cipherlist;
2206
2207 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2208 return NULL;
2209 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2210 if (ret == 0) {
2211 /* Clearing the error queue is necessary on some OpenSSL versions,
2212 otherwise the error will be reported again when another SSL call
2213 is done. */
2214 ERR_clear_error();
2215 PyErr_SetString(PySSLErrorObject,
2216 "No cipher can be selected.");
2217 return NULL;
2218 }
2219 Py_RETURN_NONE;
2220}
2221
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002222#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002223static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002224do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2225 const unsigned char *server_protocols, unsigned int server_protocols_len,
2226 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002227{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002228 int ret;
2229 if (client_protocols == NULL) {
2230 client_protocols = (unsigned char *)"";
2231 client_protocols_len = 0;
2232 }
2233 if (server_protocols == NULL) {
2234 server_protocols = (unsigned char *)"";
2235 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002236 }
2237
Benjamin Petersonaa707582015-01-23 17:30:26 -05002238 ret = SSL_select_next_proto(out, outlen,
2239 server_protocols, server_protocols_len,
2240 client_protocols, client_protocols_len);
2241 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2242 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002243
2244 return SSL_TLSEXT_ERR_OK;
2245}
2246
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002247/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2248static int
2249_advertiseNPN_cb(SSL *s,
2250 const unsigned char **data, unsigned int *len,
2251 void *args)
2252{
2253 PySSLContext *ssl_ctx = (PySSLContext *) args;
2254
2255 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002256 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002257 *len = 0;
2258 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002259 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002260 *len = ssl_ctx->npn_protocols_len;
2261 }
2262
2263 return SSL_TLSEXT_ERR_OK;
2264}
2265/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2266static int
2267_selectNPN_cb(SSL *s,
2268 unsigned char **out, unsigned char *outlen,
2269 const unsigned char *server, unsigned int server_len,
2270 void *args)
2271{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002272 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002273 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002274 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002275}
2276#endif
2277
2278static PyObject *
2279_set_npn_protocols(PySSLContext *self, PyObject *args)
2280{
2281#ifdef OPENSSL_NPN_NEGOTIATED
2282 Py_buffer protos;
2283
2284 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2285 return NULL;
2286
2287 if (self->npn_protocols != NULL) {
2288 PyMem_Free(self->npn_protocols);
2289 }
2290
2291 self->npn_protocols = PyMem_Malloc(protos.len);
2292 if (self->npn_protocols == NULL) {
2293 PyBuffer_Release(&protos);
2294 return PyErr_NoMemory();
2295 }
2296 memcpy(self->npn_protocols, protos.buf, protos.len);
2297 self->npn_protocols_len = (int) protos.len;
2298
2299 /* set both server and client callbacks, because the context can
2300 * be used to create both types of sockets */
2301 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2302 _advertiseNPN_cb,
2303 self);
2304 SSL_CTX_set_next_proto_select_cb(self->ctx,
2305 _selectNPN_cb,
2306 self);
2307
2308 PyBuffer_Release(&protos);
2309 Py_RETURN_NONE;
2310#else
2311 PyErr_SetString(PyExc_NotImplementedError,
2312 "The NPN extension requires OpenSSL 1.0.1 or later.");
2313 return NULL;
2314#endif
2315}
2316
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002317#ifdef HAVE_ALPN
2318static int
2319_selectALPN_cb(SSL *s,
2320 const unsigned char **out, unsigned char *outlen,
2321 const unsigned char *client_protocols, unsigned int client_protocols_len,
2322 void *args)
2323{
2324 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002325 return do_protocol_selection(1, (unsigned char **)out, outlen,
2326 ctx->alpn_protocols, ctx->alpn_protocols_len,
2327 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002328}
2329#endif
2330
2331static PyObject *
2332_set_alpn_protocols(PySSLContext *self, PyObject *args)
2333{
2334#ifdef HAVE_ALPN
2335 Py_buffer protos;
2336
2337 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2338 return NULL;
2339
2340 PyMem_FREE(self->alpn_protocols);
2341 self->alpn_protocols = PyMem_Malloc(protos.len);
2342 if (!self->alpn_protocols)
2343 return PyErr_NoMemory();
2344 memcpy(self->alpn_protocols, protos.buf, protos.len);
2345 self->alpn_protocols_len = protos.len;
2346 PyBuffer_Release(&protos);
2347
2348 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2349 return PyErr_NoMemory();
2350 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2351
2352 PyBuffer_Release(&protos);
2353 Py_RETURN_NONE;
2354#else
2355 PyErr_SetString(PyExc_NotImplementedError,
2356 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2357 return NULL;
2358#endif
2359}
2360
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002361static PyObject *
2362get_verify_mode(PySSLContext *self, void *c)
2363{
2364 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2365 case SSL_VERIFY_NONE:
2366 return PyLong_FromLong(PY_SSL_CERT_NONE);
2367 case SSL_VERIFY_PEER:
2368 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2369 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2370 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2371 }
2372 PyErr_SetString(PySSLErrorObject,
2373 "invalid return value from SSL_CTX_get_verify_mode");
2374 return NULL;
2375}
2376
2377static int
2378set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2379{
2380 int n, mode;
2381 if (!PyArg_Parse(arg, "i", &n))
2382 return -1;
2383 if (n == PY_SSL_CERT_NONE)
2384 mode = SSL_VERIFY_NONE;
2385 else if (n == PY_SSL_CERT_OPTIONAL)
2386 mode = SSL_VERIFY_PEER;
2387 else if (n == PY_SSL_CERT_REQUIRED)
2388 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2389 else {
2390 PyErr_SetString(PyExc_ValueError,
2391 "invalid value for verify_mode");
2392 return -1;
2393 }
2394 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2395 PyErr_SetString(PyExc_ValueError,
2396 "Cannot set verify_mode to CERT_NONE when "
2397 "check_hostname is enabled.");
2398 return -1;
2399 }
2400 SSL_CTX_set_verify(self->ctx, mode, NULL);
2401 return 0;
2402}
2403
2404#ifdef HAVE_OPENSSL_VERIFY_PARAM
2405static PyObject *
2406get_verify_flags(PySSLContext *self, void *c)
2407{
2408 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002409 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002410 unsigned long flags;
2411
2412 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002413 param = X509_STORE_get0_param(store);
2414 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002415 return PyLong_FromUnsignedLong(flags);
2416}
2417
2418static int
2419set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2420{
2421 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002422 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002423 unsigned long new_flags, flags, set, clear;
2424
2425 if (!PyArg_Parse(arg, "k", &new_flags))
2426 return -1;
2427 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002428 param = X509_STORE_get0_param(store);
2429 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002430 clear = flags & ~new_flags;
2431 set = ~flags & new_flags;
2432 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002433 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002434 _setSSLError(NULL, 0, __FILE__, __LINE__);
2435 return -1;
2436 }
2437 }
2438 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002439 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002440 _setSSLError(NULL, 0, __FILE__, __LINE__);
2441 return -1;
2442 }
2443 }
2444 return 0;
2445}
2446#endif
2447
2448static PyObject *
2449get_options(PySSLContext *self, void *c)
2450{
2451 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2452}
2453
2454static int
2455set_options(PySSLContext *self, PyObject *arg, void *c)
2456{
2457 long new_opts, opts, set, clear;
2458 if (!PyArg_Parse(arg, "l", &new_opts))
2459 return -1;
2460 opts = SSL_CTX_get_options(self->ctx);
2461 clear = opts & ~new_opts;
2462 set = ~opts & new_opts;
2463 if (clear) {
2464#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2465 SSL_CTX_clear_options(self->ctx, clear);
2466#else
2467 PyErr_SetString(PyExc_ValueError,
2468 "can't clear options before OpenSSL 0.9.8m");
2469 return -1;
2470#endif
2471 }
2472 if (set)
2473 SSL_CTX_set_options(self->ctx, set);
2474 return 0;
2475}
2476
2477static PyObject *
2478get_check_hostname(PySSLContext *self, void *c)
2479{
2480 return PyBool_FromLong(self->check_hostname);
2481}
2482
2483static int
2484set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2485{
2486 PyObject *py_check_hostname;
2487 int check_hostname;
2488 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2489 return -1;
2490
2491 check_hostname = PyObject_IsTrue(py_check_hostname);
2492 if (check_hostname < 0)
2493 return -1;
2494 if (check_hostname &&
2495 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2496 PyErr_SetString(PyExc_ValueError,
2497 "check_hostname needs a SSL context with either "
2498 "CERT_OPTIONAL or CERT_REQUIRED");
2499 return -1;
2500 }
2501 self->check_hostname = check_hostname;
2502 return 0;
2503}
2504
2505
2506typedef struct {
2507 PyThreadState *thread_state;
2508 PyObject *callable;
2509 char *password;
2510 int size;
2511 int error;
2512} _PySSLPasswordInfo;
2513
2514static int
2515_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2516 const char *bad_type_error)
2517{
2518 /* Set the password and size fields of a _PySSLPasswordInfo struct
2519 from a unicode, bytes, or byte array object.
2520 The password field will be dynamically allocated and must be freed
2521 by the caller */
2522 PyObject *password_bytes = NULL;
2523 const char *data = NULL;
2524 Py_ssize_t size;
2525
2526 if (PyUnicode_Check(password)) {
2527 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2528 if (!password_bytes) {
2529 goto error;
2530 }
2531 data = PyBytes_AS_STRING(password_bytes);
2532 size = PyBytes_GET_SIZE(password_bytes);
2533 } else if (PyBytes_Check(password)) {
2534 data = PyBytes_AS_STRING(password);
2535 size = PyBytes_GET_SIZE(password);
2536 } else if (PyByteArray_Check(password)) {
2537 data = PyByteArray_AS_STRING(password);
2538 size = PyByteArray_GET_SIZE(password);
2539 } else {
2540 PyErr_SetString(PyExc_TypeError, bad_type_error);
2541 goto error;
2542 }
2543
2544 if (size > (Py_ssize_t)INT_MAX) {
2545 PyErr_Format(PyExc_ValueError,
2546 "password cannot be longer than %d bytes", INT_MAX);
2547 goto error;
2548 }
2549
2550 PyMem_Free(pw_info->password);
2551 pw_info->password = PyMem_Malloc(size);
2552 if (!pw_info->password) {
2553 PyErr_SetString(PyExc_MemoryError,
2554 "unable to allocate password buffer");
2555 goto error;
2556 }
2557 memcpy(pw_info->password, data, size);
2558 pw_info->size = (int)size;
2559
2560 Py_XDECREF(password_bytes);
2561 return 1;
2562
2563error:
2564 Py_XDECREF(password_bytes);
2565 return 0;
2566}
2567
2568static int
2569_password_callback(char *buf, int size, int rwflag, void *userdata)
2570{
2571 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2572 PyObject *fn_ret = NULL;
2573
2574 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2575
2576 if (pw_info->callable) {
2577 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2578 if (!fn_ret) {
2579 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2580 core python API, so we could use it to add a frame here */
2581 goto error;
2582 }
2583
2584 if (!_pwinfo_set(pw_info, fn_ret,
2585 "password callback must return a string")) {
2586 goto error;
2587 }
2588 Py_CLEAR(fn_ret);
2589 }
2590
2591 if (pw_info->size > size) {
2592 PyErr_Format(PyExc_ValueError,
2593 "password cannot be longer than %d bytes", size);
2594 goto error;
2595 }
2596
2597 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2598 memcpy(buf, pw_info->password, pw_info->size);
2599 return pw_info->size;
2600
2601error:
2602 Py_XDECREF(fn_ret);
2603 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2604 pw_info->error = 1;
2605 return -1;
2606}
2607
2608static PyObject *
2609load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2610{
2611 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002612 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2613 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002614 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2615 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002616 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2617 int r;
2618
2619 errno = 0;
2620 ERR_clear_error();
2621 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002622 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002623 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002624 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002625 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002626
2627 if (keyfile && keyfile != Py_None) {
2628 if (PyString_Check(keyfile)) {
2629 Py_INCREF(keyfile);
2630 keyfile_bytes = keyfile;
2631 } else {
2632 PyObject *u = PyUnicode_FromObject(keyfile);
2633 if (!u)
2634 goto error;
2635 keyfile_bytes = PyUnicode_AsEncodedString(
2636 u, Py_FileSystemDefaultEncoding, NULL);
2637 Py_DECREF(u);
2638 if (!keyfile_bytes)
2639 goto error;
2640 }
2641 }
2642
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002643 if (password && password != Py_None) {
2644 if (PyCallable_Check(password)) {
2645 pw_info.callable = password;
2646 } else if (!_pwinfo_set(&pw_info, password,
2647 "password should be a string or callable")) {
2648 goto error;
2649 }
2650 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2651 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2652 }
2653 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2654 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2655 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2656 if (r != 1) {
2657 if (pw_info.error) {
2658 ERR_clear_error();
2659 /* the password callback has already set the error information */
2660 }
2661 else if (errno != 0) {
2662 ERR_clear_error();
2663 PyErr_SetFromErrno(PyExc_IOError);
2664 }
2665 else {
2666 _setSSLError(NULL, 0, __FILE__, __LINE__);
2667 }
2668 goto error;
2669 }
2670 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2671 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002672 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002673 SSL_FILETYPE_PEM);
2674 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2675 if (r != 1) {
2676 if (pw_info.error) {
2677 ERR_clear_error();
2678 /* the password callback has already set the error information */
2679 }
2680 else if (errno != 0) {
2681 ERR_clear_error();
2682 PyErr_SetFromErrno(PyExc_IOError);
2683 }
2684 else {
2685 _setSSLError(NULL, 0, __FILE__, __LINE__);
2686 }
2687 goto error;
2688 }
2689 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2690 r = SSL_CTX_check_private_key(self->ctx);
2691 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2692 if (r != 1) {
2693 _setSSLError(NULL, 0, __FILE__, __LINE__);
2694 goto error;
2695 }
2696 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2697 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002698 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002699 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002700 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002701 Py_RETURN_NONE;
2702
2703error:
2704 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2705 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002706 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002707 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002708 PyMem_Free(certfile_bytes);
2709 return NULL;
2710}
2711
2712/* internal helper function, returns -1 on error
2713 */
2714static int
2715_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2716 int filetype)
2717{
2718 BIO *biobuf = NULL;
2719 X509_STORE *store;
2720 int retval = 0, err, loaded = 0;
2721
2722 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2723
2724 if (len <= 0) {
2725 PyErr_SetString(PyExc_ValueError,
2726 "Empty certificate data");
2727 return -1;
2728 } else if (len > INT_MAX) {
2729 PyErr_SetString(PyExc_OverflowError,
2730 "Certificate data is too long.");
2731 return -1;
2732 }
2733
2734 biobuf = BIO_new_mem_buf(data, (int)len);
2735 if (biobuf == NULL) {
2736 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2737 return -1;
2738 }
2739
2740 store = SSL_CTX_get_cert_store(self->ctx);
2741 assert(store != NULL);
2742
2743 while (1) {
2744 X509 *cert = NULL;
2745 int r;
2746
2747 if (filetype == SSL_FILETYPE_ASN1) {
2748 cert = d2i_X509_bio(biobuf, NULL);
2749 } else {
2750 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002751 SSL_CTX_get_default_passwd_cb(self->ctx),
2752 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2753 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002754 }
2755 if (cert == NULL) {
2756 break;
2757 }
2758 r = X509_STORE_add_cert(store, cert);
2759 X509_free(cert);
2760 if (!r) {
2761 err = ERR_peek_last_error();
2762 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2763 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2764 /* cert already in hash table, not an error */
2765 ERR_clear_error();
2766 } else {
2767 break;
2768 }
2769 }
2770 loaded++;
2771 }
2772
2773 err = ERR_peek_last_error();
2774 if ((filetype == SSL_FILETYPE_ASN1) &&
2775 (loaded > 0) &&
2776 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2777 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2778 /* EOF ASN1 file, not an error */
2779 ERR_clear_error();
2780 retval = 0;
2781 } else if ((filetype == SSL_FILETYPE_PEM) &&
2782 (loaded > 0) &&
2783 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2784 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2785 /* EOF PEM file, not an error */
2786 ERR_clear_error();
2787 retval = 0;
2788 } else {
2789 _setSSLError(NULL, 0, __FILE__, __LINE__);
2790 retval = -1;
2791 }
2792
2793 BIO_free(biobuf);
2794 return retval;
2795}
2796
2797
2798static PyObject *
2799load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2800{
2801 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2802 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2803 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2804 const char *cafile_buf = NULL, *capath_buf = NULL;
2805 int r = 0, ok = 1;
2806
2807 errno = 0;
2808 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2809 "|OOO:load_verify_locations", kwlist,
2810 &cafile, &capath, &cadata))
2811 return NULL;
2812
2813 if (cafile == Py_None)
2814 cafile = NULL;
2815 if (capath == Py_None)
2816 capath = NULL;
2817 if (cadata == Py_None)
2818 cadata = NULL;
2819
2820 if (cafile == NULL && capath == NULL && cadata == NULL) {
2821 PyErr_SetString(PyExc_TypeError,
2822 "cafile, capath and cadata cannot be all omitted");
2823 goto error;
2824 }
2825
2826 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002827 if (PyString_Check(cafile)) {
2828 Py_INCREF(cafile);
2829 cafile_bytes = cafile;
2830 } else {
2831 PyObject *u = PyUnicode_FromObject(cafile);
2832 if (!u)
2833 goto error;
2834 cafile_bytes = PyUnicode_AsEncodedString(
2835 u, Py_FileSystemDefaultEncoding, NULL);
2836 Py_DECREF(u);
2837 if (!cafile_bytes)
2838 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002839 }
2840 }
2841 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002842 if (PyString_Check(capath)) {
2843 Py_INCREF(capath);
2844 capath_bytes = capath;
2845 } else {
2846 PyObject *u = PyUnicode_FromObject(capath);
2847 if (!u)
2848 goto error;
2849 capath_bytes = PyUnicode_AsEncodedString(
2850 u, Py_FileSystemDefaultEncoding, NULL);
2851 Py_DECREF(u);
2852 if (!capath_bytes)
2853 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002854 }
2855 }
2856
2857 /* validata cadata type and load cadata */
2858 if (cadata) {
2859 Py_buffer buf;
2860 PyObject *cadata_ascii = NULL;
2861
2862 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2863 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2864 PyBuffer_Release(&buf);
2865 PyErr_SetString(PyExc_TypeError,
2866 "cadata should be a contiguous buffer with "
2867 "a single dimension");
2868 goto error;
2869 }
2870 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2871 PyBuffer_Release(&buf);
2872 if (r == -1) {
2873 goto error;
2874 }
2875 } else {
2876 PyErr_Clear();
2877 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2878 if (cadata_ascii == NULL) {
2879 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002880 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002881 "bytes-like object");
2882 goto error;
2883 }
2884 r = _add_ca_certs(self,
2885 PyBytes_AS_STRING(cadata_ascii),
2886 PyBytes_GET_SIZE(cadata_ascii),
2887 SSL_FILETYPE_PEM);
2888 Py_DECREF(cadata_ascii);
2889 if (r == -1) {
2890 goto error;
2891 }
2892 }
2893 }
2894
2895 /* load cafile or capath */
2896 if (cafile_bytes || capath_bytes) {
2897 if (cafile)
2898 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2899 if (capath)
2900 capath_buf = PyBytes_AS_STRING(capath_bytes);
2901 PySSL_BEGIN_ALLOW_THREADS
2902 r = SSL_CTX_load_verify_locations(
2903 self->ctx,
2904 cafile_buf,
2905 capath_buf);
2906 PySSL_END_ALLOW_THREADS
2907 if (r != 1) {
2908 ok = 0;
2909 if (errno != 0) {
2910 ERR_clear_error();
2911 PyErr_SetFromErrno(PyExc_IOError);
2912 }
2913 else {
2914 _setSSLError(NULL, 0, __FILE__, __LINE__);
2915 }
2916 goto error;
2917 }
2918 }
2919 goto end;
2920
2921 error:
2922 ok = 0;
2923 end:
2924 Py_XDECREF(cafile_bytes);
2925 Py_XDECREF(capath_bytes);
2926 if (ok) {
2927 Py_RETURN_NONE;
2928 } else {
2929 return NULL;
2930 }
2931}
2932
2933static PyObject *
2934load_dh_params(PySSLContext *self, PyObject *filepath)
2935{
2936 BIO *bio;
2937 DH *dh;
2938 char *path = PyBytes_AsString(filepath);
2939 if (!path) {
2940 return NULL;
2941 }
2942
2943 bio = BIO_new_file(path, "r");
2944 if (bio == NULL) {
2945 ERR_clear_error();
2946 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2947 return NULL;
2948 }
2949 errno = 0;
2950 PySSL_BEGIN_ALLOW_THREADS
2951 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2952 BIO_free(bio);
2953 PySSL_END_ALLOW_THREADS
2954 if (dh == NULL) {
2955 if (errno != 0) {
2956 ERR_clear_error();
2957 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2958 }
2959 else {
2960 _setSSLError(NULL, 0, __FILE__, __LINE__);
2961 }
2962 return NULL;
2963 }
2964 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2965 _setSSLError(NULL, 0, __FILE__, __LINE__);
2966 DH_free(dh);
2967 Py_RETURN_NONE;
2968}
2969
2970static PyObject *
2971context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2972{
2973 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2974 PySocketSockObject *sock;
2975 int server_side = 0;
2976 char *hostname = NULL;
2977 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2978
2979 /* server_hostname is either None (or absent), or to be encoded
2980 using the idna encoding. */
2981 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2982 PySocketModule.Sock_Type,
2983 &sock, &server_side,
2984 Py_TYPE(Py_None), &hostname_obj,
2985 &ssl_sock)) {
2986 PyErr_Clear();
2987 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2988 PySocketModule.Sock_Type,
2989 &sock, &server_side,
2990 "idna", &hostname, &ssl_sock))
2991 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002992 }
2993
2994 res = (PyObject *) newPySSLSocket(self, sock, server_side,
2995 hostname, ssl_sock);
2996 if (hostname != NULL)
2997 PyMem_Free(hostname);
2998 return res;
2999}
3000
3001static PyObject *
3002session_stats(PySSLContext *self, PyObject *unused)
3003{
3004 int r;
3005 PyObject *value, *stats = PyDict_New();
3006 if (!stats)
3007 return NULL;
3008
3009#define ADD_STATS(SSL_NAME, KEY_NAME) \
3010 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3011 if (value == NULL) \
3012 goto error; \
3013 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3014 Py_DECREF(value); \
3015 if (r < 0) \
3016 goto error;
3017
3018 ADD_STATS(number, "number");
3019 ADD_STATS(connect, "connect");
3020 ADD_STATS(connect_good, "connect_good");
3021 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3022 ADD_STATS(accept, "accept");
3023 ADD_STATS(accept_good, "accept_good");
3024 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3025 ADD_STATS(accept, "accept");
3026 ADD_STATS(hits, "hits");
3027 ADD_STATS(misses, "misses");
3028 ADD_STATS(timeouts, "timeouts");
3029 ADD_STATS(cache_full, "cache_full");
3030
3031#undef ADD_STATS
3032
3033 return stats;
3034
3035error:
3036 Py_DECREF(stats);
3037 return NULL;
3038}
3039
3040static PyObject *
3041set_default_verify_paths(PySSLContext *self, PyObject *unused)
3042{
3043 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3044 _setSSLError(NULL, 0, __FILE__, __LINE__);
3045 return NULL;
3046 }
3047 Py_RETURN_NONE;
3048}
3049
3050#ifndef OPENSSL_NO_ECDH
3051static PyObject *
3052set_ecdh_curve(PySSLContext *self, PyObject *name)
3053{
3054 char *name_bytes;
3055 int nid;
3056 EC_KEY *key;
3057
3058 name_bytes = PyBytes_AsString(name);
3059 if (!name_bytes) {
3060 return NULL;
3061 }
3062 nid = OBJ_sn2nid(name_bytes);
3063 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003064 PyObject *r = PyObject_Repr(name);
3065 if (!r)
3066 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003067 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003068 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3069 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003070 return NULL;
3071 }
3072 key = EC_KEY_new_by_curve_name(nid);
3073 if (key == NULL) {
3074 _setSSLError(NULL, 0, __FILE__, __LINE__);
3075 return NULL;
3076 }
3077 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3078 EC_KEY_free(key);
3079 Py_RETURN_NONE;
3080}
3081#endif
3082
3083#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3084static int
3085_servername_callback(SSL *s, int *al, void *args)
3086{
3087 int ret;
3088 PySSLContext *ssl_ctx = (PySSLContext *) args;
3089 PySSLSocket *ssl;
3090 PyObject *servername_o;
3091 PyObject *servername_idna;
3092 PyObject *result;
3093 /* The high-level ssl.SSLSocket object */
3094 PyObject *ssl_socket;
3095 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3096#ifdef WITH_THREAD
3097 PyGILState_STATE gstate = PyGILState_Ensure();
3098#endif
3099
3100 if (ssl_ctx->set_hostname == NULL) {
3101 /* remove race condition in this the call back while if removing the
3102 * callback is in progress */
3103#ifdef WITH_THREAD
3104 PyGILState_Release(gstate);
3105#endif
3106 return SSL_TLSEXT_ERR_OK;
3107 }
3108
3109 ssl = SSL_get_app_data(s);
3110 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003111 if (ssl->ssl_sock == NULL) {
3112 ssl_socket = Py_None;
3113 } else {
3114 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3115 Py_INCREF(ssl_socket);
3116 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003117 if (ssl_socket == Py_None) {
3118 goto error;
3119 }
3120
3121 if (servername == NULL) {
3122 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3123 Py_None, ssl_ctx, NULL);
3124 }
3125 else {
3126 servername_o = PyBytes_FromString(servername);
3127 if (servername_o == NULL) {
3128 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3129 goto error;
3130 }
3131 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3132 if (servername_idna == NULL) {
3133 PyErr_WriteUnraisable(servername_o);
3134 Py_DECREF(servername_o);
3135 goto error;
3136 }
3137 Py_DECREF(servername_o);
3138 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3139 servername_idna, ssl_ctx, NULL);
3140 Py_DECREF(servername_idna);
3141 }
3142 Py_DECREF(ssl_socket);
3143
3144 if (result == NULL) {
3145 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3146 *al = SSL_AD_HANDSHAKE_FAILURE;
3147 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3148 }
3149 else {
3150 if (result != Py_None) {
3151 *al = (int) PyLong_AsLong(result);
3152 if (PyErr_Occurred()) {
3153 PyErr_WriteUnraisable(result);
3154 *al = SSL_AD_INTERNAL_ERROR;
3155 }
3156 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3157 }
3158 else {
3159 ret = SSL_TLSEXT_ERR_OK;
3160 }
3161 Py_DECREF(result);
3162 }
3163
3164#ifdef WITH_THREAD
3165 PyGILState_Release(gstate);
3166#endif
3167 return ret;
3168
3169error:
3170 Py_DECREF(ssl_socket);
3171 *al = SSL_AD_INTERNAL_ERROR;
3172 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3173#ifdef WITH_THREAD
3174 PyGILState_Release(gstate);
3175#endif
3176 return ret;
3177}
3178#endif
3179
3180PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3181"set_servername_callback(method)\n\
3182\n\
3183This sets a callback that will be called when a server name is provided by\n\
3184the SSL/TLS client in the SNI extension.\n\
3185\n\
3186If the argument is None then the callback is disabled. The method is called\n\
3187with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3188See RFC 6066 for details of the SNI extension.");
3189
3190static PyObject *
3191set_servername_callback(PySSLContext *self, PyObject *args)
3192{
3193#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3194 PyObject *cb;
3195
3196 if (!PyArg_ParseTuple(args, "O", &cb))
3197 return NULL;
3198
3199 Py_CLEAR(self->set_hostname);
3200 if (cb == Py_None) {
3201 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3202 }
3203 else {
3204 if (!PyCallable_Check(cb)) {
3205 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3206 PyErr_SetString(PyExc_TypeError,
3207 "not a callable object");
3208 return NULL;
3209 }
3210 Py_INCREF(cb);
3211 self->set_hostname = cb;
3212 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3213 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3214 }
3215 Py_RETURN_NONE;
3216#else
3217 PyErr_SetString(PyExc_NotImplementedError,
3218 "The TLS extension servername callback, "
3219 "SSL_CTX_set_tlsext_servername_callback, "
3220 "is not in the current OpenSSL library.");
3221 return NULL;
3222#endif
3223}
3224
3225PyDoc_STRVAR(PySSL_get_stats_doc,
3226"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3227\n\
3228Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3229CA extension and certificate revocation lists inside the context's cert\n\
3230store.\n\
3231NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3232been used at least once.");
3233
3234static PyObject *
3235cert_store_stats(PySSLContext *self)
3236{
3237 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003238 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003239 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003240 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003241
3242 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003243 objs = X509_STORE_get0_objects(store);
3244 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3245 obj = sk_X509_OBJECT_value(objs, i);
3246 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003247 case X509_LU_X509:
3248 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003249 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003250 ca++;
3251 }
3252 break;
3253 case X509_LU_CRL:
3254 crl++;
3255 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003256 default:
3257 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3258 * As far as I can tell they are internal states and never
3259 * stored in a cert store */
3260 break;
3261 }
3262 }
3263 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3264 "x509_ca", ca);
3265}
3266
3267PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3268"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3269\n\
3270Returns a list of dicts with information of loaded CA certs. If the\n\
3271optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3272NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3273been used at least once.");
3274
3275static PyObject *
3276get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3277{
3278 char *kwlist[] = {"binary_form", NULL};
3279 X509_STORE *store;
3280 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003281 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003282 int i;
3283 int binary_mode = 0;
3284
3285 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3286 kwlist, &py_binary_mode)) {
3287 return NULL;
3288 }
3289 binary_mode = PyObject_IsTrue(py_binary_mode);
3290 if (binary_mode < 0) {
3291 return NULL;
3292 }
3293
3294 if ((rlist = PyList_New(0)) == NULL) {
3295 return NULL;
3296 }
3297
3298 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003299 objs = X509_STORE_get0_objects(store);
3300 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003301 X509_OBJECT *obj;
3302 X509 *cert;
3303
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003304 obj = sk_X509_OBJECT_value(objs, i);
3305 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003306 /* not a x509 cert */
3307 continue;
3308 }
3309 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003310 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003311 if (!X509_check_ca(cert)) {
3312 continue;
3313 }
3314 if (binary_mode) {
3315 ci = _certificate_to_der(cert);
3316 } else {
3317 ci = _decode_certificate(cert);
3318 }
3319 if (ci == NULL) {
3320 goto error;
3321 }
3322 if (PyList_Append(rlist, ci) == -1) {
3323 goto error;
3324 }
3325 Py_CLEAR(ci);
3326 }
3327 return rlist;
3328
3329 error:
3330 Py_XDECREF(ci);
3331 Py_XDECREF(rlist);
3332 return NULL;
3333}
3334
3335
3336static PyGetSetDef context_getsetlist[] = {
3337 {"check_hostname", (getter) get_check_hostname,
3338 (setter) set_check_hostname, NULL},
3339 {"options", (getter) get_options,
3340 (setter) set_options, NULL},
3341#ifdef HAVE_OPENSSL_VERIFY_PARAM
3342 {"verify_flags", (getter) get_verify_flags,
3343 (setter) set_verify_flags, NULL},
3344#endif
3345 {"verify_mode", (getter) get_verify_mode,
3346 (setter) set_verify_mode, NULL},
3347 {NULL}, /* sentinel */
3348};
3349
3350static struct PyMethodDef context_methods[] = {
3351 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3352 METH_VARARGS | METH_KEYWORDS, NULL},
3353 {"set_ciphers", (PyCFunction) set_ciphers,
3354 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003355 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3356 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003357 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3358 METH_VARARGS, NULL},
3359 {"load_cert_chain", (PyCFunction) load_cert_chain,
3360 METH_VARARGS | METH_KEYWORDS, NULL},
3361 {"load_dh_params", (PyCFunction) load_dh_params,
3362 METH_O, NULL},
3363 {"load_verify_locations", (PyCFunction) load_verify_locations,
3364 METH_VARARGS | METH_KEYWORDS, NULL},
3365 {"session_stats", (PyCFunction) session_stats,
3366 METH_NOARGS, NULL},
3367 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3368 METH_NOARGS, NULL},
3369#ifndef OPENSSL_NO_ECDH
3370 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3371 METH_O, NULL},
3372#endif
3373 {"set_servername_callback", (PyCFunction) set_servername_callback,
3374 METH_VARARGS, PySSL_set_servername_callback_doc},
3375 {"cert_store_stats", (PyCFunction) cert_store_stats,
3376 METH_NOARGS, PySSL_get_stats_doc},
3377 {"get_ca_certs", (PyCFunction) get_ca_certs,
3378 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3379 {NULL, NULL} /* sentinel */
3380};
3381
3382static PyTypeObject PySSLContext_Type = {
3383 PyVarObject_HEAD_INIT(NULL, 0)
3384 "_ssl._SSLContext", /*tp_name*/
3385 sizeof(PySSLContext), /*tp_basicsize*/
3386 0, /*tp_itemsize*/
3387 (destructor)context_dealloc, /*tp_dealloc*/
3388 0, /*tp_print*/
3389 0, /*tp_getattr*/
3390 0, /*tp_setattr*/
3391 0, /*tp_reserved*/
3392 0, /*tp_repr*/
3393 0, /*tp_as_number*/
3394 0, /*tp_as_sequence*/
3395 0, /*tp_as_mapping*/
3396 0, /*tp_hash*/
3397 0, /*tp_call*/
3398 0, /*tp_str*/
3399 0, /*tp_getattro*/
3400 0, /*tp_setattro*/
3401 0, /*tp_as_buffer*/
3402 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3403 0, /*tp_doc*/
3404 (traverseproc) context_traverse, /*tp_traverse*/
3405 (inquiry) context_clear, /*tp_clear*/
3406 0, /*tp_richcompare*/
3407 0, /*tp_weaklistoffset*/
3408 0, /*tp_iter*/
3409 0, /*tp_iternext*/
3410 context_methods, /*tp_methods*/
3411 0, /*tp_members*/
3412 context_getsetlist, /*tp_getset*/
3413 0, /*tp_base*/
3414 0, /*tp_dict*/
3415 0, /*tp_descr_get*/
3416 0, /*tp_descr_set*/
3417 0, /*tp_dictoffset*/
3418 0, /*tp_init*/
3419 0, /*tp_alloc*/
3420 context_new, /*tp_new*/
3421};
3422
3423
3424
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003425#ifdef HAVE_OPENSSL_RAND
3426
3427/* helper routines for seeding the SSL PRNG */
3428static PyObject *
3429PySSL_RAND_add(PyObject *self, PyObject *args)
3430{
3431 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003432 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003433 double entropy;
3434
3435 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003436 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003437 do {
3438 if (len >= INT_MAX) {
3439 written = INT_MAX;
3440 } else {
3441 written = len;
3442 }
3443 RAND_add(buf, (int)written, entropy);
3444 buf += written;
3445 len -= written;
3446 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003447 Py_INCREF(Py_None);
3448 return Py_None;
3449}
3450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003451PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003452"RAND_add(string, entropy)\n\
3453\n\
3454Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003455bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003456
3457static PyObject *
3458PySSL_RAND_status(PyObject *self)
3459{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003460 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003461}
3462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003463PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003464"RAND_status() -> 0 or 1\n\
3465\n\
3466Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3467It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003468using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003469
Victor Stinner7c906672015-01-06 13:53:37 +01003470#endif /* HAVE_OPENSSL_RAND */
3471
3472
Benjamin Peterson42e10292016-07-07 00:02:31 -07003473#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003474
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003475static PyObject *
3476PySSL_RAND_egd(PyObject *self, PyObject *arg)
3477{
3478 int bytes;
3479
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003480 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003481 return PyErr_Format(PyExc_TypeError,
3482 "RAND_egd() expected string, found %s",
3483 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003484 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003485 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003486 PyErr_SetString(PySSLErrorObject,
3487 "EGD connection failed or EGD did not return "
3488 "enough data to seed the PRNG");
3489 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003490 }
3491 return PyInt_FromLong(bytes);
3492}
3493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003494PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003495"RAND_egd(path) -> bytes\n\
3496\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003497Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3498Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003499fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003500
Benjamin Peterson42e10292016-07-07 00:02:31 -07003501#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003502
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003503
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003504PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3505"get_default_verify_paths() -> tuple\n\
3506\n\
3507Return search paths and environment vars that are used by SSLContext's\n\
3508set_default_verify_paths() to load default CAs. The values are\n\
3509'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3510
3511static PyObject *
3512PySSL_get_default_verify_paths(PyObject *self)
3513{
3514 PyObject *ofile_env = NULL;
3515 PyObject *ofile = NULL;
3516 PyObject *odir_env = NULL;
3517 PyObject *odir = NULL;
3518
Benjamin Peterson65192c12015-07-18 10:59:13 -07003519#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003520 const char *tmp = (info); \
3521 target = NULL; \
3522 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3523 else { target = PyBytes_FromString(tmp); } \
3524 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003525 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003526
Benjamin Peterson65192c12015-07-18 10:59:13 -07003527 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3528 CONVERT(X509_get_default_cert_file(), ofile);
3529 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3530 CONVERT(X509_get_default_cert_dir(), odir);
3531#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003532
3533 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3534
3535 error:
3536 Py_XDECREF(ofile_env);
3537 Py_XDECREF(ofile);
3538 Py_XDECREF(odir_env);
3539 Py_XDECREF(odir);
3540 return NULL;
3541}
3542
3543static PyObject*
3544asn1obj2py(ASN1_OBJECT *obj)
3545{
3546 int nid;
3547 const char *ln, *sn;
3548 char buf[100];
3549 Py_ssize_t buflen;
3550
3551 nid = OBJ_obj2nid(obj);
3552 if (nid == NID_undef) {
3553 PyErr_Format(PyExc_ValueError, "Unknown object");
3554 return NULL;
3555 }
3556 sn = OBJ_nid2sn(nid);
3557 ln = OBJ_nid2ln(nid);
3558 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3559 if (buflen < 0) {
3560 _setSSLError(NULL, 0, __FILE__, __LINE__);
3561 return NULL;
3562 }
3563 if (buflen) {
3564 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3565 } else {
3566 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3567 }
3568}
3569
3570PyDoc_STRVAR(PySSL_txt2obj_doc,
3571"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3572\n\
3573Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3574objects are looked up by OID. With name=True short and long name are also\n\
3575matched.");
3576
3577static PyObject*
3578PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3579{
3580 char *kwlist[] = {"txt", "name", NULL};
3581 PyObject *result = NULL;
3582 char *txt;
3583 PyObject *pyname = Py_None;
3584 int name = 0;
3585 ASN1_OBJECT *obj;
3586
3587 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3588 kwlist, &txt, &pyname)) {
3589 return NULL;
3590 }
3591 name = PyObject_IsTrue(pyname);
3592 if (name < 0)
3593 return NULL;
3594 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3595 if (obj == NULL) {
3596 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3597 return NULL;
3598 }
3599 result = asn1obj2py(obj);
3600 ASN1_OBJECT_free(obj);
3601 return result;
3602}
3603
3604PyDoc_STRVAR(PySSL_nid2obj_doc,
3605"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3606\n\
3607Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3608
3609static PyObject*
3610PySSL_nid2obj(PyObject *self, PyObject *args)
3611{
3612 PyObject *result = NULL;
3613 int nid;
3614 ASN1_OBJECT *obj;
3615
3616 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3617 return NULL;
3618 }
3619 if (nid < NID_undef) {
3620 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3621 return NULL;
3622 }
3623 obj = OBJ_nid2obj(nid);
3624 if (obj == NULL) {
3625 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3626 return NULL;
3627 }
3628 result = asn1obj2py(obj);
3629 ASN1_OBJECT_free(obj);
3630 return result;
3631}
3632
3633#ifdef _MSC_VER
3634
3635static PyObject*
3636certEncodingType(DWORD encodingType)
3637{
3638 static PyObject *x509_asn = NULL;
3639 static PyObject *pkcs_7_asn = NULL;
3640
3641 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003642 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003643 if (x509_asn == NULL)
3644 return NULL;
3645 }
3646 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003647 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003648 if (pkcs_7_asn == NULL)
3649 return NULL;
3650 }
3651 switch(encodingType) {
3652 case X509_ASN_ENCODING:
3653 Py_INCREF(x509_asn);
3654 return x509_asn;
3655 case PKCS_7_ASN_ENCODING:
3656 Py_INCREF(pkcs_7_asn);
3657 return pkcs_7_asn;
3658 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003659 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003660 }
3661}
3662
3663static PyObject*
3664parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3665{
3666 CERT_ENHKEY_USAGE *usage;
3667 DWORD size, error, i;
3668 PyObject *retval;
3669
3670 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3671 error = GetLastError();
3672 if (error == CRYPT_E_NOT_FOUND) {
3673 Py_RETURN_TRUE;
3674 }
3675 return PyErr_SetFromWindowsErr(error);
3676 }
3677
3678 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3679 if (usage == NULL) {
3680 return PyErr_NoMemory();
3681 }
3682
3683 /* Now get the actual enhanced usage property */
3684 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3685 PyMem_Free(usage);
3686 error = GetLastError();
3687 if (error == CRYPT_E_NOT_FOUND) {
3688 Py_RETURN_TRUE;
3689 }
3690 return PyErr_SetFromWindowsErr(error);
3691 }
3692 retval = PySet_New(NULL);
3693 if (retval == NULL) {
3694 goto error;
3695 }
3696 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3697 if (usage->rgpszUsageIdentifier[i]) {
3698 PyObject *oid;
3699 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003700 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003701 if (oid == NULL) {
3702 Py_CLEAR(retval);
3703 goto error;
3704 }
3705 err = PySet_Add(retval, oid);
3706 Py_DECREF(oid);
3707 if (err == -1) {
3708 Py_CLEAR(retval);
3709 goto error;
3710 }
3711 }
3712 }
3713 error:
3714 PyMem_Free(usage);
3715 return retval;
3716}
3717
3718PyDoc_STRVAR(PySSL_enum_certificates_doc,
3719"enum_certificates(store_name) -> []\n\
3720\n\
3721Retrieve certificates from Windows' cert store. store_name may be one of\n\
3722'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3723The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3724encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3725PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3726boolean True.");
3727
3728static PyObject *
3729PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3730{
3731 char *kwlist[] = {"store_name", NULL};
3732 char *store_name;
3733 HCERTSTORE hStore = NULL;
3734 PCCERT_CONTEXT pCertCtx = NULL;
3735 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3736 PyObject *result = NULL;
3737
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003738 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003739 kwlist, &store_name)) {
3740 return NULL;
3741 }
3742 result = PyList_New(0);
3743 if (result == NULL) {
3744 return NULL;
3745 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003746 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3747 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3748 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003749 if (hStore == NULL) {
3750 Py_DECREF(result);
3751 return PyErr_SetFromWindowsErr(GetLastError());
3752 }
3753
3754 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3755 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3756 pCertCtx->cbCertEncoded);
3757 if (!cert) {
3758 Py_CLEAR(result);
3759 break;
3760 }
3761 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3762 Py_CLEAR(result);
3763 break;
3764 }
3765 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3766 if (keyusage == Py_True) {
3767 Py_DECREF(keyusage);
3768 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3769 }
3770 if (keyusage == NULL) {
3771 Py_CLEAR(result);
3772 break;
3773 }
3774 if ((tup = PyTuple_New(3)) == NULL) {
3775 Py_CLEAR(result);
3776 break;
3777 }
3778 PyTuple_SET_ITEM(tup, 0, cert);
3779 cert = NULL;
3780 PyTuple_SET_ITEM(tup, 1, enc);
3781 enc = NULL;
3782 PyTuple_SET_ITEM(tup, 2, keyusage);
3783 keyusage = NULL;
3784 if (PyList_Append(result, tup) < 0) {
3785 Py_CLEAR(result);
3786 break;
3787 }
3788 Py_CLEAR(tup);
3789 }
3790 if (pCertCtx) {
3791 /* loop ended with an error, need to clean up context manually */
3792 CertFreeCertificateContext(pCertCtx);
3793 }
3794
3795 /* In error cases cert, enc and tup may not be NULL */
3796 Py_XDECREF(cert);
3797 Py_XDECREF(enc);
3798 Py_XDECREF(keyusage);
3799 Py_XDECREF(tup);
3800
3801 if (!CertCloseStore(hStore, 0)) {
3802 /* This error case might shadow another exception.*/
3803 Py_XDECREF(result);
3804 return PyErr_SetFromWindowsErr(GetLastError());
3805 }
3806 return result;
3807}
3808
3809PyDoc_STRVAR(PySSL_enum_crls_doc,
3810"enum_crls(store_name) -> []\n\
3811\n\
3812Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3813'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3814The function returns a list of (bytes, encoding_type) tuples. The\n\
3815encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3816PKCS_7_ASN_ENCODING.");
3817
3818static PyObject *
3819PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3820{
3821 char *kwlist[] = {"store_name", NULL};
3822 char *store_name;
3823 HCERTSTORE hStore = NULL;
3824 PCCRL_CONTEXT pCrlCtx = NULL;
3825 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3826 PyObject *result = NULL;
3827
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003828 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003829 kwlist, &store_name)) {
3830 return NULL;
3831 }
3832 result = PyList_New(0);
3833 if (result == NULL) {
3834 return NULL;
3835 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003836 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3837 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3838 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003839 if (hStore == NULL) {
3840 Py_DECREF(result);
3841 return PyErr_SetFromWindowsErr(GetLastError());
3842 }
3843
3844 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3845 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3846 pCrlCtx->cbCrlEncoded);
3847 if (!crl) {
3848 Py_CLEAR(result);
3849 break;
3850 }
3851 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3852 Py_CLEAR(result);
3853 break;
3854 }
3855 if ((tup = PyTuple_New(2)) == NULL) {
3856 Py_CLEAR(result);
3857 break;
3858 }
3859 PyTuple_SET_ITEM(tup, 0, crl);
3860 crl = NULL;
3861 PyTuple_SET_ITEM(tup, 1, enc);
3862 enc = NULL;
3863
3864 if (PyList_Append(result, tup) < 0) {
3865 Py_CLEAR(result);
3866 break;
3867 }
3868 Py_CLEAR(tup);
3869 }
3870 if (pCrlCtx) {
3871 /* loop ended with an error, need to clean up context manually */
3872 CertFreeCRLContext(pCrlCtx);
3873 }
3874
3875 /* In error cases cert, enc and tup may not be NULL */
3876 Py_XDECREF(crl);
3877 Py_XDECREF(enc);
3878 Py_XDECREF(tup);
3879
3880 if (!CertCloseStore(hStore, 0)) {
3881 /* This error case might shadow another exception.*/
3882 Py_XDECREF(result);
3883 return PyErr_SetFromWindowsErr(GetLastError());
3884 }
3885 return result;
3886}
3887
3888#endif /* _MSC_VER */
3889
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003890/* List of functions exported by this module. */
3891
3892static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003893 {"_test_decode_cert", PySSL_test_decode_certificate,
3894 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003895#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003896 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3897 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003898 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3899 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003900#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003901#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003902 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3903 PySSL_RAND_egd_doc},
3904#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003905 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3906 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3907#ifdef _MSC_VER
3908 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3909 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3910 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3911 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3912#endif
3913 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3914 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3915 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3916 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003917 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003918};
3919
3920
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003921#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003922
3923/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003924 * of the Python C thread library
3925 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3926 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003927
3928static PyThread_type_lock *_ssl_locks = NULL;
3929
Christian Heimes10107812013-08-19 17:36:29 +02003930#if OPENSSL_VERSION_NUMBER >= 0x10000000
3931/* use new CRYPTO_THREADID API. */
3932static void
3933_ssl_threadid_callback(CRYPTO_THREADID *id)
3934{
3935 CRYPTO_THREADID_set_numeric(id,
3936 (unsigned long)PyThread_get_thread_ident());
3937}
3938#else
3939/* deprecated CRYPTO_set_id_callback() API. */
3940static unsigned long
3941_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003942 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003943}
Christian Heimes10107812013-08-19 17:36:29 +02003944#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003945
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003946static void _ssl_thread_locking_function
3947 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003948 /* this function is needed to perform locking on shared data
3949 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003950 structures that will be implicitly shared whenever multiple
3951 threads use OpenSSL.) Multi-threaded applications will
3952 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003953
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003954 locking_function() must be able to handle up to
3955 CRYPTO_num_locks() different mutex locks. It sets the n-th
3956 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003957
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003958 file and line are the file number of the function setting the
3959 lock. They can be useful for debugging.
3960 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003961
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003962 if ((_ssl_locks == NULL) ||
3963 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3964 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003965
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003966 if (mode & CRYPTO_LOCK) {
3967 PyThread_acquire_lock(_ssl_locks[n], 1);
3968 } else {
3969 PyThread_release_lock(_ssl_locks[n]);
3970 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003971}
3972
3973static int _setup_ssl_threads(void) {
3974
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003975 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003976
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003977 if (_ssl_locks == NULL) {
3978 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003979 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3980 if (_ssl_locks == NULL) {
3981 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003982 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003983 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003984 memset(_ssl_locks, 0,
3985 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003986 for (i = 0; i < _ssl_locks_count; i++) {
3987 _ssl_locks[i] = PyThread_allocate_lock();
3988 if (_ssl_locks[i] == NULL) {
3989 unsigned int j;
3990 for (j = 0; j < i; j++) {
3991 PyThread_free_lock(_ssl_locks[j]);
3992 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003993 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003994 return 0;
3995 }
3996 }
3997 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02003998#if OPENSSL_VERSION_NUMBER >= 0x10000000
3999 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4000#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004001 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004002#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004003 }
4004 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004005}
4006
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004007#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004008
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004009PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004010"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004011for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004012
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004013
4014
4015
4016static void
4017parse_openssl_version(unsigned long libver,
4018 unsigned int *major, unsigned int *minor,
4019 unsigned int *fix, unsigned int *patch,
4020 unsigned int *status)
4021{
4022 *status = libver & 0xF;
4023 libver >>= 4;
4024 *patch = libver & 0xFF;
4025 libver >>= 8;
4026 *fix = libver & 0xFF;
4027 libver >>= 8;
4028 *minor = libver & 0xFF;
4029 libver >>= 8;
4030 *major = libver & 0xFF;
4031}
4032
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004033PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004034init_ssl(void)
4035{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004036 PyObject *m, *d, *r;
4037 unsigned long libver;
4038 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004039 struct py_ssl_error_code *errcode;
4040 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004041
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004042 if (PyType_Ready(&PySSLContext_Type) < 0)
4043 return;
4044 if (PyType_Ready(&PySSLSocket_Type) < 0)
4045 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004046
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004047 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4048 if (m == NULL)
4049 return;
4050 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004051
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004052 /* Load _socket module and its C API */
4053 if (PySocketModule_ImportModuleAndAPI())
4054 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004055
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004056 /* Init OpenSSL */
4057 SSL_load_error_strings();
4058 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00004059#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004060#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004061 /* note that this will start threading if not already started */
4062 if (!_setup_ssl_threads()) {
4063 return;
4064 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004065#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4066 /* OpenSSL 1.1.0 builtin thread support is enabled */
4067 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004068#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004069#endif /* WITH_THREAD */
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004070 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004071
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004072 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004073 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4074 "ssl.SSLError", SSLError_doc,
4075 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004076 if (PySSLErrorObject == NULL)
4077 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004078 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4079
4080 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4081 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4082 PySSLErrorObject, NULL);
4083 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4084 "ssl.SSLWantReadError", SSLWantReadError_doc,
4085 PySSLErrorObject, NULL);
4086 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4087 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4088 PySSLErrorObject, NULL);
4089 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4090 "ssl.SSLSyscallError", SSLSyscallError_doc,
4091 PySSLErrorObject, NULL);
4092 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4093 "ssl.SSLEOFError", SSLEOFError_doc,
4094 PySSLErrorObject, NULL);
4095 if (PySSLZeroReturnErrorObject == NULL
4096 || PySSLWantReadErrorObject == NULL
4097 || PySSLWantWriteErrorObject == NULL
4098 || PySSLSyscallErrorObject == NULL
4099 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004100 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004101
4102 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4103 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4104 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4105 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4106 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4107
4108 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4109 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4110 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4111 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4112 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4113 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4114 return;
4115 if (PyDict_SetItemString(d, "_SSLContext",
4116 (PyObject *)&PySSLContext_Type) != 0)
4117 return;
4118 if (PyDict_SetItemString(d, "_SSLSocket",
4119 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004120 return;
4121 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4122 PY_SSL_ERROR_ZERO_RETURN);
4123 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4124 PY_SSL_ERROR_WANT_READ);
4125 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4126 PY_SSL_ERROR_WANT_WRITE);
4127 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4128 PY_SSL_ERROR_WANT_X509_LOOKUP);
4129 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4130 PY_SSL_ERROR_SYSCALL);
4131 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4132 PY_SSL_ERROR_SSL);
4133 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4134 PY_SSL_ERROR_WANT_CONNECT);
4135 /* non ssl.h errorcodes */
4136 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4137 PY_SSL_ERROR_EOF);
4138 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4139 PY_SSL_ERROR_INVALID_ERROR_CODE);
4140 /* cert requirements */
4141 PyModule_AddIntConstant(m, "CERT_NONE",
4142 PY_SSL_CERT_NONE);
4143 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4144 PY_SSL_CERT_OPTIONAL);
4145 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4146 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004147 /* CRL verification for verification_flags */
4148 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4149 0);
4150 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4151 X509_V_FLAG_CRL_CHECK);
4152 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4153 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4154 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4155 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004156#ifdef X509_V_FLAG_TRUSTED_FIRST
4157 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4158 X509_V_FLAG_TRUSTED_FIRST);
4159#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004160
4161 /* Alert Descriptions from ssl.h */
4162 /* note RESERVED constants no longer intended for use have been removed */
4163 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4164
4165#define ADD_AD_CONSTANT(s) \
4166 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4167 SSL_AD_##s)
4168
4169 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4170 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4171 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4172 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4173 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4174 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4175 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4176 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4177 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4178 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4179 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4180 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4181 ADD_AD_CONSTANT(UNKNOWN_CA);
4182 ADD_AD_CONSTANT(ACCESS_DENIED);
4183 ADD_AD_CONSTANT(DECODE_ERROR);
4184 ADD_AD_CONSTANT(DECRYPT_ERROR);
4185 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4186 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4187 ADD_AD_CONSTANT(INTERNAL_ERROR);
4188 ADD_AD_CONSTANT(USER_CANCELLED);
4189 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4190 /* Not all constants are in old OpenSSL versions */
4191#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4192 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4193#endif
4194#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4195 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4196#endif
4197#ifdef SSL_AD_UNRECOGNIZED_NAME
4198 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4199#endif
4200#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4201 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4202#endif
4203#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4204 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4205#endif
4206#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4207 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4208#endif
4209
4210#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004211
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004212 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004213#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004214 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4215 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004216#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004217#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004218 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4219 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004220#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004221 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004222 PY_SSL_VERSION_TLS);
4223 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4224 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004225 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4226 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004227#if HAVE_TLSv1_2
4228 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4229 PY_SSL_VERSION_TLS1_1);
4230 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4231 PY_SSL_VERSION_TLS1_2);
4232#endif
4233
4234 /* protocol options */
4235 PyModule_AddIntConstant(m, "OP_ALL",
4236 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4237 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4238 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4239 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4240#if HAVE_TLSv1_2
4241 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4242 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4243#endif
4244 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4245 SSL_OP_CIPHER_SERVER_PREFERENCE);
4246 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4247#ifdef SSL_OP_SINGLE_ECDH_USE
4248 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4249#endif
4250#ifdef SSL_OP_NO_COMPRESSION
4251 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4252 SSL_OP_NO_COMPRESSION);
4253#endif
4254
4255#if HAVE_SNI
4256 r = Py_True;
4257#else
4258 r = Py_False;
4259#endif
4260 Py_INCREF(r);
4261 PyModule_AddObject(m, "HAS_SNI", r);
4262
4263#if HAVE_OPENSSL_FINISHED
4264 r = Py_True;
4265#else
4266 r = Py_False;
4267#endif
4268 Py_INCREF(r);
4269 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4270
4271#ifdef OPENSSL_NO_ECDH
4272 r = Py_False;
4273#else
4274 r = Py_True;
4275#endif
4276 Py_INCREF(r);
4277 PyModule_AddObject(m, "HAS_ECDH", r);
4278
4279#ifdef OPENSSL_NPN_NEGOTIATED
4280 r = Py_True;
4281#else
4282 r = Py_False;
4283#endif
4284 Py_INCREF(r);
4285 PyModule_AddObject(m, "HAS_NPN", r);
4286
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004287#ifdef HAVE_ALPN
4288 r = Py_True;
4289#else
4290 r = Py_False;
4291#endif
4292 Py_INCREF(r);
4293 PyModule_AddObject(m, "HAS_ALPN", r);
4294
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004295 /* Mappings for error codes */
4296 err_codes_to_names = PyDict_New();
4297 err_names_to_codes = PyDict_New();
4298 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4299 return;
4300 errcode = error_codes;
4301 while (errcode->mnemonic != NULL) {
4302 PyObject *mnemo, *key;
4303 mnemo = PyUnicode_FromString(errcode->mnemonic);
4304 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4305 if (mnemo == NULL || key == NULL)
4306 return;
4307 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4308 return;
4309 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4310 return;
4311 Py_DECREF(key);
4312 Py_DECREF(mnemo);
4313 errcode++;
4314 }
4315 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4316 return;
4317 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4318 return;
4319
4320 lib_codes_to_names = PyDict_New();
4321 if (lib_codes_to_names == NULL)
4322 return;
4323 libcode = library_codes;
4324 while (libcode->library != NULL) {
4325 PyObject *mnemo, *key;
4326 key = PyLong_FromLong(libcode->code);
4327 mnemo = PyUnicode_FromString(libcode->library);
4328 if (key == NULL || mnemo == NULL)
4329 return;
4330 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4331 return;
4332 Py_DECREF(key);
4333 Py_DECREF(mnemo);
4334 libcode++;
4335 }
4336 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4337 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004338
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004339 /* OpenSSL version */
4340 /* SSLeay() gives us the version of the library linked against,
4341 which could be different from the headers version.
4342 */
4343 libver = SSLeay();
4344 r = PyLong_FromUnsignedLong(libver);
4345 if (r == NULL)
4346 return;
4347 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4348 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004349 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004350 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4351 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4352 return;
4353 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4354 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4355 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004356
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004357 libver = OPENSSL_VERSION_NUMBER;
4358 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4359 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4360 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4361 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004362}