blob: 213c7d21510f62b93619a950eae282301f51d805 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Benjamin Petersondaeb9252014-08-20 14:14:50 -050017#define PY_SSIZE_T_CLEAN
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000018#include "Python.h"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000019
Bill Janssen98d19da2007-09-10 21:51:02 +000020#ifdef WITH_THREAD
21#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020022
Christian Heimes0d604cf2013-08-21 13:26:05 +020023
Benjamin Petersondaeb9252014-08-20 14:14:50 -050024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Bill Janssen98d19da2007-09-10 21:51:02 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000029 PyThreadState *_save = NULL; \
Benjamin Petersondaeb9252014-08-20 14:14:50 -050030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Bill Janssen98d19da2007-09-10 21:51:02 +000034
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000035#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000036
Benjamin Petersondaeb9252014-08-20 14:14:50 -050037#define PySSL_BEGIN_ALLOW_THREADS_S(save)
38#define PySSL_END_ALLOW_THREADS_S(save)
Bill Janssen98d19da2007-09-10 21:51:02 +000039#define PySSL_BEGIN_ALLOW_THREADS
40#define PySSL_BLOCK_THREADS
41#define PySSL_UNBLOCK_THREADS
42#define PySSL_END_ALLOW_THREADS
43
44#endif
45
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000046/* Include symbols from _socket module */
47#include "socketmodule.h"
48
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000049#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000050#include <poll.h>
51#elif defined(HAVE_SYS_POLL_H)
52#include <sys/poll.h>
53#endif
54
Christian Heimesc2fc7c42016-09-05 23:37:13 +020055/* Don't warn about deprecated functions */
56#ifdef __GNUC__
57#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
58#endif
59#ifdef __clang__
60#pragma clang diagnostic ignored "-Wdeprecated-declarations"
61#endif
62
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000063/* Include OpenSSL header files */
64#include "openssl/rsa.h"
65#include "openssl/crypto.h"
66#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000067#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000068#include "openssl/pem.h"
69#include "openssl/ssl.h"
70#include "openssl/err.h"
71#include "openssl/rand.h"
72
73/* SSL error object */
74static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050075static PyObject *PySSLZeroReturnErrorObject;
76static PyObject *PySSLWantReadErrorObject;
77static PyObject *PySSLWantWriteErrorObject;
78static PyObject *PySSLSyscallErrorObject;
79static PyObject *PySSLEOFErrorObject;
80
81/* Error mappings */
82static PyObject *err_codes_to_names;
83static PyObject *err_names_to_codes;
84static PyObject *lib_codes_to_names;
85
86struct py_ssl_error_code {
87 const char *mnemonic;
88 int library, reason;
89};
90struct py_ssl_library_code {
91 const char *library;
92 int code;
93};
94
95/* Include generated data (error codes) */
96#include "_ssl_data.h"
97
Christian Heimesc2fc7c42016-09-05 23:37:13 +020098#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
99# define OPENSSL_VERSION_1_1 1
100#endif
101
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500102/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
103 http://www.openssl.org/news/changelog.html
104 */
105#if OPENSSL_VERSION_NUMBER >= 0x10001000L
106# define HAVE_TLSv1_2 1
107#else
108# define HAVE_TLSv1_2 0
109#endif
110
111/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
112 * This includes the SSL_set_SSL_CTX() function.
113 */
114#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
115# define HAVE_SNI 1
116#else
117# define HAVE_SNI 0
118#endif
119
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500120/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500121#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500122# define HAVE_ALPN
123#endif
124
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200125#ifndef INVALID_SOCKET /* MS defines this */
126#define INVALID_SOCKET (-1)
127#endif
128
129#ifdef OPENSSL_VERSION_1_1
130/* OpenSSL 1.1.0+ */
131#ifndef OPENSSL_NO_SSL2
132#define OPENSSL_NO_SSL2
133#endif
134#else /* OpenSSL < 1.1.0 */
135#if defined(WITH_THREAD)
136#define HAVE_OPENSSL_CRYPTO_LOCK
137#endif
138
139#define TLS_method SSLv23_method
140
141static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
142{
143 return ne->set;
144}
145
146#ifndef OPENSSL_NO_COMP
147static int COMP_get_type(const COMP_METHOD *meth)
148{
149 return meth->type;
150}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200151#endif
152
153static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
154{
155 return ctx->default_passwd_callback;
156}
157
158static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
159{
160 return ctx->default_passwd_callback_userdata;
161}
162
163static int X509_OBJECT_get_type(X509_OBJECT *x)
164{
165 return x->type;
166}
167
168static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
169{
170 return x->data.x509;
171}
172
173static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
174 return store->objs;
175}
176
177static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
178{
179 return store->param;
180}
181#endif /* OpenSSL < 1.1.0 or LibreSSL */
182
183
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500184enum py_ssl_error {
185 /* these mirror ssl.h */
186 PY_SSL_ERROR_NONE,
187 PY_SSL_ERROR_SSL,
188 PY_SSL_ERROR_WANT_READ,
189 PY_SSL_ERROR_WANT_WRITE,
190 PY_SSL_ERROR_WANT_X509_LOOKUP,
191 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
192 PY_SSL_ERROR_ZERO_RETURN,
193 PY_SSL_ERROR_WANT_CONNECT,
194 /* start of non ssl.h errorcodes */
195 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
196 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
197 PY_SSL_ERROR_INVALID_ERROR_CODE
198};
199
200enum py_ssl_server_or_client {
201 PY_SSL_CLIENT,
202 PY_SSL_SERVER
203};
204
205enum py_ssl_cert_requirements {
206 PY_SSL_CERT_NONE,
207 PY_SSL_CERT_OPTIONAL,
208 PY_SSL_CERT_REQUIRED
209};
210
211enum py_ssl_version {
212 PY_SSL_VERSION_SSL2,
213 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200214 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500215#if HAVE_TLSv1_2
216 PY_SSL_VERSION_TLS1,
217 PY_SSL_VERSION_TLS1_1,
218 PY_SSL_VERSION_TLS1_2
219#else
220 PY_SSL_VERSION_TLS1
221#endif
222};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000223
Bill Janssen98d19da2007-09-10 21:51:02 +0000224#ifdef WITH_THREAD
225
226/* serves as a flag to see whether we've initialized the SSL thread support. */
227/* 0 means no, greater than 0 means yes */
228
229static unsigned int _ssl_locks_count = 0;
230
231#endif /* def WITH_THREAD */
232
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000233/* SSL socket object */
234
235#define X509_NAME_MAXLEN 256
236
237/* RAND_* APIs got added to OpenSSL in 0.9.5 */
238#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
239# define HAVE_OPENSSL_RAND 1
240#else
241# undef HAVE_OPENSSL_RAND
242#endif
243
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500244/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
245 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
246 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
247#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
248# define HAVE_SSL_CTX_CLEAR_OPTIONS
249#else
250# undef HAVE_SSL_CTX_CLEAR_OPTIONS
251#endif
252
253/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
254 * older SSL, but let's be safe */
255#define PySSL_CB_MAXLEN 128
256
257/* SSL_get_finished got added to OpenSSL in 0.9.5 */
258#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
259# define HAVE_OPENSSL_FINISHED 1
260#else
261# define HAVE_OPENSSL_FINISHED 0
262#endif
263
264/* ECDH support got added to OpenSSL in 0.9.8 */
265#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
266# define OPENSSL_NO_ECDH
267#endif
268
269/* compression support got added to OpenSSL in 0.9.8 */
270#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
271# define OPENSSL_NO_COMP
272#endif
273
274/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
275#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
276# define HAVE_OPENSSL_VERIFY_PARAM
277#endif
278
279
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000281 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500282 SSL_CTX *ctx;
283#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500284 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500285 int npn_protocols_len;
286#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500287#ifdef HAVE_ALPN
288 unsigned char *alpn_protocols;
289 int alpn_protocols_len;
290#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500291#ifndef OPENSSL_NO_TLSEXT
292 PyObject *set_hostname;
293#endif
294 int check_hostname;
295} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500297typedef struct {
298 PyObject_HEAD
299 PySocketSockObject *Socket;
300 PyObject *ssl_sock;
301 SSL *ssl;
302 PySSLContext *ctx; /* weakref to SSL context */
303 X509 *peer_cert;
304 char shutdown_seen_zero;
305 char handshake_done;
306 enum py_ssl_server_or_client socket_type;
307} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000308
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500309static PyTypeObject PySSLContext_Type;
310static PyTypeObject PySSLSocket_Type;
311
312static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
313static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000314static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000315 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500316static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
317static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000318
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500319#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
320#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000321
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000322typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000323 SOCKET_IS_NONBLOCKING,
324 SOCKET_IS_BLOCKING,
325 SOCKET_HAS_TIMED_OUT,
326 SOCKET_HAS_BEEN_CLOSED,
327 SOCKET_TOO_LARGE_FOR_SELECT,
328 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000329} timeout_state;
330
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000331/* Wrap error strings with filename and line # */
332#define STRINGIFY1(x) #x
333#define STRINGIFY2(x) STRINGIFY1(x)
334#define ERRSTR1(x,y,z) (x ":" y ": " z)
335#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
336
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500337
338/*
339 * SSL errors.
340 */
341
342PyDoc_STRVAR(SSLError_doc,
343"An error occurred in the SSL implementation.");
344
345PyDoc_STRVAR(SSLZeroReturnError_doc,
346"SSL/TLS session closed cleanly.");
347
348PyDoc_STRVAR(SSLWantReadError_doc,
349"Non-blocking SSL socket needs to read more data\n"
350"before the requested operation can be completed.");
351
352PyDoc_STRVAR(SSLWantWriteError_doc,
353"Non-blocking SSL socket needs to write more data\n"
354"before the requested operation can be completed.");
355
356PyDoc_STRVAR(SSLSyscallError_doc,
357"System error when attempting SSL operation.");
358
359PyDoc_STRVAR(SSLEOFError_doc,
360"SSL/TLS connection terminated abruptly.");
361
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362
363static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500364SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500366 if (self->strerror != NULL) {
367 Py_INCREF(self->strerror);
368 return self->strerror;
369 }
370 else
371 return PyObject_Str(self->args);
372}
373
374static void
375fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
376 int lineno, unsigned long errcode)
377{
378 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
379 PyObject *init_value, *msg, *key;
380
381 if (errcode != 0) {
382 int lib, reason;
383
384 lib = ERR_GET_LIB(errcode);
385 reason = ERR_GET_REASON(errcode);
386 key = Py_BuildValue("ii", lib, reason);
387 if (key == NULL)
388 goto fail;
389 reason_obj = PyDict_GetItem(err_codes_to_names, key);
390 Py_DECREF(key);
391 if (reason_obj == NULL) {
392 /* XXX if reason < 100, it might reflect a library number (!!) */
393 PyErr_Clear();
394 }
395 key = PyLong_FromLong(lib);
396 if (key == NULL)
397 goto fail;
398 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
399 Py_DECREF(key);
400 if (lib_obj == NULL) {
401 PyErr_Clear();
402 }
403 if (errstr == NULL)
404 errstr = ERR_reason_error_string(errcode);
405 }
406 if (errstr == NULL)
407 errstr = "unknown error";
408
409 if (reason_obj && lib_obj)
410 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
411 lib_obj, reason_obj, errstr, lineno);
412 else if (lib_obj)
413 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
414 lib_obj, errstr, lineno);
415 else
416 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
417 if (msg == NULL)
418 goto fail;
419
420 init_value = Py_BuildValue("iN", ssl_errno, msg);
421 if (init_value == NULL)
422 goto fail;
423
424 err_value = PyObject_CallObject(type, init_value);
425 Py_DECREF(init_value);
426 if (err_value == NULL)
427 goto fail;
428
429 if (reason_obj == NULL)
430 reason_obj = Py_None;
431 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
432 goto fail;
433 if (lib_obj == NULL)
434 lib_obj = Py_None;
435 if (PyObject_SetAttrString(err_value, "library", lib_obj))
436 goto fail;
437 PyErr_SetObject(type, err_value);
438fail:
439 Py_XDECREF(err_value);
440}
441
442static PyObject *
443PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
444{
445 PyObject *type = PySSLErrorObject;
446 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000447 int err;
448 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500449 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000450
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000451 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500452 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000453
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000454 if (obj->ssl != NULL) {
455 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000456
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000457 switch (err) {
458 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500459 errstr = "TLS/SSL connection has been closed (EOF)";
460 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000461 p = PY_SSL_ERROR_ZERO_RETURN;
462 break;
463 case SSL_ERROR_WANT_READ:
464 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500465 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000466 p = PY_SSL_ERROR_WANT_READ;
467 break;
468 case SSL_ERROR_WANT_WRITE:
469 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500470 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000471 errstr = "The operation did not complete (write)";
472 break;
473 case SSL_ERROR_WANT_X509_LOOKUP:
474 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000475 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000476 break;
477 case SSL_ERROR_WANT_CONNECT:
478 p = PY_SSL_ERROR_WANT_CONNECT;
479 errstr = "The operation did not complete (connect)";
480 break;
481 case SSL_ERROR_SYSCALL:
482 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000483 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500484 PySocketSockObject *s = obj->Socket;
485 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000486 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500487 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000488 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000489 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000490 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500491 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000492 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500493 s->errorhandler();
494 Py_DECREF(s);
495 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000496 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000497 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500498 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000499 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000500 }
501 } else {
502 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000503 }
504 break;
505 }
506 case SSL_ERROR_SSL:
507 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000508 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500509 if (e == 0)
510 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000511 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000512 break;
513 }
514 default:
515 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
516 errstr = "Invalid error code";
517 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000518 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500519 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000520 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000521 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000522}
523
Bill Janssen98d19da2007-09-10 21:51:02 +0000524static PyObject *
525_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
526
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500527 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000528 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500529 else
530 errcode = 0;
531 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000532 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000533 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000534}
535
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500536/*
537 * SSL objects
538 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000539
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500540static PySSLSocket *
541newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
542 enum py_ssl_server_or_client socket_type,
543 char *server_hostname, PyObject *ssl_sock)
544{
545 PySSLSocket *self;
546 SSL_CTX *ctx = sslctx->ctx;
547 long mode;
548
549 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000550 if (self == NULL)
551 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000553 self->peer_cert = NULL;
554 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000555 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500556 self->ssl_sock = NULL;
557 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200558 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500559 self->handshake_done = 0;
560 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000561
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000562 /* Make sure the SSL error state is initialized */
563 (void) ERR_get_state();
564 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000565
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000566 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500567 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000568 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500569 SSL_set_app_data(self->ssl,self);
570 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
571 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000572#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500573 mode |= SSL_MODE_AUTO_RETRY;
574#endif
575 SSL_set_mode(self->ssl, mode);
576
577#if HAVE_SNI
578 if (server_hostname != NULL)
579 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000580#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000581
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000582 /* If the socket is in non-blocking mode or timeout mode, set the BIO
583 * to non-blocking mode (blocking is the default)
584 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500585 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000586 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
587 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
588 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000589
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000590 PySSL_BEGIN_ALLOW_THREADS
591 if (socket_type == PY_SSL_CLIENT)
592 SSL_set_connect_state(self->ssl);
593 else
594 SSL_set_accept_state(self->ssl);
595 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000596
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500597 self->socket_type = socket_type;
598 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400600 if (ssl_sock != Py_None) {
601 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
602 if (self->ssl_sock == NULL) {
603 Py_DECREF(self);
604 return NULL;
605 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500606 }
607 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000608}
609
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000610
611/* SSL object methods */
612
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500613static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000614{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000615 int ret;
616 int err;
617 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500618 PySocketSockObject *sock = self->Socket;
619
620 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000621
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000622 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500623 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000624 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
625 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000626
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000627 /* Actually negotiate SSL connection */
628 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
629 do {
630 PySSL_BEGIN_ALLOW_THREADS
631 ret = SSL_do_handshake(self->ssl);
632 err = SSL_get_error(self->ssl, ret);
633 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500634 if (PyErr_CheckSignals())
635 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000636 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500637 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000638 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500639 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000640 } else {
641 sockstate = SOCKET_OPERATION_OK;
642 }
643 if (sockstate == SOCKET_HAS_TIMED_OUT) {
644 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000645 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500646 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000647 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
648 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000649 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500650 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000651 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
652 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000653 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500654 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000655 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
656 break;
657 }
658 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500659 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000660 if (ret < 1)
661 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000662
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000663 if (self->peer_cert)
664 X509_free (self->peer_cert);
665 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500666 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000667 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500668 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000669
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000670 Py_INCREF(Py_None);
671 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000672
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500673error:
674 Py_DECREF(sock);
675 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000676}
677
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000678static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000679_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000680
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000681 char namebuf[X509_NAME_MAXLEN];
682 int buflen;
683 PyObject *name_obj;
684 PyObject *value_obj;
685 PyObject *attr;
686 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000687
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000688 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
689 if (buflen < 0) {
690 _setSSLError(NULL, 0, __FILE__, __LINE__);
691 goto fail;
692 }
693 name_obj = PyString_FromStringAndSize(namebuf, buflen);
694 if (name_obj == NULL)
695 goto fail;
696
697 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
698 if (buflen < 0) {
699 _setSSLError(NULL, 0, __FILE__, __LINE__);
700 Py_DECREF(name_obj);
701 goto fail;
702 }
703 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000704 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 OPENSSL_free(valuebuf);
706 if (value_obj == NULL) {
707 Py_DECREF(name_obj);
708 goto fail;
709 }
710 attr = PyTuple_New(2);
711 if (attr == NULL) {
712 Py_DECREF(name_obj);
713 Py_DECREF(value_obj);
714 goto fail;
715 }
716 PyTuple_SET_ITEM(attr, 0, name_obj);
717 PyTuple_SET_ITEM(attr, 1, value_obj);
718 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000719
Bill Janssen98d19da2007-09-10 21:51:02 +0000720 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000721 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000722}
723
724static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000725_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000726{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000727 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
728 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
729 PyObject *rdnt;
730 PyObject *attr = NULL; /* tuple to hold an attribute */
731 int entry_count = X509_NAME_entry_count(xname);
732 X509_NAME_ENTRY *entry;
733 ASN1_OBJECT *name;
734 ASN1_STRING *value;
735 int index_counter;
736 int rdn_level = -1;
737 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000738
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000739 dn = PyList_New(0);
740 if (dn == NULL)
741 return NULL;
742 /* now create another tuple to hold the top-level RDN */
743 rdn = PyList_New(0);
744 if (rdn == NULL)
745 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000746
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000747 for (index_counter = 0;
748 index_counter < entry_count;
749 index_counter++)
750 {
751 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000752
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000753 /* check to see if we've gotten to a new RDN */
754 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200755 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000756 /* yes, new RDN */
757 /* add old RDN to DN */
758 rdnt = PyList_AsTuple(rdn);
759 Py_DECREF(rdn);
760 if (rdnt == NULL)
761 goto fail0;
762 retcode = PyList_Append(dn, rdnt);
763 Py_DECREF(rdnt);
764 if (retcode < 0)
765 goto fail0;
766 /* create new RDN */
767 rdn = PyList_New(0);
768 if (rdn == NULL)
769 goto fail0;
770 }
771 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200772 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000773
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000774 /* now add this attribute to the current RDN */
775 name = X509_NAME_ENTRY_get_object(entry);
776 value = X509_NAME_ENTRY_get_data(entry);
777 attr = _create_tuple_for_attribute(name, value);
778 /*
779 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
780 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500781 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
782 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000783 */
784 if (attr == NULL)
785 goto fail1;
786 retcode = PyList_Append(rdn, attr);
787 Py_DECREF(attr);
788 if (retcode < 0)
789 goto fail1;
790 }
791 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100792 if (rdn != NULL) {
793 if (PyList_GET_SIZE(rdn) > 0) {
794 rdnt = PyList_AsTuple(rdn);
795 Py_DECREF(rdn);
796 if (rdnt == NULL)
797 goto fail0;
798 retcode = PyList_Append(dn, rdnt);
799 Py_DECREF(rdnt);
800 if (retcode < 0)
801 goto fail0;
802 }
803 else {
804 Py_DECREF(rdn);
805 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000806 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000807
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000808 /* convert list to tuple */
809 rdnt = PyList_AsTuple(dn);
810 Py_DECREF(dn);
811 if (rdnt == NULL)
812 return NULL;
813 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000814
815 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000816 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000817
818 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000819 Py_XDECREF(dn);
820 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821}
822
823static PyObject *
824_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000825
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000826 /* this code follows the procedure outlined in
827 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
828 function to extract the STACK_OF(GENERAL_NAME),
829 then iterates through the stack to add the
830 names. */
831
832 int i, j;
833 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200834 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000835 X509_EXTENSION *ext = NULL;
836 GENERAL_NAMES *names = NULL;
837 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000838 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000839 BIO *biobuf = NULL;
840 char buf[2048];
841 char *vptr;
842 int len;
843 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000844#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000845 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000846#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000847 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000848#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000849
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000850 if (certificate == NULL)
851 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000852
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000853 /* get a memory buffer */
854 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000855
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200856 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000857 while ((i = X509_get_ext_by_NID(
858 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000859
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000860 if (peer_alt_names == Py_None) {
861 peer_alt_names = PyList_New(0);
862 if (peer_alt_names == NULL)
863 goto fail;
864 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000865
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000866 /* now decode the altName */
867 ext = X509_get_ext(certificate, i);
868 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500869 PyErr_SetString
870 (PySSLErrorObject,
871 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000872 goto fail;
873 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000874
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200875 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000876 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500877 names = (GENERAL_NAMES*)
878 (ASN1_item_d2i(NULL,
879 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200880 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500881 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000882 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500883 names = (GENERAL_NAMES*)
884 (method->d2i(NULL,
885 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200886 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000887
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000888 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000889 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200890 int gntype;
891 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000893 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200894 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200895 switch (gntype) {
896 case GEN_DIRNAME:
897 /* we special-case DirName as a tuple of
898 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000899
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000900 t = PyTuple_New(2);
901 if (t == NULL) {
902 goto fail;
903 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000904
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000905 v = PyString_FromString("DirName");
906 if (v == NULL) {
907 Py_DECREF(t);
908 goto fail;
909 }
910 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000911
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000912 v = _create_tuple_for_X509_NAME (name->d.dirn);
913 if (v == NULL) {
914 Py_DECREF(t);
915 goto fail;
916 }
917 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200918 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000919
Christian Heimes88b174c2013-08-17 00:54:47 +0200920 case GEN_EMAIL:
921 case GEN_DNS:
922 case GEN_URI:
923 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
924 correctly, CVE-2013-4238 */
925 t = PyTuple_New(2);
926 if (t == NULL)
927 goto fail;
928 switch (gntype) {
929 case GEN_EMAIL:
930 v = PyString_FromString("email");
931 as = name->d.rfc822Name;
932 break;
933 case GEN_DNS:
934 v = PyString_FromString("DNS");
935 as = name->d.dNSName;
936 break;
937 case GEN_URI:
938 v = PyString_FromString("URI");
939 as = name->d.uniformResourceIdentifier;
940 break;
941 }
942 if (v == NULL) {
943 Py_DECREF(t);
944 goto fail;
945 }
946 PyTuple_SET_ITEM(t, 0, v);
947 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
948 ASN1_STRING_length(as));
949 if (v == NULL) {
950 Py_DECREF(t);
951 goto fail;
952 }
953 PyTuple_SET_ITEM(t, 1, v);
954 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000955
Christian Heimes6663eb62016-09-06 23:25:35 +0200956 case GEN_RID:
957 t = PyTuple_New(2);
958 if (t == NULL)
959 goto fail;
960
961 v = PyUnicode_FromString("Registered ID");
962 if (v == NULL) {
963 Py_DECREF(t);
964 goto fail;
965 }
966 PyTuple_SET_ITEM(t, 0, v);
967
968 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
969 if (len < 0) {
970 Py_DECREF(t);
971 _setSSLError(NULL, 0, __FILE__, __LINE__);
972 goto fail;
973 } else if (len >= (int)sizeof(buf)) {
974 v = PyUnicode_FromString("<INVALID>");
975 } else {
976 v = PyUnicode_FromStringAndSize(buf, len);
977 }
978 if (v == NULL) {
979 Py_DECREF(t);
980 goto fail;
981 }
982 PyTuple_SET_ITEM(t, 1, v);
983 break;
984
Christian Heimes88b174c2013-08-17 00:54:47 +0200985 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000986 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200987 switch (gntype) {
988 /* check for new general name type */
989 case GEN_OTHERNAME:
990 case GEN_X400:
991 case GEN_EDIPARTY:
992 case GEN_IPADD:
993 case GEN_RID:
994 break;
995 default:
996 if (PyErr_Warn(PyExc_RuntimeWarning,
997 "Unknown general name type") == -1) {
998 goto fail;
999 }
1000 break;
1001 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001002 (void) BIO_reset(biobuf);
1003 GENERAL_NAME_print(biobuf, name);
1004 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1005 if (len < 0) {
1006 _setSSLError(NULL, 0, __FILE__, __LINE__);
1007 goto fail;
1008 }
1009 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001010 if (vptr == NULL) {
1011 PyErr_Format(PyExc_ValueError,
1012 "Invalid value %.200s",
1013 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001014 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001015 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001016 t = PyTuple_New(2);
1017 if (t == NULL)
1018 goto fail;
1019 v = PyString_FromStringAndSize(buf, (vptr - buf));
1020 if (v == NULL) {
1021 Py_DECREF(t);
1022 goto fail;
1023 }
1024 PyTuple_SET_ITEM(t, 0, v);
1025 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1026 if (v == NULL) {
1027 Py_DECREF(t);
1028 goto fail;
1029 }
1030 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001031 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001032 }
1033
1034 /* and add that rendering to the list */
1035
1036 if (PyList_Append(peer_alt_names, t) < 0) {
1037 Py_DECREF(t);
1038 goto fail;
1039 }
1040 Py_DECREF(t);
1041 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001042 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001043 }
1044 BIO_free(biobuf);
1045 if (peer_alt_names != Py_None) {
1046 v = PyList_AsTuple(peer_alt_names);
1047 Py_DECREF(peer_alt_names);
1048 return v;
1049 } else {
1050 return peer_alt_names;
1051 }
1052
Bill Janssen98d19da2007-09-10 21:51:02 +00001053
1054 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001055 if (biobuf != NULL)
1056 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001057
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001058 if (peer_alt_names != Py_None) {
1059 Py_XDECREF(peer_alt_names);
1060 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001061
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001062 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001063}
1064
1065static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001066_get_aia_uri(X509 *certificate, int nid) {
1067 PyObject *lst = NULL, *ostr = NULL;
1068 int i, result;
1069 AUTHORITY_INFO_ACCESS *info;
1070
1071 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001072 if (info == NULL)
1073 return Py_None;
1074 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1075 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001076 return Py_None;
1077 }
1078
1079 if ((lst = PyList_New(0)) == NULL) {
1080 goto fail;
1081 }
1082
1083 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1084 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1085 ASN1_IA5STRING *uri;
1086
1087 if ((OBJ_obj2nid(ad->method) != nid) ||
1088 (ad->location->type != GEN_URI)) {
1089 continue;
1090 }
1091 uri = ad->location->d.uniformResourceIdentifier;
1092 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1093 uri->length);
1094 if (ostr == NULL) {
1095 goto fail;
1096 }
1097 result = PyList_Append(lst, ostr);
1098 Py_DECREF(ostr);
1099 if (result < 0) {
1100 goto fail;
1101 }
1102 }
1103 AUTHORITY_INFO_ACCESS_free(info);
1104
1105 /* convert to tuple or None */
1106 if (PyList_Size(lst) == 0) {
1107 Py_DECREF(lst);
1108 return Py_None;
1109 } else {
1110 PyObject *tup;
1111 tup = PyList_AsTuple(lst);
1112 Py_DECREF(lst);
1113 return tup;
1114 }
1115
1116 fail:
1117 AUTHORITY_INFO_ACCESS_free(info);
1118 Py_XDECREF(lst);
1119 return NULL;
1120}
1121
1122static PyObject *
1123_get_crl_dp(X509 *certificate) {
1124 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001125 int i, j;
1126 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001127
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001128 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001129
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001130 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001131 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001132
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001133 lst = PyList_New(0);
1134 if (lst == NULL)
1135 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001136
1137 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1138 DIST_POINT *dp;
1139 STACK_OF(GENERAL_NAME) *gns;
1140
1141 dp = sk_DIST_POINT_value(dps, i);
1142 gns = dp->distpoint->name.fullname;
1143
1144 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1145 GENERAL_NAME *gn;
1146 ASN1_IA5STRING *uri;
1147 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001148 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001149
1150 gn = sk_GENERAL_NAME_value(gns, j);
1151 if (gn->type != GEN_URI) {
1152 continue;
1153 }
1154 uri = gn->d.uniformResourceIdentifier;
1155 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1156 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001157 if (ouri == NULL)
1158 goto done;
1159
1160 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001161 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001162 if (err < 0)
1163 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001164 }
1165 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001166
1167 /* Convert to tuple. */
1168 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1169
1170 done:
1171 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001172 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001173 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001174}
1175
1176static PyObject *
1177_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001178
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001179 PyObject *retval = NULL;
1180 BIO *biobuf = NULL;
1181 PyObject *peer;
1182 PyObject *peer_alt_names = NULL;
1183 PyObject *issuer;
1184 PyObject *version;
1185 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001186 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001187 ASN1_INTEGER *serialNumber;
1188 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001189 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001190 ASN1_TIME *notBefore, *notAfter;
1191 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001192
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001193 retval = PyDict_New();
1194 if (retval == NULL)
1195 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001196
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001197 peer = _create_tuple_for_X509_NAME(
1198 X509_get_subject_name(certificate));
1199 if (peer == NULL)
1200 goto fail0;
1201 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1202 Py_DECREF(peer);
1203 goto fail0;
1204 }
1205 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001206
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001207 issuer = _create_tuple_for_X509_NAME(
1208 X509_get_issuer_name(certificate));
1209 if (issuer == NULL)
1210 goto fail0;
1211 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001212 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001213 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001214 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001215 Py_DECREF(issuer);
1216
1217 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1218 if (version == NULL)
1219 goto fail0;
1220 if (PyDict_SetItemString(retval, "version", version) < 0) {
1221 Py_DECREF(version);
1222 goto fail0;
1223 }
1224 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001225
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001226 /* get a memory buffer */
1227 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001228
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001229 (void) BIO_reset(biobuf);
1230 serialNumber = X509_get_serialNumber(certificate);
1231 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1232 i2a_ASN1_INTEGER(biobuf, serialNumber);
1233 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1234 if (len < 0) {
1235 _setSSLError(NULL, 0, __FILE__, __LINE__);
1236 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001237 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001238 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1239 if (sn_obj == NULL)
1240 goto fail1;
1241 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1242 Py_DECREF(sn_obj);
1243 goto fail1;
1244 }
1245 Py_DECREF(sn_obj);
1246
1247 (void) BIO_reset(biobuf);
1248 notBefore = X509_get_notBefore(certificate);
1249 ASN1_TIME_print(biobuf, notBefore);
1250 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1251 if (len < 0) {
1252 _setSSLError(NULL, 0, __FILE__, __LINE__);
1253 goto fail1;
1254 }
1255 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1256 if (pnotBefore == NULL)
1257 goto fail1;
1258 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1259 Py_DECREF(pnotBefore);
1260 goto fail1;
1261 }
1262 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001263
1264 (void) BIO_reset(biobuf);
1265 notAfter = X509_get_notAfter(certificate);
1266 ASN1_TIME_print(biobuf, notAfter);
1267 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1268 if (len < 0) {
1269 _setSSLError(NULL, 0, __FILE__, __LINE__);
1270 goto fail1;
1271 }
1272 pnotAfter = PyString_FromStringAndSize(buf, len);
1273 if (pnotAfter == NULL)
1274 goto fail1;
1275 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1276 Py_DECREF(pnotAfter);
1277 goto fail1;
1278 }
1279 Py_DECREF(pnotAfter);
1280
1281 /* Now look for subjectAltName */
1282
1283 peer_alt_names = _get_peer_alt_names(certificate);
1284 if (peer_alt_names == NULL)
1285 goto fail1;
1286 else if (peer_alt_names != Py_None) {
1287 if (PyDict_SetItemString(retval, "subjectAltName",
1288 peer_alt_names) < 0) {
1289 Py_DECREF(peer_alt_names);
1290 goto fail1;
1291 }
1292 Py_DECREF(peer_alt_names);
1293 }
1294
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001295 /* Authority Information Access: OCSP URIs */
1296 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1297 if (obj == NULL) {
1298 goto fail1;
1299 } else if (obj != Py_None) {
1300 result = PyDict_SetItemString(retval, "OCSP", obj);
1301 Py_DECREF(obj);
1302 if (result < 0) {
1303 goto fail1;
1304 }
1305 }
1306
1307 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1308 if (obj == NULL) {
1309 goto fail1;
1310 } else if (obj != Py_None) {
1311 result = PyDict_SetItemString(retval, "caIssuers", obj);
1312 Py_DECREF(obj);
1313 if (result < 0) {
1314 goto fail1;
1315 }
1316 }
1317
1318 /* CDP (CRL distribution points) */
1319 obj = _get_crl_dp(certificate);
1320 if (obj == NULL) {
1321 goto fail1;
1322 } else if (obj != Py_None) {
1323 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1324 Py_DECREF(obj);
1325 if (result < 0) {
1326 goto fail1;
1327 }
1328 }
1329
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001330 BIO_free(biobuf);
1331 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001332
1333 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001334 if (biobuf != NULL)
1335 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001336 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001337 Py_XDECREF(retval);
1338 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001339}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001340
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001341static PyObject *
1342_certificate_to_der(X509 *certificate)
1343{
1344 unsigned char *bytes_buf = NULL;
1345 int len;
1346 PyObject *retval;
1347
1348 bytes_buf = NULL;
1349 len = i2d_X509(certificate, &bytes_buf);
1350 if (len < 0) {
1351 _setSSLError(NULL, 0, __FILE__, __LINE__);
1352 return NULL;
1353 }
1354 /* this is actually an immutable bytes sequence */
1355 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1356 OPENSSL_free(bytes_buf);
1357 return retval;
1358}
Bill Janssen98d19da2007-09-10 21:51:02 +00001359
1360static PyObject *
1361PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1362
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001363 PyObject *retval = NULL;
1364 char *filename = NULL;
1365 X509 *x=NULL;
1366 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001367
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001368 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001369 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001370
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001371 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001372 PyErr_SetString(PySSLErrorObject,
1373 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001374 goto fail0;
1375 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001376
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001377 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001378 PyErr_SetString(PySSLErrorObject,
1379 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001380 goto fail0;
1381 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001382
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001383 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1384 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001385 PyErr_SetString(PySSLErrorObject,
1386 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001387 goto fail0;
1388 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001389
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001390 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001391 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001392
1393 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001394
1395 if (cert != NULL) BIO_free(cert);
1396 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001397}
1398
1399
1400static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001401PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001402{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001403 int verification;
1404 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001405 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001406
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001407 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1408 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001409
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001410 if (!self->handshake_done) {
1411 PyErr_SetString(PyExc_ValueError,
1412 "handshake not done yet");
1413 return NULL;
1414 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001415 if (!self->peer_cert)
1416 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001417
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001418 b = PyObject_IsTrue(binary_mode);
1419 if (b < 0)
1420 return NULL;
1421 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001422 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001423 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001424 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001425 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001426 if ((verification & SSL_VERIFY_PEER) == 0)
1427 return PyDict_New();
1428 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001429 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001430 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001431}
1432
1433PyDoc_STRVAR(PySSL_peercert_doc,
1434"peer_certificate([der=False]) -> certificate\n\
1435\n\
1436Returns the certificate for the peer. If no certificate was provided,\n\
1437returns None. If a certificate was provided, but not validated, returns\n\
1438an empty dictionary. Otherwise returns a dict containing information\n\
1439about the peer certificate.\n\
1440\n\
1441If the optional argument is True, returns a DER-encoded copy of the\n\
1442peer certificate, or None if no certificate was provided. This will\n\
1443return the certificate even if it wasn't validated.");
1444
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001445static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001446
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001447 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001448 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001449 char *cipher_name;
1450 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001453 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001454 current = SSL_get_current_cipher(self->ssl);
1455 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001456 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001457
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001458 retval = PyTuple_New(3);
1459 if (retval == NULL)
1460 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001461
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001462 cipher_name = (char *) SSL_CIPHER_get_name(current);
1463 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001464 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001465 PyTuple_SET_ITEM(retval, 0, Py_None);
1466 } else {
1467 v = PyString_FromString(cipher_name);
1468 if (v == NULL)
1469 goto fail0;
1470 PyTuple_SET_ITEM(retval, 0, v);
1471 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001472 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001473 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001474 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001475 PyTuple_SET_ITEM(retval, 1, Py_None);
1476 } else {
1477 v = PyString_FromString(cipher_protocol);
1478 if (v == NULL)
1479 goto fail0;
1480 PyTuple_SET_ITEM(retval, 1, v);
1481 }
1482 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1483 if (v == NULL)
1484 goto fail0;
1485 PyTuple_SET_ITEM(retval, 2, v);
1486 return retval;
1487
Bill Janssen98d19da2007-09-10 21:51:02 +00001488 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001489 Py_DECREF(retval);
1490 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001491}
1492
Alex Gaynore98205d2014-09-04 13:33:22 -07001493static PyObject *PySSL_version(PySSLSocket *self)
1494{
1495 const char *version;
1496
1497 if (self->ssl == NULL)
1498 Py_RETURN_NONE;
1499 version = SSL_get_version(self->ssl);
1500 if (!strcmp(version, "unknown"))
1501 Py_RETURN_NONE;
1502 return PyUnicode_FromString(version);
1503}
1504
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001505#ifdef OPENSSL_NPN_NEGOTIATED
1506static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1507 const unsigned char *out;
1508 unsigned int outlen;
1509
1510 SSL_get0_next_proto_negotiated(self->ssl,
1511 &out, &outlen);
1512
1513 if (out == NULL)
1514 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001515 return PyString_FromStringAndSize((char *)out, outlen);
1516}
1517#endif
1518
1519#ifdef HAVE_ALPN
1520static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1521 const unsigned char *out;
1522 unsigned int outlen;
1523
1524 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1525
1526 if (out == NULL)
1527 Py_RETURN_NONE;
1528 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001529}
1530#endif
1531
1532static PyObject *PySSL_compression(PySSLSocket *self) {
1533#ifdef OPENSSL_NO_COMP
1534 Py_RETURN_NONE;
1535#else
1536 const COMP_METHOD *comp_method;
1537 const char *short_name;
1538
1539 if (self->ssl == NULL)
1540 Py_RETURN_NONE;
1541 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001542 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001543 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001544 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001545 if (short_name == NULL)
1546 Py_RETURN_NONE;
1547 return PyBytes_FromString(short_name);
1548#endif
1549}
1550
1551static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1552 Py_INCREF(self->ctx);
1553 return self->ctx;
1554}
1555
1556static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1557 void *closure) {
1558
1559 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1560#if !HAVE_SNI
1561 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1562 "context is not supported by your OpenSSL library");
1563 return -1;
1564#else
1565 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001566 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001567 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1568#endif
1569 } else {
1570 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1571 return -1;
1572 }
1573
1574 return 0;
1575}
1576
1577PyDoc_STRVAR(PySSL_set_context_doc,
1578"_setter_context(ctx)\n\
1579\
1580This changes the context associated with the SSLSocket. This is typically\n\
1581used from within a callback function set by the set_servername_callback\n\
1582on the SSLContext to change the certificate information associated with the\n\
1583SSLSocket before the cryptographic exchange handshake messages\n");
1584
1585
1586
1587static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001589 if (self->peer_cert) /* Possible not to have one? */
1590 X509_free (self->peer_cert);
1591 if (self->ssl)
1592 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001593 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001594 Py_XDECREF(self->ssl_sock);
1595 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001596 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001597}
1598
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001599/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001600 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001601 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001602 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001603
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001604static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001605check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001606{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001607 fd_set fds;
1608 struct timeval tv;
1609 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001610
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001611 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1612 if (s->sock_timeout < 0.0)
1613 return SOCKET_IS_BLOCKING;
1614 else if (s->sock_timeout == 0.0)
1615 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001616
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001617 /* Guard against closed socket */
1618 if (s->sock_fd < 0)
1619 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001620
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001621 /* Prefer poll, if available, since you can poll() any fd
1622 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001623#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001624 {
1625 struct pollfd pollfd;
1626 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001627
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001628 pollfd.fd = s->sock_fd;
1629 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001630
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001631 /* s->sock_timeout is in seconds, timeout in ms */
1632 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1633 PySSL_BEGIN_ALLOW_THREADS
1634 rc = poll(&pollfd, 1, timeout);
1635 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001636
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001637 goto normal_return;
1638 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001639#endif
1640
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001641 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001642 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001643 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001644
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001645 /* Construct the arguments to select */
1646 tv.tv_sec = (int)s->sock_timeout;
1647 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1648 FD_ZERO(&fds);
1649 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001650
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001651 /* See if the socket is ready */
1652 PySSL_BEGIN_ALLOW_THREADS
1653 if (writing)
1654 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1655 else
1656 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1657 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001658
Bill Janssen934b16d2008-06-28 22:19:33 +00001659#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001660normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001661#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001662 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1663 (when we are able to write or when there's something to read) */
1664 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001665}
1666
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001667static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001668{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001669 Py_buffer buf;
1670 int len;
1671 int sockstate;
1672 int err;
1673 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001674 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001676 Py_INCREF(sock);
1677
1678 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1679 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001680 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001681 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001682
Victor Stinnerc1a44262013-06-25 00:48:02 +02001683 if (buf.len > INT_MAX) {
1684 PyErr_Format(PyExc_OverflowError,
1685 "string longer than %d bytes", INT_MAX);
1686 goto error;
1687 }
1688
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001689 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001691 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1692 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001693
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001694 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001695 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1696 PyErr_SetString(PySSLErrorObject,
1697 "The write operation timed out");
1698 goto error;
1699 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1700 PyErr_SetString(PySSLErrorObject,
1701 "Underlying socket has been closed.");
1702 goto error;
1703 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1704 PyErr_SetString(PySSLErrorObject,
1705 "Underlying socket too large for select().");
1706 goto error;
1707 }
1708 do {
1709 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001710 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001711 err = SSL_get_error(self->ssl, len);
1712 PySSL_END_ALLOW_THREADS
1713 if (PyErr_CheckSignals()) {
1714 goto error;
1715 }
1716 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001717 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001719 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 } else {
1721 sockstate = SOCKET_OPERATION_OK;
1722 }
1723 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1724 PyErr_SetString(PySSLErrorObject,
1725 "The write operation timed out");
1726 goto error;
1727 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1728 PyErr_SetString(PySSLErrorObject,
1729 "Underlying socket has been closed.");
1730 goto error;
1731 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1732 break;
1733 }
1734 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001735
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001736 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001737 PyBuffer_Release(&buf);
1738 if (len > 0)
1739 return PyInt_FromLong(len);
1740 else
1741 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001742
1743error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001744 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001745 PyBuffer_Release(&buf);
1746 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747}
1748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750"write(s) -> len\n\
1751\n\
1752Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001755static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001756{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001757 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001758
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001759 PySSL_BEGIN_ALLOW_THREADS
1760 count = SSL_pending(self->ssl);
1761 PySSL_END_ALLOW_THREADS
1762 if (count < 0)
1763 return PySSL_SetError(self, count, __FILE__, __LINE__);
1764 else
1765 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001766}
1767
1768PyDoc_STRVAR(PySSL_SSLpending_doc,
1769"pending() -> count\n\
1770\n\
1771Returns the number of already decrypted bytes available for read,\n\
1772pending on the connection.\n");
1773
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001774static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001775{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001776 PyObject *dest = NULL;
1777 Py_buffer buf;
1778 char *mem;
1779 int len, count;
1780 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001781 int sockstate;
1782 int err;
1783 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001784 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001785
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001786 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001788 buf.obj = NULL;
1789 buf.buf = NULL;
1790 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1791 goto error;
1792
1793 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001794 if (len < 0) {
1795 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1796 goto error;
1797 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001798 dest = PyBytes_FromStringAndSize(NULL, len);
1799 if (dest == NULL)
1800 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001801 if (len == 0) {
1802 Py_XDECREF(sock);
1803 return dest;
1804 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001805 mem = PyBytes_AS_STRING(dest);
1806 }
1807 else {
1808 buf_passed = 1;
1809 mem = buf.buf;
1810 if (len <= 0 || len > buf.len) {
1811 len = (int) buf.len;
1812 if (buf.len != len) {
1813 PyErr_SetString(PyExc_OverflowError,
1814 "maximum length can't fit in a C 'int'");
1815 goto error;
1816 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001817 if (len == 0) {
1818 count = 0;
1819 goto done;
1820 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001821 }
1822 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001823
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001824 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001825 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001826 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1827 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001828
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001829 do {
1830 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001831 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001832 err = SSL_get_error(self->ssl, count);
1833 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001834 if (PyErr_CheckSignals())
1835 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001836 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001837 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001838 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001840 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1841 (SSL_get_shutdown(self->ssl) ==
1842 SSL_RECEIVED_SHUTDOWN))
1843 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844 count = 0;
1845 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001846 } else {
1847 sockstate = SOCKET_OPERATION_OK;
1848 }
1849 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1850 PyErr_SetString(PySSLErrorObject,
1851 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001852 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001853 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1854 break;
1855 }
1856 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1857 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858 PySSL_SetError(self, count, __FILE__, __LINE__);
1859 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001860 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001861
1862done:
1863 Py_DECREF(sock);
1864 if (!buf_passed) {
1865 _PyBytes_Resize(&dest, count);
1866 return dest;
1867 }
1868 else {
1869 PyBuffer_Release(&buf);
1870 return PyLong_FromLong(count);
1871 }
1872
1873error:
1874 Py_DECREF(sock);
1875 if (!buf_passed)
1876 Py_XDECREF(dest);
1877 else
1878 PyBuffer_Release(&buf);
1879 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001880}
1881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001882PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001883"read([len]) -> string\n\
1884\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001885Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001886
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001887static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001888{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001889 int err, ssl_err, sockstate, nonblocking;
1890 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001891 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001893 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001894 if (sock->sock_fd < 0) {
1895 _setSSLError("Underlying socket connection gone",
1896 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001897 return NULL;
1898 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001899 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001900
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001901 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001902 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001903 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1904 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001905
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001906 while (1) {
1907 PySSL_BEGIN_ALLOW_THREADS
1908 /* Disable read-ahead so that unwrap can work correctly.
1909 * Otherwise OpenSSL might read in too much data,
1910 * eating clear text data that happens to be
1911 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001912 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001913 * function is used and the shutdown_seen_zero != 0
1914 * condition is met.
1915 */
1916 if (self->shutdown_seen_zero)
1917 SSL_set_read_ahead(self->ssl, 0);
1918 err = SSL_shutdown(self->ssl);
1919 PySSL_END_ALLOW_THREADS
1920 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1921 if (err > 0)
1922 break;
1923 if (err == 0) {
1924 /* Don't loop endlessly; instead preserve legacy
1925 behaviour of trying SSL_shutdown() only twice.
1926 This looks necessary for OpenSSL < 0.9.8m */
1927 if (++zeros > 1)
1928 break;
1929 /* Shutdown was sent, now try receiving */
1930 self->shutdown_seen_zero = 1;
1931 continue;
1932 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001933
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001934 /* Possibly retry shutdown until timeout or failure */
1935 ssl_err = SSL_get_error(self->ssl, err);
1936 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001937 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001938 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001939 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001940 else
1941 break;
1942 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1943 if (ssl_err == SSL_ERROR_WANT_READ)
1944 PyErr_SetString(PySSLErrorObject,
1945 "The read operation timed out");
1946 else
1947 PyErr_SetString(PySSLErrorObject,
1948 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001949 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001950 }
1951 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1952 PyErr_SetString(PySSLErrorObject,
1953 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001954 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001955 }
1956 else if (sockstate != SOCKET_OPERATION_OK)
1957 /* Retain the SSL error code */
1958 break;
1959 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001960
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001961 if (err < 0) {
1962 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001963 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001964 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001965 else
1966 /* It's already INCREF'ed */
1967 return (PyObject *) sock;
1968
1969error:
1970 Py_DECREF(sock);
1971 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001972}
1973
1974PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1975"shutdown(s) -> socket\n\
1976\n\
1977Does the SSL shutdown handshake with the remote end, and returns\n\
1978the underlying socket object.");
1979
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001980#if HAVE_OPENSSL_FINISHED
1981static PyObject *
1982PySSL_tls_unique_cb(PySSLSocket *self)
1983{
1984 PyObject *retval = NULL;
1985 char buf[PySSL_CB_MAXLEN];
1986 size_t len;
1987
1988 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1989 /* if session is resumed XOR we are the client */
1990 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1991 }
1992 else {
1993 /* if a new session XOR we are the server */
1994 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1995 }
1996
1997 /* It cannot be negative in current OpenSSL version as of July 2011 */
1998 if (len == 0)
1999 Py_RETURN_NONE;
2000
2001 retval = PyBytes_FromStringAndSize(buf, len);
2002
2003 return retval;
2004}
2005
2006PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2007"tls_unique_cb() -> bytes\n\
2008\n\
2009Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2010\n\
2011If the TLS handshake is not yet complete, None is returned");
2012
2013#endif /* HAVE_OPENSSL_FINISHED */
2014
2015static PyGetSetDef ssl_getsetlist[] = {
2016 {"context", (getter) PySSL_get_context,
2017 (setter) PySSL_set_context, PySSL_set_context_doc},
2018 {NULL}, /* sentinel */
2019};
2020
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002021static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002022 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2023 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2024 PySSL_SSLwrite_doc},
2025 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2026 PySSL_SSLread_doc},
2027 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2028 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002029 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2030 PySSL_peercert_doc},
2031 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002032 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002033#ifdef OPENSSL_NPN_NEGOTIATED
2034 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2035#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002036#ifdef HAVE_ALPN
2037 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2038#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002039 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002040 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2041 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002042#if HAVE_OPENSSL_FINISHED
2043 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2044 PySSL_tls_unique_cb_doc},
2045#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002046 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002047};
2048
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002049static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002050 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002051 "_ssl._SSLSocket", /*tp_name*/
2052 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002053 0, /*tp_itemsize*/
2054 /* methods */
2055 (destructor)PySSL_dealloc, /*tp_dealloc*/
2056 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002057 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002058 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002059 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002060 0, /*tp_repr*/
2061 0, /*tp_as_number*/
2062 0, /*tp_as_sequence*/
2063 0, /*tp_as_mapping*/
2064 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002065 0, /*tp_call*/
2066 0, /*tp_str*/
2067 0, /*tp_getattro*/
2068 0, /*tp_setattro*/
2069 0, /*tp_as_buffer*/
2070 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2071 0, /*tp_doc*/
2072 0, /*tp_traverse*/
2073 0, /*tp_clear*/
2074 0, /*tp_richcompare*/
2075 0, /*tp_weaklistoffset*/
2076 0, /*tp_iter*/
2077 0, /*tp_iternext*/
2078 PySSLMethods, /*tp_methods*/
2079 0, /*tp_members*/
2080 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002081};
2082
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002083
2084/*
2085 * _SSLContext objects
2086 */
2087
2088static PyObject *
2089context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2090{
2091 char *kwlist[] = {"protocol", NULL};
2092 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002093 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002094 long options;
2095 SSL_CTX *ctx = NULL;
2096
2097 if (!PyArg_ParseTupleAndKeywords(
2098 args, kwds, "i:_SSLContext", kwlist,
2099 &proto_version))
2100 return NULL;
2101
2102 PySSL_BEGIN_ALLOW_THREADS
2103 if (proto_version == PY_SSL_VERSION_TLS1)
2104 ctx = SSL_CTX_new(TLSv1_method());
2105#if HAVE_TLSv1_2
2106 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2107 ctx = SSL_CTX_new(TLSv1_1_method());
2108 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2109 ctx = SSL_CTX_new(TLSv1_2_method());
2110#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002111#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002112 else if (proto_version == PY_SSL_VERSION_SSL3)
2113 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002114#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002115#ifndef OPENSSL_NO_SSL2
2116 else if (proto_version == PY_SSL_VERSION_SSL2)
2117 ctx = SSL_CTX_new(SSLv2_method());
2118#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002119 else if (proto_version == PY_SSL_VERSION_TLS)
2120 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002121 else
2122 proto_version = -1;
2123 PySSL_END_ALLOW_THREADS
2124
2125 if (proto_version == -1) {
2126 PyErr_SetString(PyExc_ValueError,
2127 "invalid protocol version");
2128 return NULL;
2129 }
2130 if (ctx == NULL) {
2131 PyErr_SetString(PySSLErrorObject,
2132 "failed to allocate SSL context");
2133 return NULL;
2134 }
2135
2136 assert(type != NULL && type->tp_alloc != NULL);
2137 self = (PySSLContext *) type->tp_alloc(type, 0);
2138 if (self == NULL) {
2139 SSL_CTX_free(ctx);
2140 return NULL;
2141 }
2142 self->ctx = ctx;
2143#ifdef OPENSSL_NPN_NEGOTIATED
2144 self->npn_protocols = NULL;
2145#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002146#ifdef HAVE_ALPN
2147 self->alpn_protocols = NULL;
2148#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002149#ifndef OPENSSL_NO_TLSEXT
2150 self->set_hostname = NULL;
2151#endif
2152 /* Don't check host name by default */
2153 self->check_hostname = 0;
2154 /* Defaults */
2155 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2156 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2157 if (proto_version != PY_SSL_VERSION_SSL2)
2158 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002159 if (proto_version != PY_SSL_VERSION_SSL3)
2160 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002161 SSL_CTX_set_options(self->ctx, options);
2162
Donald Stufftf1a696e2017-03-02 12:37:07 -05002163#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002164 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2165 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002166 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2167 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002168#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002169 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2170#else
2171 {
2172 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2173 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2174 EC_KEY_free(key);
2175 }
2176#endif
2177#endif
2178
2179#define SID_CTX "Python"
2180 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2181 sizeof(SID_CTX));
2182#undef SID_CTX
2183
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002184#ifdef X509_V_FLAG_TRUSTED_FIRST
2185 {
2186 /* Improve trust chain building when cross-signed intermediate
2187 certificates are present. See https://bugs.python.org/issue23476. */
2188 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2189 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2190 }
2191#endif
2192
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002193 return (PyObject *)self;
2194}
2195
2196static int
2197context_traverse(PySSLContext *self, visitproc visit, void *arg)
2198{
2199#ifndef OPENSSL_NO_TLSEXT
2200 Py_VISIT(self->set_hostname);
2201#endif
2202 return 0;
2203}
2204
2205static int
2206context_clear(PySSLContext *self)
2207{
2208#ifndef OPENSSL_NO_TLSEXT
2209 Py_CLEAR(self->set_hostname);
2210#endif
2211 return 0;
2212}
2213
2214static void
2215context_dealloc(PySSLContext *self)
2216{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002217 /* bpo-31095: UnTrack is needed before calling any callbacks */
2218 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002219 context_clear(self);
2220 SSL_CTX_free(self->ctx);
2221#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002222 PyMem_FREE(self->npn_protocols);
2223#endif
2224#ifdef HAVE_ALPN
2225 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002226#endif
2227 Py_TYPE(self)->tp_free(self);
2228}
2229
2230static PyObject *
2231set_ciphers(PySSLContext *self, PyObject *args)
2232{
2233 int ret;
2234 const char *cipherlist;
2235
2236 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2237 return NULL;
2238 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2239 if (ret == 0) {
2240 /* Clearing the error queue is necessary on some OpenSSL versions,
2241 otherwise the error will be reported again when another SSL call
2242 is done. */
2243 ERR_clear_error();
2244 PyErr_SetString(PySSLErrorObject,
2245 "No cipher can be selected.");
2246 return NULL;
2247 }
2248 Py_RETURN_NONE;
2249}
2250
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002251#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002252static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002253do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2254 const unsigned char *server_protocols, unsigned int server_protocols_len,
2255 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002256{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002257 int ret;
2258 if (client_protocols == NULL) {
2259 client_protocols = (unsigned char *)"";
2260 client_protocols_len = 0;
2261 }
2262 if (server_protocols == NULL) {
2263 server_protocols = (unsigned char *)"";
2264 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002265 }
2266
Benjamin Petersonaa707582015-01-23 17:30:26 -05002267 ret = SSL_select_next_proto(out, outlen,
2268 server_protocols, server_protocols_len,
2269 client_protocols, client_protocols_len);
2270 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2271 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002272
2273 return SSL_TLSEXT_ERR_OK;
2274}
2275
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002276/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2277static int
2278_advertiseNPN_cb(SSL *s,
2279 const unsigned char **data, unsigned int *len,
2280 void *args)
2281{
2282 PySSLContext *ssl_ctx = (PySSLContext *) args;
2283
2284 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002285 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002286 *len = 0;
2287 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002288 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002289 *len = ssl_ctx->npn_protocols_len;
2290 }
2291
2292 return SSL_TLSEXT_ERR_OK;
2293}
2294/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2295static int
2296_selectNPN_cb(SSL *s,
2297 unsigned char **out, unsigned char *outlen,
2298 const unsigned char *server, unsigned int server_len,
2299 void *args)
2300{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002301 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002302 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002303 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002304}
2305#endif
2306
2307static PyObject *
2308_set_npn_protocols(PySSLContext *self, PyObject *args)
2309{
2310#ifdef OPENSSL_NPN_NEGOTIATED
2311 Py_buffer protos;
2312
2313 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2314 return NULL;
2315
2316 if (self->npn_protocols != NULL) {
2317 PyMem_Free(self->npn_protocols);
2318 }
2319
2320 self->npn_protocols = PyMem_Malloc(protos.len);
2321 if (self->npn_protocols == NULL) {
2322 PyBuffer_Release(&protos);
2323 return PyErr_NoMemory();
2324 }
2325 memcpy(self->npn_protocols, protos.buf, protos.len);
2326 self->npn_protocols_len = (int) protos.len;
2327
2328 /* set both server and client callbacks, because the context can
2329 * be used to create both types of sockets */
2330 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2331 _advertiseNPN_cb,
2332 self);
2333 SSL_CTX_set_next_proto_select_cb(self->ctx,
2334 _selectNPN_cb,
2335 self);
2336
2337 PyBuffer_Release(&protos);
2338 Py_RETURN_NONE;
2339#else
2340 PyErr_SetString(PyExc_NotImplementedError,
2341 "The NPN extension requires OpenSSL 1.0.1 or later.");
2342 return NULL;
2343#endif
2344}
2345
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002346#ifdef HAVE_ALPN
2347static int
2348_selectALPN_cb(SSL *s,
2349 const unsigned char **out, unsigned char *outlen,
2350 const unsigned char *client_protocols, unsigned int client_protocols_len,
2351 void *args)
2352{
2353 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002354 return do_protocol_selection(1, (unsigned char **)out, outlen,
2355 ctx->alpn_protocols, ctx->alpn_protocols_len,
2356 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002357}
2358#endif
2359
2360static PyObject *
2361_set_alpn_protocols(PySSLContext *self, PyObject *args)
2362{
2363#ifdef HAVE_ALPN
2364 Py_buffer protos;
2365
2366 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2367 return NULL;
2368
2369 PyMem_FREE(self->alpn_protocols);
2370 self->alpn_protocols = PyMem_Malloc(protos.len);
2371 if (!self->alpn_protocols)
2372 return PyErr_NoMemory();
2373 memcpy(self->alpn_protocols, protos.buf, protos.len);
2374 self->alpn_protocols_len = protos.len;
2375 PyBuffer_Release(&protos);
2376
2377 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2378 return PyErr_NoMemory();
2379 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2380
2381 PyBuffer_Release(&protos);
2382 Py_RETURN_NONE;
2383#else
2384 PyErr_SetString(PyExc_NotImplementedError,
2385 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2386 return NULL;
2387#endif
2388}
2389
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002390static PyObject *
2391get_verify_mode(PySSLContext *self, void *c)
2392{
2393 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2394 case SSL_VERIFY_NONE:
2395 return PyLong_FromLong(PY_SSL_CERT_NONE);
2396 case SSL_VERIFY_PEER:
2397 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2398 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2399 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2400 }
2401 PyErr_SetString(PySSLErrorObject,
2402 "invalid return value from SSL_CTX_get_verify_mode");
2403 return NULL;
2404}
2405
2406static int
2407set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2408{
2409 int n, mode;
2410 if (!PyArg_Parse(arg, "i", &n))
2411 return -1;
2412 if (n == PY_SSL_CERT_NONE)
2413 mode = SSL_VERIFY_NONE;
2414 else if (n == PY_SSL_CERT_OPTIONAL)
2415 mode = SSL_VERIFY_PEER;
2416 else if (n == PY_SSL_CERT_REQUIRED)
2417 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2418 else {
2419 PyErr_SetString(PyExc_ValueError,
2420 "invalid value for verify_mode");
2421 return -1;
2422 }
2423 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2424 PyErr_SetString(PyExc_ValueError,
2425 "Cannot set verify_mode to CERT_NONE when "
2426 "check_hostname is enabled.");
2427 return -1;
2428 }
2429 SSL_CTX_set_verify(self->ctx, mode, NULL);
2430 return 0;
2431}
2432
2433#ifdef HAVE_OPENSSL_VERIFY_PARAM
2434static PyObject *
2435get_verify_flags(PySSLContext *self, void *c)
2436{
2437 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002438 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002439 unsigned long flags;
2440
2441 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002442 param = X509_STORE_get0_param(store);
2443 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002444 return PyLong_FromUnsignedLong(flags);
2445}
2446
2447static int
2448set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2449{
2450 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002451 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002452 unsigned long new_flags, flags, set, clear;
2453
2454 if (!PyArg_Parse(arg, "k", &new_flags))
2455 return -1;
2456 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002457 param = X509_STORE_get0_param(store);
2458 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002459 clear = flags & ~new_flags;
2460 set = ~flags & new_flags;
2461 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002462 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002463 _setSSLError(NULL, 0, __FILE__, __LINE__);
2464 return -1;
2465 }
2466 }
2467 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002468 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002469 _setSSLError(NULL, 0, __FILE__, __LINE__);
2470 return -1;
2471 }
2472 }
2473 return 0;
2474}
2475#endif
2476
2477static PyObject *
2478get_options(PySSLContext *self, void *c)
2479{
2480 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2481}
2482
2483static int
2484set_options(PySSLContext *self, PyObject *arg, void *c)
2485{
2486 long new_opts, opts, set, clear;
2487 if (!PyArg_Parse(arg, "l", &new_opts))
2488 return -1;
2489 opts = SSL_CTX_get_options(self->ctx);
2490 clear = opts & ~new_opts;
2491 set = ~opts & new_opts;
2492 if (clear) {
2493#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2494 SSL_CTX_clear_options(self->ctx, clear);
2495#else
2496 PyErr_SetString(PyExc_ValueError,
2497 "can't clear options before OpenSSL 0.9.8m");
2498 return -1;
2499#endif
2500 }
2501 if (set)
2502 SSL_CTX_set_options(self->ctx, set);
2503 return 0;
2504}
2505
2506static PyObject *
2507get_check_hostname(PySSLContext *self, void *c)
2508{
2509 return PyBool_FromLong(self->check_hostname);
2510}
2511
2512static int
2513set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2514{
2515 PyObject *py_check_hostname;
2516 int check_hostname;
2517 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2518 return -1;
2519
2520 check_hostname = PyObject_IsTrue(py_check_hostname);
2521 if (check_hostname < 0)
2522 return -1;
2523 if (check_hostname &&
2524 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2525 PyErr_SetString(PyExc_ValueError,
2526 "check_hostname needs a SSL context with either "
2527 "CERT_OPTIONAL or CERT_REQUIRED");
2528 return -1;
2529 }
2530 self->check_hostname = check_hostname;
2531 return 0;
2532}
2533
2534
2535typedef struct {
2536 PyThreadState *thread_state;
2537 PyObject *callable;
2538 char *password;
2539 int size;
2540 int error;
2541} _PySSLPasswordInfo;
2542
2543static int
2544_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2545 const char *bad_type_error)
2546{
2547 /* Set the password and size fields of a _PySSLPasswordInfo struct
2548 from a unicode, bytes, or byte array object.
2549 The password field will be dynamically allocated and must be freed
2550 by the caller */
2551 PyObject *password_bytes = NULL;
2552 const char *data = NULL;
2553 Py_ssize_t size;
2554
2555 if (PyUnicode_Check(password)) {
2556 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2557 if (!password_bytes) {
2558 goto error;
2559 }
2560 data = PyBytes_AS_STRING(password_bytes);
2561 size = PyBytes_GET_SIZE(password_bytes);
2562 } else if (PyBytes_Check(password)) {
2563 data = PyBytes_AS_STRING(password);
2564 size = PyBytes_GET_SIZE(password);
2565 } else if (PyByteArray_Check(password)) {
2566 data = PyByteArray_AS_STRING(password);
2567 size = PyByteArray_GET_SIZE(password);
2568 } else {
2569 PyErr_SetString(PyExc_TypeError, bad_type_error);
2570 goto error;
2571 }
2572
2573 if (size > (Py_ssize_t)INT_MAX) {
2574 PyErr_Format(PyExc_ValueError,
2575 "password cannot be longer than %d bytes", INT_MAX);
2576 goto error;
2577 }
2578
2579 PyMem_Free(pw_info->password);
2580 pw_info->password = PyMem_Malloc(size);
2581 if (!pw_info->password) {
2582 PyErr_SetString(PyExc_MemoryError,
2583 "unable to allocate password buffer");
2584 goto error;
2585 }
2586 memcpy(pw_info->password, data, size);
2587 pw_info->size = (int)size;
2588
2589 Py_XDECREF(password_bytes);
2590 return 1;
2591
2592error:
2593 Py_XDECREF(password_bytes);
2594 return 0;
2595}
2596
2597static int
2598_password_callback(char *buf, int size, int rwflag, void *userdata)
2599{
2600 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2601 PyObject *fn_ret = NULL;
2602
2603 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2604
2605 if (pw_info->callable) {
2606 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2607 if (!fn_ret) {
2608 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2609 core python API, so we could use it to add a frame here */
2610 goto error;
2611 }
2612
2613 if (!_pwinfo_set(pw_info, fn_ret,
2614 "password callback must return a string")) {
2615 goto error;
2616 }
2617 Py_CLEAR(fn_ret);
2618 }
2619
2620 if (pw_info->size > size) {
2621 PyErr_Format(PyExc_ValueError,
2622 "password cannot be longer than %d bytes", size);
2623 goto error;
2624 }
2625
2626 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2627 memcpy(buf, pw_info->password, pw_info->size);
2628 return pw_info->size;
2629
2630error:
2631 Py_XDECREF(fn_ret);
2632 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2633 pw_info->error = 1;
2634 return -1;
2635}
2636
2637static PyObject *
2638load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2639{
2640 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002641 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2642 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002643 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2644 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002645 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2646 int r;
2647
2648 errno = 0;
2649 ERR_clear_error();
2650 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002651 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002652 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002653 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002654 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002655
2656 if (keyfile && keyfile != Py_None) {
2657 if (PyString_Check(keyfile)) {
2658 Py_INCREF(keyfile);
2659 keyfile_bytes = keyfile;
2660 } else {
2661 PyObject *u = PyUnicode_FromObject(keyfile);
2662 if (!u)
2663 goto error;
2664 keyfile_bytes = PyUnicode_AsEncodedString(
2665 u, Py_FileSystemDefaultEncoding, NULL);
2666 Py_DECREF(u);
2667 if (!keyfile_bytes)
2668 goto error;
2669 }
2670 }
2671
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002672 if (password && password != Py_None) {
2673 if (PyCallable_Check(password)) {
2674 pw_info.callable = password;
2675 } else if (!_pwinfo_set(&pw_info, password,
2676 "password should be a string or callable")) {
2677 goto error;
2678 }
2679 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2680 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2681 }
2682 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2683 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2684 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2685 if (r != 1) {
2686 if (pw_info.error) {
2687 ERR_clear_error();
2688 /* the password callback has already set the error information */
2689 }
2690 else if (errno != 0) {
2691 ERR_clear_error();
2692 PyErr_SetFromErrno(PyExc_IOError);
2693 }
2694 else {
2695 _setSSLError(NULL, 0, __FILE__, __LINE__);
2696 }
2697 goto error;
2698 }
2699 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2700 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002701 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002702 SSL_FILETYPE_PEM);
2703 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2704 if (r != 1) {
2705 if (pw_info.error) {
2706 ERR_clear_error();
2707 /* the password callback has already set the error information */
2708 }
2709 else if (errno != 0) {
2710 ERR_clear_error();
2711 PyErr_SetFromErrno(PyExc_IOError);
2712 }
2713 else {
2714 _setSSLError(NULL, 0, __FILE__, __LINE__);
2715 }
2716 goto error;
2717 }
2718 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2719 r = SSL_CTX_check_private_key(self->ctx);
2720 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2721 if (r != 1) {
2722 _setSSLError(NULL, 0, __FILE__, __LINE__);
2723 goto error;
2724 }
2725 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2726 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002727 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002728 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002729 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002730 Py_RETURN_NONE;
2731
2732error:
2733 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2734 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002735 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002736 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002737 PyMem_Free(certfile_bytes);
2738 return NULL;
2739}
2740
2741/* internal helper function, returns -1 on error
2742 */
2743static int
2744_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2745 int filetype)
2746{
2747 BIO *biobuf = NULL;
2748 X509_STORE *store;
2749 int retval = 0, err, loaded = 0;
2750
2751 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2752
2753 if (len <= 0) {
2754 PyErr_SetString(PyExc_ValueError,
2755 "Empty certificate data");
2756 return -1;
2757 } else if (len > INT_MAX) {
2758 PyErr_SetString(PyExc_OverflowError,
2759 "Certificate data is too long.");
2760 return -1;
2761 }
2762
2763 biobuf = BIO_new_mem_buf(data, (int)len);
2764 if (biobuf == NULL) {
2765 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2766 return -1;
2767 }
2768
2769 store = SSL_CTX_get_cert_store(self->ctx);
2770 assert(store != NULL);
2771
2772 while (1) {
2773 X509 *cert = NULL;
2774 int r;
2775
2776 if (filetype == SSL_FILETYPE_ASN1) {
2777 cert = d2i_X509_bio(biobuf, NULL);
2778 } else {
2779 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002780 SSL_CTX_get_default_passwd_cb(self->ctx),
2781 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2782 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002783 }
2784 if (cert == NULL) {
2785 break;
2786 }
2787 r = X509_STORE_add_cert(store, cert);
2788 X509_free(cert);
2789 if (!r) {
2790 err = ERR_peek_last_error();
2791 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2792 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2793 /* cert already in hash table, not an error */
2794 ERR_clear_error();
2795 } else {
2796 break;
2797 }
2798 }
2799 loaded++;
2800 }
2801
2802 err = ERR_peek_last_error();
2803 if ((filetype == SSL_FILETYPE_ASN1) &&
2804 (loaded > 0) &&
2805 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2806 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2807 /* EOF ASN1 file, not an error */
2808 ERR_clear_error();
2809 retval = 0;
2810 } else if ((filetype == SSL_FILETYPE_PEM) &&
2811 (loaded > 0) &&
2812 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2813 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2814 /* EOF PEM file, not an error */
2815 ERR_clear_error();
2816 retval = 0;
2817 } else {
2818 _setSSLError(NULL, 0, __FILE__, __LINE__);
2819 retval = -1;
2820 }
2821
2822 BIO_free(biobuf);
2823 return retval;
2824}
2825
2826
2827static PyObject *
2828load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2829{
2830 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2831 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2832 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2833 const char *cafile_buf = NULL, *capath_buf = NULL;
2834 int r = 0, ok = 1;
2835
2836 errno = 0;
2837 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2838 "|OOO:load_verify_locations", kwlist,
2839 &cafile, &capath, &cadata))
2840 return NULL;
2841
2842 if (cafile == Py_None)
2843 cafile = NULL;
2844 if (capath == Py_None)
2845 capath = NULL;
2846 if (cadata == Py_None)
2847 cadata = NULL;
2848
2849 if (cafile == NULL && capath == NULL && cadata == NULL) {
2850 PyErr_SetString(PyExc_TypeError,
2851 "cafile, capath and cadata cannot be all omitted");
2852 goto error;
2853 }
2854
2855 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002856 if (PyString_Check(cafile)) {
2857 Py_INCREF(cafile);
2858 cafile_bytes = cafile;
2859 } else {
2860 PyObject *u = PyUnicode_FromObject(cafile);
2861 if (!u)
2862 goto error;
2863 cafile_bytes = PyUnicode_AsEncodedString(
2864 u, Py_FileSystemDefaultEncoding, NULL);
2865 Py_DECREF(u);
2866 if (!cafile_bytes)
2867 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002868 }
2869 }
2870 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002871 if (PyString_Check(capath)) {
2872 Py_INCREF(capath);
2873 capath_bytes = capath;
2874 } else {
2875 PyObject *u = PyUnicode_FromObject(capath);
2876 if (!u)
2877 goto error;
2878 capath_bytes = PyUnicode_AsEncodedString(
2879 u, Py_FileSystemDefaultEncoding, NULL);
2880 Py_DECREF(u);
2881 if (!capath_bytes)
2882 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002883 }
2884 }
2885
2886 /* validata cadata type and load cadata */
2887 if (cadata) {
2888 Py_buffer buf;
2889 PyObject *cadata_ascii = NULL;
2890
2891 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2892 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2893 PyBuffer_Release(&buf);
2894 PyErr_SetString(PyExc_TypeError,
2895 "cadata should be a contiguous buffer with "
2896 "a single dimension");
2897 goto error;
2898 }
2899 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2900 PyBuffer_Release(&buf);
2901 if (r == -1) {
2902 goto error;
2903 }
2904 } else {
2905 PyErr_Clear();
2906 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2907 if (cadata_ascii == NULL) {
2908 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002909 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002910 "bytes-like object");
2911 goto error;
2912 }
2913 r = _add_ca_certs(self,
2914 PyBytes_AS_STRING(cadata_ascii),
2915 PyBytes_GET_SIZE(cadata_ascii),
2916 SSL_FILETYPE_PEM);
2917 Py_DECREF(cadata_ascii);
2918 if (r == -1) {
2919 goto error;
2920 }
2921 }
2922 }
2923
2924 /* load cafile or capath */
2925 if (cafile_bytes || capath_bytes) {
2926 if (cafile)
2927 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2928 if (capath)
2929 capath_buf = PyBytes_AS_STRING(capath_bytes);
2930 PySSL_BEGIN_ALLOW_THREADS
2931 r = SSL_CTX_load_verify_locations(
2932 self->ctx,
2933 cafile_buf,
2934 capath_buf);
2935 PySSL_END_ALLOW_THREADS
2936 if (r != 1) {
2937 ok = 0;
2938 if (errno != 0) {
2939 ERR_clear_error();
2940 PyErr_SetFromErrno(PyExc_IOError);
2941 }
2942 else {
2943 _setSSLError(NULL, 0, __FILE__, __LINE__);
2944 }
2945 goto error;
2946 }
2947 }
2948 goto end;
2949
2950 error:
2951 ok = 0;
2952 end:
2953 Py_XDECREF(cafile_bytes);
2954 Py_XDECREF(capath_bytes);
2955 if (ok) {
2956 Py_RETURN_NONE;
2957 } else {
2958 return NULL;
2959 }
2960}
2961
2962static PyObject *
2963load_dh_params(PySSLContext *self, PyObject *filepath)
2964{
2965 BIO *bio;
2966 DH *dh;
2967 char *path = PyBytes_AsString(filepath);
2968 if (!path) {
2969 return NULL;
2970 }
2971
2972 bio = BIO_new_file(path, "r");
2973 if (bio == NULL) {
2974 ERR_clear_error();
2975 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2976 return NULL;
2977 }
2978 errno = 0;
2979 PySSL_BEGIN_ALLOW_THREADS
2980 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2981 BIO_free(bio);
2982 PySSL_END_ALLOW_THREADS
2983 if (dh == NULL) {
2984 if (errno != 0) {
2985 ERR_clear_error();
2986 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2987 }
2988 else {
2989 _setSSLError(NULL, 0, __FILE__, __LINE__);
2990 }
2991 return NULL;
2992 }
2993 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2994 _setSSLError(NULL, 0, __FILE__, __LINE__);
2995 DH_free(dh);
2996 Py_RETURN_NONE;
2997}
2998
2999static PyObject *
3000context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3001{
3002 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3003 PySocketSockObject *sock;
3004 int server_side = 0;
3005 char *hostname = NULL;
3006 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3007
3008 /* server_hostname is either None (or absent), or to be encoded
3009 using the idna encoding. */
3010 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3011 PySocketModule.Sock_Type,
3012 &sock, &server_side,
3013 Py_TYPE(Py_None), &hostname_obj,
3014 &ssl_sock)) {
3015 PyErr_Clear();
3016 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3017 PySocketModule.Sock_Type,
3018 &sock, &server_side,
3019 "idna", &hostname, &ssl_sock))
3020 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003021 }
3022
3023 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3024 hostname, ssl_sock);
3025 if (hostname != NULL)
3026 PyMem_Free(hostname);
3027 return res;
3028}
3029
3030static PyObject *
3031session_stats(PySSLContext *self, PyObject *unused)
3032{
3033 int r;
3034 PyObject *value, *stats = PyDict_New();
3035 if (!stats)
3036 return NULL;
3037
3038#define ADD_STATS(SSL_NAME, KEY_NAME) \
3039 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3040 if (value == NULL) \
3041 goto error; \
3042 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3043 Py_DECREF(value); \
3044 if (r < 0) \
3045 goto error;
3046
3047 ADD_STATS(number, "number");
3048 ADD_STATS(connect, "connect");
3049 ADD_STATS(connect_good, "connect_good");
3050 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3051 ADD_STATS(accept, "accept");
3052 ADD_STATS(accept_good, "accept_good");
3053 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3054 ADD_STATS(accept, "accept");
3055 ADD_STATS(hits, "hits");
3056 ADD_STATS(misses, "misses");
3057 ADD_STATS(timeouts, "timeouts");
3058 ADD_STATS(cache_full, "cache_full");
3059
3060#undef ADD_STATS
3061
3062 return stats;
3063
3064error:
3065 Py_DECREF(stats);
3066 return NULL;
3067}
3068
3069static PyObject *
3070set_default_verify_paths(PySSLContext *self, PyObject *unused)
3071{
3072 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3073 _setSSLError(NULL, 0, __FILE__, __LINE__);
3074 return NULL;
3075 }
3076 Py_RETURN_NONE;
3077}
3078
3079#ifndef OPENSSL_NO_ECDH
3080static PyObject *
3081set_ecdh_curve(PySSLContext *self, PyObject *name)
3082{
3083 char *name_bytes;
3084 int nid;
3085 EC_KEY *key;
3086
3087 name_bytes = PyBytes_AsString(name);
3088 if (!name_bytes) {
3089 return NULL;
3090 }
3091 nid = OBJ_sn2nid(name_bytes);
3092 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003093 PyObject *r = PyObject_Repr(name);
3094 if (!r)
3095 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003096 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003097 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3098 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003099 return NULL;
3100 }
3101 key = EC_KEY_new_by_curve_name(nid);
3102 if (key == NULL) {
3103 _setSSLError(NULL, 0, __FILE__, __LINE__);
3104 return NULL;
3105 }
3106 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3107 EC_KEY_free(key);
3108 Py_RETURN_NONE;
3109}
3110#endif
3111
3112#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3113static int
3114_servername_callback(SSL *s, int *al, void *args)
3115{
3116 int ret;
3117 PySSLContext *ssl_ctx = (PySSLContext *) args;
3118 PySSLSocket *ssl;
3119 PyObject *servername_o;
3120 PyObject *servername_idna;
3121 PyObject *result;
3122 /* The high-level ssl.SSLSocket object */
3123 PyObject *ssl_socket;
3124 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3125#ifdef WITH_THREAD
3126 PyGILState_STATE gstate = PyGILState_Ensure();
3127#endif
3128
3129 if (ssl_ctx->set_hostname == NULL) {
3130 /* remove race condition in this the call back while if removing the
3131 * callback is in progress */
3132#ifdef WITH_THREAD
3133 PyGILState_Release(gstate);
3134#endif
3135 return SSL_TLSEXT_ERR_OK;
3136 }
3137
3138 ssl = SSL_get_app_data(s);
3139 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003140 if (ssl->ssl_sock == NULL) {
3141 ssl_socket = Py_None;
3142 } else {
3143 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3144 Py_INCREF(ssl_socket);
3145 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003146 if (ssl_socket == Py_None) {
3147 goto error;
3148 }
3149
3150 if (servername == NULL) {
3151 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3152 Py_None, ssl_ctx, NULL);
3153 }
3154 else {
3155 servername_o = PyBytes_FromString(servername);
3156 if (servername_o == NULL) {
3157 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3158 goto error;
3159 }
3160 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3161 if (servername_idna == NULL) {
3162 PyErr_WriteUnraisable(servername_o);
3163 Py_DECREF(servername_o);
3164 goto error;
3165 }
3166 Py_DECREF(servername_o);
3167 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3168 servername_idna, ssl_ctx, NULL);
3169 Py_DECREF(servername_idna);
3170 }
3171 Py_DECREF(ssl_socket);
3172
3173 if (result == NULL) {
3174 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3175 *al = SSL_AD_HANDSHAKE_FAILURE;
3176 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3177 }
3178 else {
3179 if (result != Py_None) {
3180 *al = (int) PyLong_AsLong(result);
3181 if (PyErr_Occurred()) {
3182 PyErr_WriteUnraisable(result);
3183 *al = SSL_AD_INTERNAL_ERROR;
3184 }
3185 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3186 }
3187 else {
3188 ret = SSL_TLSEXT_ERR_OK;
3189 }
3190 Py_DECREF(result);
3191 }
3192
3193#ifdef WITH_THREAD
3194 PyGILState_Release(gstate);
3195#endif
3196 return ret;
3197
3198error:
3199 Py_DECREF(ssl_socket);
3200 *al = SSL_AD_INTERNAL_ERROR;
3201 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3202#ifdef WITH_THREAD
3203 PyGILState_Release(gstate);
3204#endif
3205 return ret;
3206}
3207#endif
3208
3209PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3210"set_servername_callback(method)\n\
3211\n\
3212This sets a callback that will be called when a server name is provided by\n\
3213the SSL/TLS client in the SNI extension.\n\
3214\n\
3215If the argument is None then the callback is disabled. The method is called\n\
3216with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3217See RFC 6066 for details of the SNI extension.");
3218
3219static PyObject *
3220set_servername_callback(PySSLContext *self, PyObject *args)
3221{
3222#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3223 PyObject *cb;
3224
3225 if (!PyArg_ParseTuple(args, "O", &cb))
3226 return NULL;
3227
3228 Py_CLEAR(self->set_hostname);
3229 if (cb == Py_None) {
3230 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3231 }
3232 else {
3233 if (!PyCallable_Check(cb)) {
3234 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3235 PyErr_SetString(PyExc_TypeError,
3236 "not a callable object");
3237 return NULL;
3238 }
3239 Py_INCREF(cb);
3240 self->set_hostname = cb;
3241 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3242 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3243 }
3244 Py_RETURN_NONE;
3245#else
3246 PyErr_SetString(PyExc_NotImplementedError,
3247 "The TLS extension servername callback, "
3248 "SSL_CTX_set_tlsext_servername_callback, "
3249 "is not in the current OpenSSL library.");
3250 return NULL;
3251#endif
3252}
3253
3254PyDoc_STRVAR(PySSL_get_stats_doc,
3255"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3256\n\
3257Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3258CA extension and certificate revocation lists inside the context's cert\n\
3259store.\n\
3260NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3261been used at least once.");
3262
3263static PyObject *
3264cert_store_stats(PySSLContext *self)
3265{
3266 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003267 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003268 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003269 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003270
3271 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003272 objs = X509_STORE_get0_objects(store);
3273 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3274 obj = sk_X509_OBJECT_value(objs, i);
3275 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003276 case X509_LU_X509:
3277 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003278 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003279 ca++;
3280 }
3281 break;
3282 case X509_LU_CRL:
3283 crl++;
3284 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003285 default:
3286 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3287 * As far as I can tell they are internal states and never
3288 * stored in a cert store */
3289 break;
3290 }
3291 }
3292 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3293 "x509_ca", ca);
3294}
3295
3296PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3297"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3298\n\
3299Returns a list of dicts with information of loaded CA certs. If the\n\
3300optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3301NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3302been used at least once.");
3303
3304static PyObject *
3305get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3306{
3307 char *kwlist[] = {"binary_form", NULL};
3308 X509_STORE *store;
3309 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003310 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003311 int i;
3312 int binary_mode = 0;
3313
3314 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3315 kwlist, &py_binary_mode)) {
3316 return NULL;
3317 }
3318 binary_mode = PyObject_IsTrue(py_binary_mode);
3319 if (binary_mode < 0) {
3320 return NULL;
3321 }
3322
3323 if ((rlist = PyList_New(0)) == NULL) {
3324 return NULL;
3325 }
3326
3327 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003328 objs = X509_STORE_get0_objects(store);
3329 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003330 X509_OBJECT *obj;
3331 X509 *cert;
3332
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003333 obj = sk_X509_OBJECT_value(objs, i);
3334 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003335 /* not a x509 cert */
3336 continue;
3337 }
3338 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003339 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003340 if (!X509_check_ca(cert)) {
3341 continue;
3342 }
3343 if (binary_mode) {
3344 ci = _certificate_to_der(cert);
3345 } else {
3346 ci = _decode_certificate(cert);
3347 }
3348 if (ci == NULL) {
3349 goto error;
3350 }
3351 if (PyList_Append(rlist, ci) == -1) {
3352 goto error;
3353 }
3354 Py_CLEAR(ci);
3355 }
3356 return rlist;
3357
3358 error:
3359 Py_XDECREF(ci);
3360 Py_XDECREF(rlist);
3361 return NULL;
3362}
3363
3364
3365static PyGetSetDef context_getsetlist[] = {
3366 {"check_hostname", (getter) get_check_hostname,
3367 (setter) set_check_hostname, NULL},
3368 {"options", (getter) get_options,
3369 (setter) set_options, NULL},
3370#ifdef HAVE_OPENSSL_VERIFY_PARAM
3371 {"verify_flags", (getter) get_verify_flags,
3372 (setter) set_verify_flags, NULL},
3373#endif
3374 {"verify_mode", (getter) get_verify_mode,
3375 (setter) set_verify_mode, NULL},
3376 {NULL}, /* sentinel */
3377};
3378
3379static struct PyMethodDef context_methods[] = {
3380 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3381 METH_VARARGS | METH_KEYWORDS, NULL},
3382 {"set_ciphers", (PyCFunction) set_ciphers,
3383 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003384 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3385 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003386 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3387 METH_VARARGS, NULL},
3388 {"load_cert_chain", (PyCFunction) load_cert_chain,
3389 METH_VARARGS | METH_KEYWORDS, NULL},
3390 {"load_dh_params", (PyCFunction) load_dh_params,
3391 METH_O, NULL},
3392 {"load_verify_locations", (PyCFunction) load_verify_locations,
3393 METH_VARARGS | METH_KEYWORDS, NULL},
3394 {"session_stats", (PyCFunction) session_stats,
3395 METH_NOARGS, NULL},
3396 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3397 METH_NOARGS, NULL},
3398#ifndef OPENSSL_NO_ECDH
3399 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3400 METH_O, NULL},
3401#endif
3402 {"set_servername_callback", (PyCFunction) set_servername_callback,
3403 METH_VARARGS, PySSL_set_servername_callback_doc},
3404 {"cert_store_stats", (PyCFunction) cert_store_stats,
3405 METH_NOARGS, PySSL_get_stats_doc},
3406 {"get_ca_certs", (PyCFunction) get_ca_certs,
3407 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3408 {NULL, NULL} /* sentinel */
3409};
3410
3411static PyTypeObject PySSLContext_Type = {
3412 PyVarObject_HEAD_INIT(NULL, 0)
3413 "_ssl._SSLContext", /*tp_name*/
3414 sizeof(PySSLContext), /*tp_basicsize*/
3415 0, /*tp_itemsize*/
3416 (destructor)context_dealloc, /*tp_dealloc*/
3417 0, /*tp_print*/
3418 0, /*tp_getattr*/
3419 0, /*tp_setattr*/
3420 0, /*tp_reserved*/
3421 0, /*tp_repr*/
3422 0, /*tp_as_number*/
3423 0, /*tp_as_sequence*/
3424 0, /*tp_as_mapping*/
3425 0, /*tp_hash*/
3426 0, /*tp_call*/
3427 0, /*tp_str*/
3428 0, /*tp_getattro*/
3429 0, /*tp_setattro*/
3430 0, /*tp_as_buffer*/
3431 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3432 0, /*tp_doc*/
3433 (traverseproc) context_traverse, /*tp_traverse*/
3434 (inquiry) context_clear, /*tp_clear*/
3435 0, /*tp_richcompare*/
3436 0, /*tp_weaklistoffset*/
3437 0, /*tp_iter*/
3438 0, /*tp_iternext*/
3439 context_methods, /*tp_methods*/
3440 0, /*tp_members*/
3441 context_getsetlist, /*tp_getset*/
3442 0, /*tp_base*/
3443 0, /*tp_dict*/
3444 0, /*tp_descr_get*/
3445 0, /*tp_descr_set*/
3446 0, /*tp_dictoffset*/
3447 0, /*tp_init*/
3448 0, /*tp_alloc*/
3449 context_new, /*tp_new*/
3450};
3451
3452
3453
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003454#ifdef HAVE_OPENSSL_RAND
3455
3456/* helper routines for seeding the SSL PRNG */
3457static PyObject *
3458PySSL_RAND_add(PyObject *self, PyObject *args)
3459{
3460 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003461 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003462 double entropy;
3463
3464 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003465 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003466 do {
3467 if (len >= INT_MAX) {
3468 written = INT_MAX;
3469 } else {
3470 written = len;
3471 }
3472 RAND_add(buf, (int)written, entropy);
3473 buf += written;
3474 len -= written;
3475 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003476 Py_INCREF(Py_None);
3477 return Py_None;
3478}
3479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003480PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003481"RAND_add(string, entropy)\n\
3482\n\
3483Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003484bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003485
3486static PyObject *
3487PySSL_RAND_status(PyObject *self)
3488{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003489 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003490}
3491
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003492PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003493"RAND_status() -> 0 or 1\n\
3494\n\
3495Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3496It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003497using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003498
Victor Stinner7c906672015-01-06 13:53:37 +01003499#endif /* HAVE_OPENSSL_RAND */
3500
3501
Benjamin Peterson42e10292016-07-07 00:02:31 -07003502#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003503
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003504static PyObject *
3505PySSL_RAND_egd(PyObject *self, PyObject *arg)
3506{
3507 int bytes;
3508
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003509 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003510 return PyErr_Format(PyExc_TypeError,
3511 "RAND_egd() expected string, found %s",
3512 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003513 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003514 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003515 PyErr_SetString(PySSLErrorObject,
3516 "EGD connection failed or EGD did not return "
3517 "enough data to seed the PRNG");
3518 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003519 }
3520 return PyInt_FromLong(bytes);
3521}
3522
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003523PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003524"RAND_egd(path) -> bytes\n\
3525\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003526Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3527Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003528fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003529
Benjamin Peterson42e10292016-07-07 00:02:31 -07003530#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003531
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003532
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003533PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3534"get_default_verify_paths() -> tuple\n\
3535\n\
3536Return search paths and environment vars that are used by SSLContext's\n\
3537set_default_verify_paths() to load default CAs. The values are\n\
3538'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3539
3540static PyObject *
3541PySSL_get_default_verify_paths(PyObject *self)
3542{
3543 PyObject *ofile_env = NULL;
3544 PyObject *ofile = NULL;
3545 PyObject *odir_env = NULL;
3546 PyObject *odir = NULL;
3547
Benjamin Peterson65192c12015-07-18 10:59:13 -07003548#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003549 const char *tmp = (info); \
3550 target = NULL; \
3551 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3552 else { target = PyBytes_FromString(tmp); } \
3553 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003554 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003555
Benjamin Peterson65192c12015-07-18 10:59:13 -07003556 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3557 CONVERT(X509_get_default_cert_file(), ofile);
3558 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3559 CONVERT(X509_get_default_cert_dir(), odir);
3560#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003561
3562 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3563
3564 error:
3565 Py_XDECREF(ofile_env);
3566 Py_XDECREF(ofile);
3567 Py_XDECREF(odir_env);
3568 Py_XDECREF(odir);
3569 return NULL;
3570}
3571
3572static PyObject*
3573asn1obj2py(ASN1_OBJECT *obj)
3574{
3575 int nid;
3576 const char *ln, *sn;
3577 char buf[100];
3578 Py_ssize_t buflen;
3579
3580 nid = OBJ_obj2nid(obj);
3581 if (nid == NID_undef) {
3582 PyErr_Format(PyExc_ValueError, "Unknown object");
3583 return NULL;
3584 }
3585 sn = OBJ_nid2sn(nid);
3586 ln = OBJ_nid2ln(nid);
3587 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3588 if (buflen < 0) {
3589 _setSSLError(NULL, 0, __FILE__, __LINE__);
3590 return NULL;
3591 }
3592 if (buflen) {
3593 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3594 } else {
3595 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3596 }
3597}
3598
3599PyDoc_STRVAR(PySSL_txt2obj_doc,
3600"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3601\n\
3602Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3603objects are looked up by OID. With name=True short and long name are also\n\
3604matched.");
3605
3606static PyObject*
3607PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3608{
3609 char *kwlist[] = {"txt", "name", NULL};
3610 PyObject *result = NULL;
3611 char *txt;
3612 PyObject *pyname = Py_None;
3613 int name = 0;
3614 ASN1_OBJECT *obj;
3615
3616 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3617 kwlist, &txt, &pyname)) {
3618 return NULL;
3619 }
3620 name = PyObject_IsTrue(pyname);
3621 if (name < 0)
3622 return NULL;
3623 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3624 if (obj == NULL) {
3625 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3626 return NULL;
3627 }
3628 result = asn1obj2py(obj);
3629 ASN1_OBJECT_free(obj);
3630 return result;
3631}
3632
3633PyDoc_STRVAR(PySSL_nid2obj_doc,
3634"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3635\n\
3636Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3637
3638static PyObject*
3639PySSL_nid2obj(PyObject *self, PyObject *args)
3640{
3641 PyObject *result = NULL;
3642 int nid;
3643 ASN1_OBJECT *obj;
3644
3645 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3646 return NULL;
3647 }
3648 if (nid < NID_undef) {
3649 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3650 return NULL;
3651 }
3652 obj = OBJ_nid2obj(nid);
3653 if (obj == NULL) {
3654 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3655 return NULL;
3656 }
3657 result = asn1obj2py(obj);
3658 ASN1_OBJECT_free(obj);
3659 return result;
3660}
3661
3662#ifdef _MSC_VER
3663
3664static PyObject*
3665certEncodingType(DWORD encodingType)
3666{
3667 static PyObject *x509_asn = NULL;
3668 static PyObject *pkcs_7_asn = NULL;
3669
3670 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003671 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003672 if (x509_asn == NULL)
3673 return NULL;
3674 }
3675 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003676 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003677 if (pkcs_7_asn == NULL)
3678 return NULL;
3679 }
3680 switch(encodingType) {
3681 case X509_ASN_ENCODING:
3682 Py_INCREF(x509_asn);
3683 return x509_asn;
3684 case PKCS_7_ASN_ENCODING:
3685 Py_INCREF(pkcs_7_asn);
3686 return pkcs_7_asn;
3687 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003688 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003689 }
3690}
3691
3692static PyObject*
3693parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3694{
3695 CERT_ENHKEY_USAGE *usage;
3696 DWORD size, error, i;
3697 PyObject *retval;
3698
3699 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3700 error = GetLastError();
3701 if (error == CRYPT_E_NOT_FOUND) {
3702 Py_RETURN_TRUE;
3703 }
3704 return PyErr_SetFromWindowsErr(error);
3705 }
3706
3707 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3708 if (usage == NULL) {
3709 return PyErr_NoMemory();
3710 }
3711
3712 /* Now get the actual enhanced usage property */
3713 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3714 PyMem_Free(usage);
3715 error = GetLastError();
3716 if (error == CRYPT_E_NOT_FOUND) {
3717 Py_RETURN_TRUE;
3718 }
3719 return PyErr_SetFromWindowsErr(error);
3720 }
3721 retval = PySet_New(NULL);
3722 if (retval == NULL) {
3723 goto error;
3724 }
3725 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3726 if (usage->rgpszUsageIdentifier[i]) {
3727 PyObject *oid;
3728 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003729 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003730 if (oid == NULL) {
3731 Py_CLEAR(retval);
3732 goto error;
3733 }
3734 err = PySet_Add(retval, oid);
3735 Py_DECREF(oid);
3736 if (err == -1) {
3737 Py_CLEAR(retval);
3738 goto error;
3739 }
3740 }
3741 }
3742 error:
3743 PyMem_Free(usage);
3744 return retval;
3745}
3746
3747PyDoc_STRVAR(PySSL_enum_certificates_doc,
3748"enum_certificates(store_name) -> []\n\
3749\n\
3750Retrieve certificates from Windows' cert store. store_name may be one of\n\
3751'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3752The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3753encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3754PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3755boolean True.");
3756
3757static PyObject *
3758PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3759{
3760 char *kwlist[] = {"store_name", NULL};
3761 char *store_name;
3762 HCERTSTORE hStore = NULL;
3763 PCCERT_CONTEXT pCertCtx = NULL;
3764 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3765 PyObject *result = NULL;
3766
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003767 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003768 kwlist, &store_name)) {
3769 return NULL;
3770 }
3771 result = PyList_New(0);
3772 if (result == NULL) {
3773 return NULL;
3774 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003775 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3776 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3777 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003778 if (hStore == NULL) {
3779 Py_DECREF(result);
3780 return PyErr_SetFromWindowsErr(GetLastError());
3781 }
3782
3783 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3784 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3785 pCertCtx->cbCertEncoded);
3786 if (!cert) {
3787 Py_CLEAR(result);
3788 break;
3789 }
3790 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3791 Py_CLEAR(result);
3792 break;
3793 }
3794 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3795 if (keyusage == Py_True) {
3796 Py_DECREF(keyusage);
3797 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3798 }
3799 if (keyusage == NULL) {
3800 Py_CLEAR(result);
3801 break;
3802 }
3803 if ((tup = PyTuple_New(3)) == NULL) {
3804 Py_CLEAR(result);
3805 break;
3806 }
3807 PyTuple_SET_ITEM(tup, 0, cert);
3808 cert = NULL;
3809 PyTuple_SET_ITEM(tup, 1, enc);
3810 enc = NULL;
3811 PyTuple_SET_ITEM(tup, 2, keyusage);
3812 keyusage = NULL;
3813 if (PyList_Append(result, tup) < 0) {
3814 Py_CLEAR(result);
3815 break;
3816 }
3817 Py_CLEAR(tup);
3818 }
3819 if (pCertCtx) {
3820 /* loop ended with an error, need to clean up context manually */
3821 CertFreeCertificateContext(pCertCtx);
3822 }
3823
3824 /* In error cases cert, enc and tup may not be NULL */
3825 Py_XDECREF(cert);
3826 Py_XDECREF(enc);
3827 Py_XDECREF(keyusage);
3828 Py_XDECREF(tup);
3829
3830 if (!CertCloseStore(hStore, 0)) {
3831 /* This error case might shadow another exception.*/
3832 Py_XDECREF(result);
3833 return PyErr_SetFromWindowsErr(GetLastError());
3834 }
3835 return result;
3836}
3837
3838PyDoc_STRVAR(PySSL_enum_crls_doc,
3839"enum_crls(store_name) -> []\n\
3840\n\
3841Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3842'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3843The function returns a list of (bytes, encoding_type) tuples. The\n\
3844encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3845PKCS_7_ASN_ENCODING.");
3846
3847static PyObject *
3848PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3849{
3850 char *kwlist[] = {"store_name", NULL};
3851 char *store_name;
3852 HCERTSTORE hStore = NULL;
3853 PCCRL_CONTEXT pCrlCtx = NULL;
3854 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3855 PyObject *result = NULL;
3856
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003857 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003858 kwlist, &store_name)) {
3859 return NULL;
3860 }
3861 result = PyList_New(0);
3862 if (result == NULL) {
3863 return NULL;
3864 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003865 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3866 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3867 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003868 if (hStore == NULL) {
3869 Py_DECREF(result);
3870 return PyErr_SetFromWindowsErr(GetLastError());
3871 }
3872
3873 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3874 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3875 pCrlCtx->cbCrlEncoded);
3876 if (!crl) {
3877 Py_CLEAR(result);
3878 break;
3879 }
3880 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3881 Py_CLEAR(result);
3882 break;
3883 }
3884 if ((tup = PyTuple_New(2)) == NULL) {
3885 Py_CLEAR(result);
3886 break;
3887 }
3888 PyTuple_SET_ITEM(tup, 0, crl);
3889 crl = NULL;
3890 PyTuple_SET_ITEM(tup, 1, enc);
3891 enc = NULL;
3892
3893 if (PyList_Append(result, tup) < 0) {
3894 Py_CLEAR(result);
3895 break;
3896 }
3897 Py_CLEAR(tup);
3898 }
3899 if (pCrlCtx) {
3900 /* loop ended with an error, need to clean up context manually */
3901 CertFreeCRLContext(pCrlCtx);
3902 }
3903
3904 /* In error cases cert, enc and tup may not be NULL */
3905 Py_XDECREF(crl);
3906 Py_XDECREF(enc);
3907 Py_XDECREF(tup);
3908
3909 if (!CertCloseStore(hStore, 0)) {
3910 /* This error case might shadow another exception.*/
3911 Py_XDECREF(result);
3912 return PyErr_SetFromWindowsErr(GetLastError());
3913 }
3914 return result;
3915}
3916
3917#endif /* _MSC_VER */
3918
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003919/* List of functions exported by this module. */
3920
3921static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003922 {"_test_decode_cert", PySSL_test_decode_certificate,
3923 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003924#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003925 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3926 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003927 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3928 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003929#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003930#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003931 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3932 PySSL_RAND_egd_doc},
3933#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003934 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3935 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3936#ifdef _MSC_VER
3937 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3938 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3939 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3940 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3941#endif
3942 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3943 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3944 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3945 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003946 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003947};
3948
3949
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003950#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003951
3952/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003953 * of the Python C thread library
3954 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3955 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003956
3957static PyThread_type_lock *_ssl_locks = NULL;
3958
Christian Heimes10107812013-08-19 17:36:29 +02003959#if OPENSSL_VERSION_NUMBER >= 0x10000000
3960/* use new CRYPTO_THREADID API. */
3961static void
3962_ssl_threadid_callback(CRYPTO_THREADID *id)
3963{
3964 CRYPTO_THREADID_set_numeric(id,
3965 (unsigned long)PyThread_get_thread_ident());
3966}
3967#else
3968/* deprecated CRYPTO_set_id_callback() API. */
3969static unsigned long
3970_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003971 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003972}
Christian Heimes10107812013-08-19 17:36:29 +02003973#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003974
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003975static void _ssl_thread_locking_function
3976 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003977 /* this function is needed to perform locking on shared data
3978 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003979 structures that will be implicitly shared whenever multiple
3980 threads use OpenSSL.) Multi-threaded applications will
3981 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003982
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003983 locking_function() must be able to handle up to
3984 CRYPTO_num_locks() different mutex locks. It sets the n-th
3985 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003986
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003987 file and line are the file number of the function setting the
3988 lock. They can be useful for debugging.
3989 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003990
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003991 if ((_ssl_locks == NULL) ||
3992 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3993 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003994
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003995 if (mode & CRYPTO_LOCK) {
3996 PyThread_acquire_lock(_ssl_locks[n], 1);
3997 } else {
3998 PyThread_release_lock(_ssl_locks[n]);
3999 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004000}
4001
4002static int _setup_ssl_threads(void) {
4003
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004004 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004005
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004006 if (_ssl_locks == NULL) {
4007 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004008 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4009 if (_ssl_locks == NULL) {
4010 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004011 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004012 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004013 memset(_ssl_locks, 0,
4014 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004015 for (i = 0; i < _ssl_locks_count; i++) {
4016 _ssl_locks[i] = PyThread_allocate_lock();
4017 if (_ssl_locks[i] == NULL) {
4018 unsigned int j;
4019 for (j = 0; j < i; j++) {
4020 PyThread_free_lock(_ssl_locks[j]);
4021 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004022 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004023 return 0;
4024 }
4025 }
4026 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004027#if OPENSSL_VERSION_NUMBER >= 0x10000000
4028 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4029#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004030 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004031#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004032 }
4033 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004034}
4035
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004036#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004038PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004039"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004040for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004041
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004042
4043
4044
4045static void
4046parse_openssl_version(unsigned long libver,
4047 unsigned int *major, unsigned int *minor,
4048 unsigned int *fix, unsigned int *patch,
4049 unsigned int *status)
4050{
4051 *status = libver & 0xF;
4052 libver >>= 4;
4053 *patch = libver & 0xFF;
4054 libver >>= 8;
4055 *fix = libver & 0xFF;
4056 libver >>= 8;
4057 *minor = libver & 0xFF;
4058 libver >>= 8;
4059 *major = libver & 0xFF;
4060}
4061
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004062PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004063init_ssl(void)
4064{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004065 PyObject *m, *d, *r;
4066 unsigned long libver;
4067 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004068 struct py_ssl_error_code *errcode;
4069 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004070
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004071 if (PyType_Ready(&PySSLContext_Type) < 0)
4072 return;
4073 if (PyType_Ready(&PySSLSocket_Type) < 0)
4074 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004075
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004076 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4077 if (m == NULL)
4078 return;
4079 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004080
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004081 /* Load _socket module and its C API */
4082 if (PySocketModule_ImportModuleAndAPI())
4083 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004084
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004085 /* Init OpenSSL */
4086 SSL_load_error_strings();
4087 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00004088#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004089#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004090 /* note that this will start threading if not already started */
4091 if (!_setup_ssl_threads()) {
4092 return;
4093 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004094#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4095 /* OpenSSL 1.1.0 builtin thread support is enabled */
4096 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004097#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004098#endif /* WITH_THREAD */
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004099 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004100
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004101 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004102 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4103 "ssl.SSLError", SSLError_doc,
4104 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004105 if (PySSLErrorObject == NULL)
4106 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004107 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4108
4109 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4110 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4111 PySSLErrorObject, NULL);
4112 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4113 "ssl.SSLWantReadError", SSLWantReadError_doc,
4114 PySSLErrorObject, NULL);
4115 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4116 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4117 PySSLErrorObject, NULL);
4118 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4119 "ssl.SSLSyscallError", SSLSyscallError_doc,
4120 PySSLErrorObject, NULL);
4121 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4122 "ssl.SSLEOFError", SSLEOFError_doc,
4123 PySSLErrorObject, NULL);
4124 if (PySSLZeroReturnErrorObject == NULL
4125 || PySSLWantReadErrorObject == NULL
4126 || PySSLWantWriteErrorObject == NULL
4127 || PySSLSyscallErrorObject == NULL
4128 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004129 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004130
4131 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4132 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4133 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4134 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4135 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4136
4137 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4138 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4139 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4140 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4141 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4142 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4143 return;
4144 if (PyDict_SetItemString(d, "_SSLContext",
4145 (PyObject *)&PySSLContext_Type) != 0)
4146 return;
4147 if (PyDict_SetItemString(d, "_SSLSocket",
4148 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004149 return;
4150 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4151 PY_SSL_ERROR_ZERO_RETURN);
4152 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4153 PY_SSL_ERROR_WANT_READ);
4154 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4155 PY_SSL_ERROR_WANT_WRITE);
4156 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4157 PY_SSL_ERROR_WANT_X509_LOOKUP);
4158 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4159 PY_SSL_ERROR_SYSCALL);
4160 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4161 PY_SSL_ERROR_SSL);
4162 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4163 PY_SSL_ERROR_WANT_CONNECT);
4164 /* non ssl.h errorcodes */
4165 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4166 PY_SSL_ERROR_EOF);
4167 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4168 PY_SSL_ERROR_INVALID_ERROR_CODE);
4169 /* cert requirements */
4170 PyModule_AddIntConstant(m, "CERT_NONE",
4171 PY_SSL_CERT_NONE);
4172 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4173 PY_SSL_CERT_OPTIONAL);
4174 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4175 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004176 /* CRL verification for verification_flags */
4177 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4178 0);
4179 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4180 X509_V_FLAG_CRL_CHECK);
4181 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4182 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4183 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4184 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004185#ifdef X509_V_FLAG_TRUSTED_FIRST
4186 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4187 X509_V_FLAG_TRUSTED_FIRST);
4188#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004189
4190 /* Alert Descriptions from ssl.h */
4191 /* note RESERVED constants no longer intended for use have been removed */
4192 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4193
4194#define ADD_AD_CONSTANT(s) \
4195 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4196 SSL_AD_##s)
4197
4198 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4199 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4200 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4201 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4202 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4203 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4204 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4205 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4206 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4207 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4208 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4209 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4210 ADD_AD_CONSTANT(UNKNOWN_CA);
4211 ADD_AD_CONSTANT(ACCESS_DENIED);
4212 ADD_AD_CONSTANT(DECODE_ERROR);
4213 ADD_AD_CONSTANT(DECRYPT_ERROR);
4214 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4215 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4216 ADD_AD_CONSTANT(INTERNAL_ERROR);
4217 ADD_AD_CONSTANT(USER_CANCELLED);
4218 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4219 /* Not all constants are in old OpenSSL versions */
4220#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4221 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4222#endif
4223#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4224 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4225#endif
4226#ifdef SSL_AD_UNRECOGNIZED_NAME
4227 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4228#endif
4229#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4230 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4231#endif
4232#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4233 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4234#endif
4235#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4236 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4237#endif
4238
4239#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004240
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004241 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004242#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004243 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4244 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004245#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004246#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004247 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4248 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004249#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004250 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004251 PY_SSL_VERSION_TLS);
4252 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4253 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004254 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4255 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004256#if HAVE_TLSv1_2
4257 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4258 PY_SSL_VERSION_TLS1_1);
4259 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4260 PY_SSL_VERSION_TLS1_2);
4261#endif
4262
4263 /* protocol options */
4264 PyModule_AddIntConstant(m, "OP_ALL",
4265 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4266 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4267 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4268 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4269#if HAVE_TLSv1_2
4270 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4271 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4272#endif
4273 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4274 SSL_OP_CIPHER_SERVER_PREFERENCE);
4275 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4276#ifdef SSL_OP_SINGLE_ECDH_USE
4277 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4278#endif
4279#ifdef SSL_OP_NO_COMPRESSION
4280 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4281 SSL_OP_NO_COMPRESSION);
4282#endif
4283
4284#if HAVE_SNI
4285 r = Py_True;
4286#else
4287 r = Py_False;
4288#endif
4289 Py_INCREF(r);
4290 PyModule_AddObject(m, "HAS_SNI", r);
4291
4292#if HAVE_OPENSSL_FINISHED
4293 r = Py_True;
4294#else
4295 r = Py_False;
4296#endif
4297 Py_INCREF(r);
4298 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4299
4300#ifdef OPENSSL_NO_ECDH
4301 r = Py_False;
4302#else
4303 r = Py_True;
4304#endif
4305 Py_INCREF(r);
4306 PyModule_AddObject(m, "HAS_ECDH", r);
4307
4308#ifdef OPENSSL_NPN_NEGOTIATED
4309 r = Py_True;
4310#else
4311 r = Py_False;
4312#endif
4313 Py_INCREF(r);
4314 PyModule_AddObject(m, "HAS_NPN", r);
4315
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004316#ifdef HAVE_ALPN
4317 r = Py_True;
4318#else
4319 r = Py_False;
4320#endif
4321 Py_INCREF(r);
4322 PyModule_AddObject(m, "HAS_ALPN", r);
4323
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004324 /* Mappings for error codes */
4325 err_codes_to_names = PyDict_New();
4326 err_names_to_codes = PyDict_New();
4327 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4328 return;
4329 errcode = error_codes;
4330 while (errcode->mnemonic != NULL) {
4331 PyObject *mnemo, *key;
4332 mnemo = PyUnicode_FromString(errcode->mnemonic);
4333 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4334 if (mnemo == NULL || key == NULL)
4335 return;
4336 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4337 return;
4338 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4339 return;
4340 Py_DECREF(key);
4341 Py_DECREF(mnemo);
4342 errcode++;
4343 }
4344 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4345 return;
4346 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4347 return;
4348
4349 lib_codes_to_names = PyDict_New();
4350 if (lib_codes_to_names == NULL)
4351 return;
4352 libcode = library_codes;
4353 while (libcode->library != NULL) {
4354 PyObject *mnemo, *key;
4355 key = PyLong_FromLong(libcode->code);
4356 mnemo = PyUnicode_FromString(libcode->library);
4357 if (key == NULL || mnemo == NULL)
4358 return;
4359 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4360 return;
4361 Py_DECREF(key);
4362 Py_DECREF(mnemo);
4363 libcode++;
4364 }
4365 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4366 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004367
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004368 /* OpenSSL version */
4369 /* SSLeay() gives us the version of the library linked against,
4370 which could be different from the headers version.
4371 */
4372 libver = SSLeay();
4373 r = PyLong_FromUnsignedLong(libver);
4374 if (r == NULL)
4375 return;
4376 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4377 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004378 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004379 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4380 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4381 return;
4382 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4383 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4384 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004385
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004386 libver = OPENSSL_VERSION_NUMBER;
4387 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4388 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4389 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4390 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004391}