blob: 761554a7827f4eaa8eefbd2286ade80aa1087b72 [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;
Christian Heimes72ed2332017-09-05 01:11:40 +0200283#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
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 *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200679_asn1obj2py(const ASN1_OBJECT *name, int no_name)
680{
681 char buf[X509_NAME_MAXLEN];
682 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000683 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200684 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000685
Christian Heimesc9d668c2017-09-05 19:13:07 +0200686 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000687 if (buflen < 0) {
688 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200689 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000690 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200691 /* initial buffer is too small for oid + terminating null byte */
692 if (buflen > X509_NAME_MAXLEN - 1) {
693 /* make OBJ_obj2txt() calculate the required buflen */
694 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
695 /* allocate len + 1 for terminating NULL byte */
696 namebuf = PyMem_Malloc(buflen + 1);
697 if (namebuf == NULL) {
698 PyErr_NoMemory();
699 return NULL;
700 }
701 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
702 if (buflen < 0) {
703 _setSSLError(NULL, 0, __FILE__, __LINE__);
704 goto done;
705 }
706 }
707 if (!buflen && no_name) {
708 Py_INCREF(Py_None);
709 name_obj = Py_None;
710 }
711 else {
712 name_obj = PyString_FromStringAndSize(namebuf, buflen);
713 }
714
715 done:
716 if (buf != namebuf) {
717 PyMem_Free(namebuf);
718 }
719 return name_obj;
720}
721
722static PyObject *
723_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
724{
725 Py_ssize_t buflen;
726 unsigned char *valuebuf = NULL;
727 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000728
729 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
730 if (buflen < 0) {
731 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200732 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000733 }
734 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000735 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000736
Christian Heimesc9d668c2017-09-05 19:13:07 +0200737 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
738 OPENSSL_free(valuebuf);
739 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000740}
741
742static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000743_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000744{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000745 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
746 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
747 PyObject *rdnt;
748 PyObject *attr = NULL; /* tuple to hold an attribute */
749 int entry_count = X509_NAME_entry_count(xname);
750 X509_NAME_ENTRY *entry;
751 ASN1_OBJECT *name;
752 ASN1_STRING *value;
753 int index_counter;
754 int rdn_level = -1;
755 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000756
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000757 dn = PyList_New(0);
758 if (dn == NULL)
759 return NULL;
760 /* now create another tuple to hold the top-level RDN */
761 rdn = PyList_New(0);
762 if (rdn == NULL)
763 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000764
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000765 for (index_counter = 0;
766 index_counter < entry_count;
767 index_counter++)
768 {
769 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000770
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000771 /* check to see if we've gotten to a new RDN */
772 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200773 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000774 /* yes, new RDN */
775 /* add old RDN to DN */
776 rdnt = PyList_AsTuple(rdn);
777 Py_DECREF(rdn);
778 if (rdnt == NULL)
779 goto fail0;
780 retcode = PyList_Append(dn, rdnt);
781 Py_DECREF(rdnt);
782 if (retcode < 0)
783 goto fail0;
784 /* create new RDN */
785 rdn = PyList_New(0);
786 if (rdn == NULL)
787 goto fail0;
788 }
789 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200790 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000791
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000792 /* now add this attribute to the current RDN */
793 name = X509_NAME_ENTRY_get_object(entry);
794 value = X509_NAME_ENTRY_get_data(entry);
795 attr = _create_tuple_for_attribute(name, value);
796 /*
797 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
798 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500799 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
800 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000801 */
802 if (attr == NULL)
803 goto fail1;
804 retcode = PyList_Append(rdn, attr);
805 Py_DECREF(attr);
806 if (retcode < 0)
807 goto fail1;
808 }
809 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100810 if (rdn != NULL) {
811 if (PyList_GET_SIZE(rdn) > 0) {
812 rdnt = PyList_AsTuple(rdn);
813 Py_DECREF(rdn);
814 if (rdnt == NULL)
815 goto fail0;
816 retcode = PyList_Append(dn, rdnt);
817 Py_DECREF(rdnt);
818 if (retcode < 0)
819 goto fail0;
820 }
821 else {
822 Py_DECREF(rdn);
823 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000824 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000825
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000826 /* convert list to tuple */
827 rdnt = PyList_AsTuple(dn);
828 Py_DECREF(dn);
829 if (rdnt == NULL)
830 return NULL;
831 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000832
833 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000834 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000835
836 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000837 Py_XDECREF(dn);
838 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000839}
840
841static PyObject *
842_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000843
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000844 /* this code follows the procedure outlined in
845 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
846 function to extract the STACK_OF(GENERAL_NAME),
847 then iterates through the stack to add the
848 names. */
849
850 int i, j;
851 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200852 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000853 X509_EXTENSION *ext = NULL;
854 GENERAL_NAMES *names = NULL;
855 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000856 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000857 BIO *biobuf = NULL;
858 char buf[2048];
859 char *vptr;
860 int len;
861 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000862#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000863 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000864#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000865 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000866#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000867
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000868 if (certificate == NULL)
869 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000870
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000871 /* get a memory buffer */
872 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000873
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200874 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000875 while ((i = X509_get_ext_by_NID(
876 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000877
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000878 if (peer_alt_names == Py_None) {
879 peer_alt_names = PyList_New(0);
880 if (peer_alt_names == NULL)
881 goto fail;
882 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000883
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000884 /* now decode the altName */
885 ext = X509_get_ext(certificate, i);
886 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500887 PyErr_SetString
888 (PySSLErrorObject,
889 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000890 goto fail;
891 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200893 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000894 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500895 names = (GENERAL_NAMES*)
896 (ASN1_item_d2i(NULL,
897 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200898 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500899 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000900 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500901 names = (GENERAL_NAMES*)
902 (method->d2i(NULL,
903 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200904 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000905
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000906 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000907 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200908 int gntype;
909 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000910
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000911 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200912 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200913 switch (gntype) {
914 case GEN_DIRNAME:
915 /* we special-case DirName as a tuple of
916 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000917
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000918 t = PyTuple_New(2);
919 if (t == NULL) {
920 goto fail;
921 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000922
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000923 v = PyString_FromString("DirName");
924 if (v == NULL) {
925 Py_DECREF(t);
926 goto fail;
927 }
928 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000929
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000930 v = _create_tuple_for_X509_NAME (name->d.dirn);
931 if (v == NULL) {
932 Py_DECREF(t);
933 goto fail;
934 }
935 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200936 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000937
Christian Heimes88b174c2013-08-17 00:54:47 +0200938 case GEN_EMAIL:
939 case GEN_DNS:
940 case GEN_URI:
941 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
942 correctly, CVE-2013-4238 */
943 t = PyTuple_New(2);
944 if (t == NULL)
945 goto fail;
946 switch (gntype) {
947 case GEN_EMAIL:
948 v = PyString_FromString("email");
949 as = name->d.rfc822Name;
950 break;
951 case GEN_DNS:
952 v = PyString_FromString("DNS");
953 as = name->d.dNSName;
954 break;
955 case GEN_URI:
956 v = PyString_FromString("URI");
957 as = name->d.uniformResourceIdentifier;
958 break;
959 }
960 if (v == NULL) {
961 Py_DECREF(t);
962 goto fail;
963 }
964 PyTuple_SET_ITEM(t, 0, v);
965 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
966 ASN1_STRING_length(as));
967 if (v == NULL) {
968 Py_DECREF(t);
969 goto fail;
970 }
971 PyTuple_SET_ITEM(t, 1, v);
972 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000973
Christian Heimes6663eb62016-09-06 23:25:35 +0200974 case GEN_RID:
975 t = PyTuple_New(2);
976 if (t == NULL)
977 goto fail;
978
979 v = PyUnicode_FromString("Registered ID");
980 if (v == NULL) {
981 Py_DECREF(t);
982 goto fail;
983 }
984 PyTuple_SET_ITEM(t, 0, v);
985
986 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
987 if (len < 0) {
988 Py_DECREF(t);
989 _setSSLError(NULL, 0, __FILE__, __LINE__);
990 goto fail;
991 } else if (len >= (int)sizeof(buf)) {
992 v = PyUnicode_FromString("<INVALID>");
993 } else {
994 v = PyUnicode_FromStringAndSize(buf, len);
995 }
996 if (v == NULL) {
997 Py_DECREF(t);
998 goto fail;
999 }
1000 PyTuple_SET_ITEM(t, 1, v);
1001 break;
1002
Christian Heimes88b174c2013-08-17 00:54:47 +02001003 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001004 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001005 switch (gntype) {
1006 /* check for new general name type */
1007 case GEN_OTHERNAME:
1008 case GEN_X400:
1009 case GEN_EDIPARTY:
1010 case GEN_IPADD:
1011 case GEN_RID:
1012 break;
1013 default:
1014 if (PyErr_Warn(PyExc_RuntimeWarning,
1015 "Unknown general name type") == -1) {
1016 goto fail;
1017 }
1018 break;
1019 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001020 (void) BIO_reset(biobuf);
1021 GENERAL_NAME_print(biobuf, name);
1022 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1023 if (len < 0) {
1024 _setSSLError(NULL, 0, __FILE__, __LINE__);
1025 goto fail;
1026 }
1027 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001028 if (vptr == NULL) {
1029 PyErr_Format(PyExc_ValueError,
1030 "Invalid value %.200s",
1031 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001032 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001033 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001034 t = PyTuple_New(2);
1035 if (t == NULL)
1036 goto fail;
1037 v = PyString_FromStringAndSize(buf, (vptr - buf));
1038 if (v == NULL) {
1039 Py_DECREF(t);
1040 goto fail;
1041 }
1042 PyTuple_SET_ITEM(t, 0, v);
1043 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1044 if (v == NULL) {
1045 Py_DECREF(t);
1046 goto fail;
1047 }
1048 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001049 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001050 }
1051
1052 /* and add that rendering to the list */
1053
1054 if (PyList_Append(peer_alt_names, t) < 0) {
1055 Py_DECREF(t);
1056 goto fail;
1057 }
1058 Py_DECREF(t);
1059 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001060 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001061 }
1062 BIO_free(biobuf);
1063 if (peer_alt_names != Py_None) {
1064 v = PyList_AsTuple(peer_alt_names);
1065 Py_DECREF(peer_alt_names);
1066 return v;
1067 } else {
1068 return peer_alt_names;
1069 }
1070
Bill Janssen98d19da2007-09-10 21:51:02 +00001071
1072 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001073 if (biobuf != NULL)
1074 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001075
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001076 if (peer_alt_names != Py_None) {
1077 Py_XDECREF(peer_alt_names);
1078 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001079
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001080 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001081}
1082
1083static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001084_get_aia_uri(X509 *certificate, int nid) {
1085 PyObject *lst = NULL, *ostr = NULL;
1086 int i, result;
1087 AUTHORITY_INFO_ACCESS *info;
1088
1089 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001090 if (info == NULL)
1091 return Py_None;
1092 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1093 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001094 return Py_None;
1095 }
1096
1097 if ((lst = PyList_New(0)) == NULL) {
1098 goto fail;
1099 }
1100
1101 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1102 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1103 ASN1_IA5STRING *uri;
1104
1105 if ((OBJ_obj2nid(ad->method) != nid) ||
1106 (ad->location->type != GEN_URI)) {
1107 continue;
1108 }
1109 uri = ad->location->d.uniformResourceIdentifier;
1110 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1111 uri->length);
1112 if (ostr == NULL) {
1113 goto fail;
1114 }
1115 result = PyList_Append(lst, ostr);
1116 Py_DECREF(ostr);
1117 if (result < 0) {
1118 goto fail;
1119 }
1120 }
1121 AUTHORITY_INFO_ACCESS_free(info);
1122
1123 /* convert to tuple or None */
1124 if (PyList_Size(lst) == 0) {
1125 Py_DECREF(lst);
1126 return Py_None;
1127 } else {
1128 PyObject *tup;
1129 tup = PyList_AsTuple(lst);
1130 Py_DECREF(lst);
1131 return tup;
1132 }
1133
1134 fail:
1135 AUTHORITY_INFO_ACCESS_free(info);
1136 Py_XDECREF(lst);
1137 return NULL;
1138}
1139
1140static PyObject *
1141_get_crl_dp(X509 *certificate) {
1142 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001143 int i, j;
1144 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001145
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001146 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001147
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001148 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001149 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001150
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001151 lst = PyList_New(0);
1152 if (lst == NULL)
1153 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001154
1155 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1156 DIST_POINT *dp;
1157 STACK_OF(GENERAL_NAME) *gns;
1158
1159 dp = sk_DIST_POINT_value(dps, i);
1160 gns = dp->distpoint->name.fullname;
1161
1162 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1163 GENERAL_NAME *gn;
1164 ASN1_IA5STRING *uri;
1165 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001166 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001167
1168 gn = sk_GENERAL_NAME_value(gns, j);
1169 if (gn->type != GEN_URI) {
1170 continue;
1171 }
1172 uri = gn->d.uniformResourceIdentifier;
1173 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1174 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001175 if (ouri == NULL)
1176 goto done;
1177
1178 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001179 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001180 if (err < 0)
1181 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001182 }
1183 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001184
1185 /* Convert to tuple. */
1186 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1187
1188 done:
1189 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001190 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001191 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001192}
1193
1194static PyObject *
1195_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001196
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001197 PyObject *retval = NULL;
1198 BIO *biobuf = NULL;
1199 PyObject *peer;
1200 PyObject *peer_alt_names = NULL;
1201 PyObject *issuer;
1202 PyObject *version;
1203 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001204 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001205 ASN1_INTEGER *serialNumber;
1206 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001207 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001208 ASN1_TIME *notBefore, *notAfter;
1209 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001210
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001211 retval = PyDict_New();
1212 if (retval == NULL)
1213 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001214
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001215 peer = _create_tuple_for_X509_NAME(
1216 X509_get_subject_name(certificate));
1217 if (peer == NULL)
1218 goto fail0;
1219 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1220 Py_DECREF(peer);
1221 goto fail0;
1222 }
1223 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001224
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001225 issuer = _create_tuple_for_X509_NAME(
1226 X509_get_issuer_name(certificate));
1227 if (issuer == NULL)
1228 goto fail0;
1229 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001230 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001231 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001232 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001233 Py_DECREF(issuer);
1234
1235 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1236 if (version == NULL)
1237 goto fail0;
1238 if (PyDict_SetItemString(retval, "version", version) < 0) {
1239 Py_DECREF(version);
1240 goto fail0;
1241 }
1242 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001243
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001244 /* get a memory buffer */
1245 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001246
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001247 (void) BIO_reset(biobuf);
1248 serialNumber = X509_get_serialNumber(certificate);
1249 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1250 i2a_ASN1_INTEGER(biobuf, serialNumber);
1251 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1252 if (len < 0) {
1253 _setSSLError(NULL, 0, __FILE__, __LINE__);
1254 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001255 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001256 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1257 if (sn_obj == NULL)
1258 goto fail1;
1259 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1260 Py_DECREF(sn_obj);
1261 goto fail1;
1262 }
1263 Py_DECREF(sn_obj);
1264
1265 (void) BIO_reset(biobuf);
1266 notBefore = X509_get_notBefore(certificate);
1267 ASN1_TIME_print(biobuf, notBefore);
1268 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1269 if (len < 0) {
1270 _setSSLError(NULL, 0, __FILE__, __LINE__);
1271 goto fail1;
1272 }
1273 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1274 if (pnotBefore == NULL)
1275 goto fail1;
1276 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1277 Py_DECREF(pnotBefore);
1278 goto fail1;
1279 }
1280 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001281
1282 (void) BIO_reset(biobuf);
1283 notAfter = X509_get_notAfter(certificate);
1284 ASN1_TIME_print(biobuf, notAfter);
1285 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1286 if (len < 0) {
1287 _setSSLError(NULL, 0, __FILE__, __LINE__);
1288 goto fail1;
1289 }
1290 pnotAfter = PyString_FromStringAndSize(buf, len);
1291 if (pnotAfter == NULL)
1292 goto fail1;
1293 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1294 Py_DECREF(pnotAfter);
1295 goto fail1;
1296 }
1297 Py_DECREF(pnotAfter);
1298
1299 /* Now look for subjectAltName */
1300
1301 peer_alt_names = _get_peer_alt_names(certificate);
1302 if (peer_alt_names == NULL)
1303 goto fail1;
1304 else if (peer_alt_names != Py_None) {
1305 if (PyDict_SetItemString(retval, "subjectAltName",
1306 peer_alt_names) < 0) {
1307 Py_DECREF(peer_alt_names);
1308 goto fail1;
1309 }
1310 Py_DECREF(peer_alt_names);
1311 }
1312
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001313 /* Authority Information Access: OCSP URIs */
1314 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1315 if (obj == NULL) {
1316 goto fail1;
1317 } else if (obj != Py_None) {
1318 result = PyDict_SetItemString(retval, "OCSP", obj);
1319 Py_DECREF(obj);
1320 if (result < 0) {
1321 goto fail1;
1322 }
1323 }
1324
1325 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1326 if (obj == NULL) {
1327 goto fail1;
1328 } else if (obj != Py_None) {
1329 result = PyDict_SetItemString(retval, "caIssuers", obj);
1330 Py_DECREF(obj);
1331 if (result < 0) {
1332 goto fail1;
1333 }
1334 }
1335
1336 /* CDP (CRL distribution points) */
1337 obj = _get_crl_dp(certificate);
1338 if (obj == NULL) {
1339 goto fail1;
1340 } else if (obj != Py_None) {
1341 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1342 Py_DECREF(obj);
1343 if (result < 0) {
1344 goto fail1;
1345 }
1346 }
1347
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001348 BIO_free(biobuf);
1349 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001350
1351 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001352 if (biobuf != NULL)
1353 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001354 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001355 Py_XDECREF(retval);
1356 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001357}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001358
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001359static PyObject *
1360_certificate_to_der(X509 *certificate)
1361{
1362 unsigned char *bytes_buf = NULL;
1363 int len;
1364 PyObject *retval;
1365
1366 bytes_buf = NULL;
1367 len = i2d_X509(certificate, &bytes_buf);
1368 if (len < 0) {
1369 _setSSLError(NULL, 0, __FILE__, __LINE__);
1370 return NULL;
1371 }
1372 /* this is actually an immutable bytes sequence */
1373 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1374 OPENSSL_free(bytes_buf);
1375 return retval;
1376}
Bill Janssen98d19da2007-09-10 21:51:02 +00001377
1378static PyObject *
1379PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1380
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001381 PyObject *retval = NULL;
1382 char *filename = NULL;
1383 X509 *x=NULL;
1384 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001385
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001386 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001387 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001388
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001389 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001390 PyErr_SetString(PySSLErrorObject,
1391 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001392 goto fail0;
1393 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001394
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001395 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001396 PyErr_SetString(PySSLErrorObject,
1397 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001398 goto fail0;
1399 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001400
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001401 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1402 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001403 PyErr_SetString(PySSLErrorObject,
1404 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001405 goto fail0;
1406 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001407
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001408 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001409 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001410
1411 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001412
1413 if (cert != NULL) BIO_free(cert);
1414 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001415}
1416
1417
1418static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001419PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001420{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001421 int verification;
1422 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001423 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001424
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001425 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1426 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001427
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001428 if (!self->handshake_done) {
1429 PyErr_SetString(PyExc_ValueError,
1430 "handshake not done yet");
1431 return NULL;
1432 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001433 if (!self->peer_cert)
1434 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001435
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001436 b = PyObject_IsTrue(binary_mode);
1437 if (b < 0)
1438 return NULL;
1439 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001440 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001441 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001442 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001443 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001444 if ((verification & SSL_VERIFY_PEER) == 0)
1445 return PyDict_New();
1446 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001447 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001448 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001449}
1450
1451PyDoc_STRVAR(PySSL_peercert_doc,
1452"peer_certificate([der=False]) -> certificate\n\
1453\n\
1454Returns the certificate for the peer. If no certificate was provided,\n\
1455returns None. If a certificate was provided, but not validated, returns\n\
1456an empty dictionary. Otherwise returns a dict containing information\n\
1457about the peer certificate.\n\
1458\n\
1459If the optional argument is True, returns a DER-encoded copy of the\n\
1460peer certificate, or None if no certificate was provided. This will\n\
1461return the certificate even if it wasn't validated.");
1462
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001463static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001464
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001465 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001466 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001467 char *cipher_name;
1468 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001469
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001470 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001471 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001472 current = SSL_get_current_cipher(self->ssl);
1473 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001474 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001475
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001476 retval = PyTuple_New(3);
1477 if (retval == NULL)
1478 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001479
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001480 cipher_name = (char *) SSL_CIPHER_get_name(current);
1481 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001482 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001483 PyTuple_SET_ITEM(retval, 0, Py_None);
1484 } else {
1485 v = PyString_FromString(cipher_name);
1486 if (v == NULL)
1487 goto fail0;
1488 PyTuple_SET_ITEM(retval, 0, v);
1489 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001490 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001491 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001492 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001493 PyTuple_SET_ITEM(retval, 1, Py_None);
1494 } else {
1495 v = PyString_FromString(cipher_protocol);
1496 if (v == NULL)
1497 goto fail0;
1498 PyTuple_SET_ITEM(retval, 1, v);
1499 }
1500 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1501 if (v == NULL)
1502 goto fail0;
1503 PyTuple_SET_ITEM(retval, 2, v);
1504 return retval;
1505
Bill Janssen98d19da2007-09-10 21:51:02 +00001506 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001507 Py_DECREF(retval);
1508 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001509}
1510
Alex Gaynore98205d2014-09-04 13:33:22 -07001511static PyObject *PySSL_version(PySSLSocket *self)
1512{
1513 const char *version;
1514
1515 if (self->ssl == NULL)
1516 Py_RETURN_NONE;
1517 version = SSL_get_version(self->ssl);
1518 if (!strcmp(version, "unknown"))
1519 Py_RETURN_NONE;
1520 return PyUnicode_FromString(version);
1521}
1522
Christian Heimes72ed2332017-09-05 01:11:40 +02001523#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001524static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1525 const unsigned char *out;
1526 unsigned int outlen;
1527
1528 SSL_get0_next_proto_negotiated(self->ssl,
1529 &out, &outlen);
1530
1531 if (out == NULL)
1532 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001533 return PyString_FromStringAndSize((char *)out, outlen);
1534}
1535#endif
1536
1537#ifdef HAVE_ALPN
1538static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1539 const unsigned char *out;
1540 unsigned int outlen;
1541
1542 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1543
1544 if (out == NULL)
1545 Py_RETURN_NONE;
1546 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001547}
1548#endif
1549
1550static PyObject *PySSL_compression(PySSLSocket *self) {
1551#ifdef OPENSSL_NO_COMP
1552 Py_RETURN_NONE;
1553#else
1554 const COMP_METHOD *comp_method;
1555 const char *short_name;
1556
1557 if (self->ssl == NULL)
1558 Py_RETURN_NONE;
1559 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001560 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001561 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001562 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001563 if (short_name == NULL)
1564 Py_RETURN_NONE;
1565 return PyBytes_FromString(short_name);
1566#endif
1567}
1568
1569static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1570 Py_INCREF(self->ctx);
1571 return self->ctx;
1572}
1573
1574static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1575 void *closure) {
1576
1577 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1578#if !HAVE_SNI
1579 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1580 "context is not supported by your OpenSSL library");
1581 return -1;
1582#else
1583 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001584 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001585 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1586#endif
1587 } else {
1588 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1589 return -1;
1590 }
1591
1592 return 0;
1593}
1594
1595PyDoc_STRVAR(PySSL_set_context_doc,
1596"_setter_context(ctx)\n\
1597\
1598This changes the context associated with the SSLSocket. This is typically\n\
1599used from within a callback function set by the set_servername_callback\n\
1600on the SSLContext to change the certificate information associated with the\n\
1601SSLSocket before the cryptographic exchange handshake messages\n");
1602
1603
1604
1605static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001606{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001607 if (self->peer_cert) /* Possible not to have one? */
1608 X509_free (self->peer_cert);
1609 if (self->ssl)
1610 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001611 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001612 Py_XDECREF(self->ssl_sock);
1613 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001614 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001615}
1616
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001617/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001618 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001619 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001620 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001621
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001622static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001623check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001624{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001625 fd_set fds;
1626 struct timeval tv;
1627 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001628
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001629 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1630 if (s->sock_timeout < 0.0)
1631 return SOCKET_IS_BLOCKING;
1632 else if (s->sock_timeout == 0.0)
1633 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001634
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001635 /* Guard against closed socket */
1636 if (s->sock_fd < 0)
1637 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001638
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001639 /* Prefer poll, if available, since you can poll() any fd
1640 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001641#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001642 {
1643 struct pollfd pollfd;
1644 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001645
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001646 pollfd.fd = s->sock_fd;
1647 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001648
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001649 /* s->sock_timeout is in seconds, timeout in ms */
1650 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1651 PySSL_BEGIN_ALLOW_THREADS
1652 rc = poll(&pollfd, 1, timeout);
1653 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001654
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001655 goto normal_return;
1656 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001657#endif
1658
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001659 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001660 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001661 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001662
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001663 /* Construct the arguments to select */
1664 tv.tv_sec = (int)s->sock_timeout;
1665 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1666 FD_ZERO(&fds);
1667 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001668
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001669 /* See if the socket is ready */
1670 PySSL_BEGIN_ALLOW_THREADS
1671 if (writing)
1672 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1673 else
1674 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1675 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676
Bill Janssen934b16d2008-06-28 22:19:33 +00001677#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001678normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001679#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001680 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1681 (when we are able to write or when there's something to read) */
1682 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001683}
1684
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001685static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001686{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001687 Py_buffer buf;
1688 int len;
1689 int sockstate;
1690 int err;
1691 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001692 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001693
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001694 Py_INCREF(sock);
1695
1696 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1697 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001698 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001699 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001700
Victor Stinnerc1a44262013-06-25 00:48:02 +02001701 if (buf.len > INT_MAX) {
1702 PyErr_Format(PyExc_OverflowError,
1703 "string longer than %d bytes", INT_MAX);
1704 goto error;
1705 }
1706
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001707 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001708 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001709 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1710 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001711
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001712 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001713 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1714 PyErr_SetString(PySSLErrorObject,
1715 "The write operation timed out");
1716 goto error;
1717 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1718 PyErr_SetString(PySSLErrorObject,
1719 "Underlying socket has been closed.");
1720 goto error;
1721 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1722 PyErr_SetString(PySSLErrorObject,
1723 "Underlying socket too large for select().");
1724 goto error;
1725 }
1726 do {
1727 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001728 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001729 err = SSL_get_error(self->ssl, len);
1730 PySSL_END_ALLOW_THREADS
1731 if (PyErr_CheckSignals()) {
1732 goto error;
1733 }
1734 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001735 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001736 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001737 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001738 } else {
1739 sockstate = SOCKET_OPERATION_OK;
1740 }
1741 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1742 PyErr_SetString(PySSLErrorObject,
1743 "The write operation timed out");
1744 goto error;
1745 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1746 PyErr_SetString(PySSLErrorObject,
1747 "Underlying socket has been closed.");
1748 goto error;
1749 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1750 break;
1751 }
1752 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001753
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001754 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001755 PyBuffer_Release(&buf);
1756 if (len > 0)
1757 return PyInt_FromLong(len);
1758 else
1759 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001760
1761error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001762 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001763 PyBuffer_Release(&buf);
1764 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001765}
1766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001767PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001768"write(s) -> len\n\
1769\n\
1770Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001773static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001774{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001775 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001776
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001777 PySSL_BEGIN_ALLOW_THREADS
1778 count = SSL_pending(self->ssl);
1779 PySSL_END_ALLOW_THREADS
1780 if (count < 0)
1781 return PySSL_SetError(self, count, __FILE__, __LINE__);
1782 else
1783 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001784}
1785
1786PyDoc_STRVAR(PySSL_SSLpending_doc,
1787"pending() -> count\n\
1788\n\
1789Returns the number of already decrypted bytes available for read,\n\
1790pending on the connection.\n");
1791
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001792static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001794 PyObject *dest = NULL;
1795 Py_buffer buf;
1796 char *mem;
1797 int len, count;
1798 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001799 int sockstate;
1800 int err;
1801 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001802 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001803
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001804 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001805
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001806 buf.obj = NULL;
1807 buf.buf = NULL;
1808 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1809 goto error;
1810
1811 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001812 if (len < 0) {
1813 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1814 goto error;
1815 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001816 dest = PyBytes_FromStringAndSize(NULL, len);
1817 if (dest == NULL)
1818 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001819 if (len == 0) {
1820 Py_XDECREF(sock);
1821 return dest;
1822 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001823 mem = PyBytes_AS_STRING(dest);
1824 }
1825 else {
1826 buf_passed = 1;
1827 mem = buf.buf;
1828 if (len <= 0 || len > buf.len) {
1829 len = (int) buf.len;
1830 if (buf.len != len) {
1831 PyErr_SetString(PyExc_OverflowError,
1832 "maximum length can't fit in a C 'int'");
1833 goto error;
1834 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001835 if (len == 0) {
1836 count = 0;
1837 goto done;
1838 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839 }
1840 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001841
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001843 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001844 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1845 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001846
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001847 do {
1848 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001849 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001850 err = SSL_get_error(self->ssl, count);
1851 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001852 if (PyErr_CheckSignals())
1853 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001854 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001855 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001856 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001857 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001858 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1859 (SSL_get_shutdown(self->ssl) ==
1860 SSL_RECEIVED_SHUTDOWN))
1861 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001862 count = 0;
1863 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001864 } else {
1865 sockstate = SOCKET_OPERATION_OK;
1866 }
1867 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1868 PyErr_SetString(PySSLErrorObject,
1869 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001870 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001871 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1872 break;
1873 }
1874 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1875 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001876 PySSL_SetError(self, count, __FILE__, __LINE__);
1877 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001878 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001879
1880done:
1881 Py_DECREF(sock);
1882 if (!buf_passed) {
1883 _PyBytes_Resize(&dest, count);
1884 return dest;
1885 }
1886 else {
1887 PyBuffer_Release(&buf);
1888 return PyLong_FromLong(count);
1889 }
1890
1891error:
1892 Py_DECREF(sock);
1893 if (!buf_passed)
1894 Py_XDECREF(dest);
1895 else
1896 PyBuffer_Release(&buf);
1897 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001898}
1899
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001900PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001901"read([len]) -> string\n\
1902\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001903Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001904
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001905static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001906{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 int err, ssl_err, sockstate, nonblocking;
1908 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001909 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001910
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001911 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001912 if (sock->sock_fd < 0) {
1913 _setSSLError("Underlying socket connection gone",
1914 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001915 return NULL;
1916 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001917 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001918
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001919 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001920 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001921 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1922 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001923
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001924 while (1) {
1925 PySSL_BEGIN_ALLOW_THREADS
1926 /* Disable read-ahead so that unwrap can work correctly.
1927 * Otherwise OpenSSL might read in too much data,
1928 * eating clear text data that happens to be
1929 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001930 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001931 * function is used and the shutdown_seen_zero != 0
1932 * condition is met.
1933 */
1934 if (self->shutdown_seen_zero)
1935 SSL_set_read_ahead(self->ssl, 0);
1936 err = SSL_shutdown(self->ssl);
1937 PySSL_END_ALLOW_THREADS
1938 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1939 if (err > 0)
1940 break;
1941 if (err == 0) {
1942 /* Don't loop endlessly; instead preserve legacy
1943 behaviour of trying SSL_shutdown() only twice.
1944 This looks necessary for OpenSSL < 0.9.8m */
1945 if (++zeros > 1)
1946 break;
1947 /* Shutdown was sent, now try receiving */
1948 self->shutdown_seen_zero = 1;
1949 continue;
1950 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001951
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001952 /* Possibly retry shutdown until timeout or failure */
1953 ssl_err = SSL_get_error(self->ssl, err);
1954 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001955 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001956 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001957 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001958 else
1959 break;
1960 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1961 if (ssl_err == SSL_ERROR_WANT_READ)
1962 PyErr_SetString(PySSLErrorObject,
1963 "The read operation timed out");
1964 else
1965 PyErr_SetString(PySSLErrorObject,
1966 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001967 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001968 }
1969 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1970 PyErr_SetString(PySSLErrorObject,
1971 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001972 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001973 }
1974 else if (sockstate != SOCKET_OPERATION_OK)
1975 /* Retain the SSL error code */
1976 break;
1977 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001978
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001979 if (err < 0) {
1980 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001981 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001982 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001983 else
1984 /* It's already INCREF'ed */
1985 return (PyObject *) sock;
1986
1987error:
1988 Py_DECREF(sock);
1989 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001990}
1991
1992PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1993"shutdown(s) -> socket\n\
1994\n\
1995Does the SSL shutdown handshake with the remote end, and returns\n\
1996the underlying socket object.");
1997
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001998#if HAVE_OPENSSL_FINISHED
1999static PyObject *
2000PySSL_tls_unique_cb(PySSLSocket *self)
2001{
2002 PyObject *retval = NULL;
2003 char buf[PySSL_CB_MAXLEN];
2004 size_t len;
2005
2006 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2007 /* if session is resumed XOR we are the client */
2008 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2009 }
2010 else {
2011 /* if a new session XOR we are the server */
2012 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2013 }
2014
2015 /* It cannot be negative in current OpenSSL version as of July 2011 */
2016 if (len == 0)
2017 Py_RETURN_NONE;
2018
2019 retval = PyBytes_FromStringAndSize(buf, len);
2020
2021 return retval;
2022}
2023
2024PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2025"tls_unique_cb() -> bytes\n\
2026\n\
2027Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2028\n\
2029If the TLS handshake is not yet complete, None is returned");
2030
2031#endif /* HAVE_OPENSSL_FINISHED */
2032
2033static PyGetSetDef ssl_getsetlist[] = {
2034 {"context", (getter) PySSL_get_context,
2035 (setter) PySSL_set_context, PySSL_set_context_doc},
2036 {NULL}, /* sentinel */
2037};
2038
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002039static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002040 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2041 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2042 PySSL_SSLwrite_doc},
2043 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2044 PySSL_SSLread_doc},
2045 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2046 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002047 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2048 PySSL_peercert_doc},
2049 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002050 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002051#ifdef OPENSSL_NPN_NEGOTIATED
2052 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2053#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002054#ifdef HAVE_ALPN
2055 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2056#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002057 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002058 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2059 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002060#if HAVE_OPENSSL_FINISHED
2061 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2062 PySSL_tls_unique_cb_doc},
2063#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002064 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002065};
2066
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002067static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002068 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002069 "_ssl._SSLSocket", /*tp_name*/
2070 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002071 0, /*tp_itemsize*/
2072 /* methods */
2073 (destructor)PySSL_dealloc, /*tp_dealloc*/
2074 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002075 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002076 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002077 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002078 0, /*tp_repr*/
2079 0, /*tp_as_number*/
2080 0, /*tp_as_sequence*/
2081 0, /*tp_as_mapping*/
2082 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002083 0, /*tp_call*/
2084 0, /*tp_str*/
2085 0, /*tp_getattro*/
2086 0, /*tp_setattro*/
2087 0, /*tp_as_buffer*/
2088 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2089 0, /*tp_doc*/
2090 0, /*tp_traverse*/
2091 0, /*tp_clear*/
2092 0, /*tp_richcompare*/
2093 0, /*tp_weaklistoffset*/
2094 0, /*tp_iter*/
2095 0, /*tp_iternext*/
2096 PySSLMethods, /*tp_methods*/
2097 0, /*tp_members*/
2098 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002099};
2100
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002101
2102/*
2103 * _SSLContext objects
2104 */
2105
2106static PyObject *
2107context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2108{
2109 char *kwlist[] = {"protocol", NULL};
2110 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002111 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002112 long options;
2113 SSL_CTX *ctx = NULL;
2114
2115 if (!PyArg_ParseTupleAndKeywords(
2116 args, kwds, "i:_SSLContext", kwlist,
2117 &proto_version))
2118 return NULL;
2119
2120 PySSL_BEGIN_ALLOW_THREADS
2121 if (proto_version == PY_SSL_VERSION_TLS1)
2122 ctx = SSL_CTX_new(TLSv1_method());
2123#if HAVE_TLSv1_2
2124 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2125 ctx = SSL_CTX_new(TLSv1_1_method());
2126 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2127 ctx = SSL_CTX_new(TLSv1_2_method());
2128#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002129#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002130 else if (proto_version == PY_SSL_VERSION_SSL3)
2131 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002132#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002133#ifndef OPENSSL_NO_SSL2
2134 else if (proto_version == PY_SSL_VERSION_SSL2)
2135 ctx = SSL_CTX_new(SSLv2_method());
2136#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002137 else if (proto_version == PY_SSL_VERSION_TLS)
2138 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002139 else
2140 proto_version = -1;
2141 PySSL_END_ALLOW_THREADS
2142
2143 if (proto_version == -1) {
2144 PyErr_SetString(PyExc_ValueError,
2145 "invalid protocol version");
2146 return NULL;
2147 }
2148 if (ctx == NULL) {
2149 PyErr_SetString(PySSLErrorObject,
2150 "failed to allocate SSL context");
2151 return NULL;
2152 }
2153
2154 assert(type != NULL && type->tp_alloc != NULL);
2155 self = (PySSLContext *) type->tp_alloc(type, 0);
2156 if (self == NULL) {
2157 SSL_CTX_free(ctx);
2158 return NULL;
2159 }
2160 self->ctx = ctx;
Christian Heimes72ed2332017-09-05 01:11:40 +02002161#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002162 self->npn_protocols = NULL;
2163#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002164#ifdef HAVE_ALPN
2165 self->alpn_protocols = NULL;
2166#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002167#ifndef OPENSSL_NO_TLSEXT
2168 self->set_hostname = NULL;
2169#endif
2170 /* Don't check host name by default */
2171 self->check_hostname = 0;
2172 /* Defaults */
2173 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2174 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2175 if (proto_version != PY_SSL_VERSION_SSL2)
2176 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002177 if (proto_version != PY_SSL_VERSION_SSL3)
2178 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002179 SSL_CTX_set_options(self->ctx, options);
2180
Donald Stufftf1a696e2017-03-02 12:37:07 -05002181#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002182 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2183 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002184 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2185 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002186#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002187 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2188#else
2189 {
2190 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2191 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2192 EC_KEY_free(key);
2193 }
2194#endif
2195#endif
2196
2197#define SID_CTX "Python"
2198 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2199 sizeof(SID_CTX));
2200#undef SID_CTX
2201
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002202#ifdef X509_V_FLAG_TRUSTED_FIRST
2203 {
2204 /* Improve trust chain building when cross-signed intermediate
2205 certificates are present. See https://bugs.python.org/issue23476. */
2206 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2207 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2208 }
2209#endif
2210
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002211 return (PyObject *)self;
2212}
2213
2214static int
2215context_traverse(PySSLContext *self, visitproc visit, void *arg)
2216{
2217#ifndef OPENSSL_NO_TLSEXT
2218 Py_VISIT(self->set_hostname);
2219#endif
2220 return 0;
2221}
2222
2223static int
2224context_clear(PySSLContext *self)
2225{
2226#ifndef OPENSSL_NO_TLSEXT
2227 Py_CLEAR(self->set_hostname);
2228#endif
2229 return 0;
2230}
2231
2232static void
2233context_dealloc(PySSLContext *self)
2234{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002235 /* bpo-31095: UnTrack is needed before calling any callbacks */
2236 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002237 context_clear(self);
2238 SSL_CTX_free(self->ctx);
Christian Heimes72ed2332017-09-05 01:11:40 +02002239#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002240 PyMem_FREE(self->npn_protocols);
2241#endif
2242#ifdef HAVE_ALPN
2243 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002244#endif
2245 Py_TYPE(self)->tp_free(self);
2246}
2247
2248static PyObject *
2249set_ciphers(PySSLContext *self, PyObject *args)
2250{
2251 int ret;
2252 const char *cipherlist;
2253
2254 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2255 return NULL;
2256 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2257 if (ret == 0) {
2258 /* Clearing the error queue is necessary on some OpenSSL versions,
2259 otherwise the error will be reported again when another SSL call
2260 is done. */
2261 ERR_clear_error();
2262 PyErr_SetString(PySSLErrorObject,
2263 "No cipher can be selected.");
2264 return NULL;
2265 }
2266 Py_RETURN_NONE;
2267}
2268
Christian Heimes72ed2332017-09-05 01:11:40 +02002269#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002270static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002271do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2272 const unsigned char *server_protocols, unsigned int server_protocols_len,
2273 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002274{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002275 int ret;
2276 if (client_protocols == NULL) {
2277 client_protocols = (unsigned char *)"";
2278 client_protocols_len = 0;
2279 }
2280 if (server_protocols == NULL) {
2281 server_protocols = (unsigned char *)"";
2282 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002283 }
2284
Benjamin Petersonaa707582015-01-23 17:30:26 -05002285 ret = SSL_select_next_proto(out, outlen,
2286 server_protocols, server_protocols_len,
2287 client_protocols, client_protocols_len);
2288 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2289 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002290
2291 return SSL_TLSEXT_ERR_OK;
2292}
Christian Heimes72ed2332017-09-05 01:11:40 +02002293#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002294
Christian Heimes72ed2332017-09-05 01:11:40 +02002295#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002296/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2297static int
2298_advertiseNPN_cb(SSL *s,
2299 const unsigned char **data, unsigned int *len,
2300 void *args)
2301{
2302 PySSLContext *ssl_ctx = (PySSLContext *) args;
2303
2304 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002305 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002306 *len = 0;
2307 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002308 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002309 *len = ssl_ctx->npn_protocols_len;
2310 }
2311
2312 return SSL_TLSEXT_ERR_OK;
2313}
2314/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2315static int
2316_selectNPN_cb(SSL *s,
2317 unsigned char **out, unsigned char *outlen,
2318 const unsigned char *server, unsigned int server_len,
2319 void *args)
2320{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002321 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002322 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002323 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002324}
2325#endif
2326
2327static PyObject *
2328_set_npn_protocols(PySSLContext *self, PyObject *args)
2329{
Christian Heimes72ed2332017-09-05 01:11:40 +02002330#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002331 Py_buffer protos;
2332
2333 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2334 return NULL;
2335
2336 if (self->npn_protocols != NULL) {
2337 PyMem_Free(self->npn_protocols);
2338 }
2339
2340 self->npn_protocols = PyMem_Malloc(protos.len);
2341 if (self->npn_protocols == NULL) {
2342 PyBuffer_Release(&protos);
2343 return PyErr_NoMemory();
2344 }
2345 memcpy(self->npn_protocols, protos.buf, protos.len);
2346 self->npn_protocols_len = (int) protos.len;
2347
2348 /* set both server and client callbacks, because the context can
2349 * be used to create both types of sockets */
2350 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2351 _advertiseNPN_cb,
2352 self);
2353 SSL_CTX_set_next_proto_select_cb(self->ctx,
2354 _selectNPN_cb,
2355 self);
2356
2357 PyBuffer_Release(&protos);
2358 Py_RETURN_NONE;
2359#else
2360 PyErr_SetString(PyExc_NotImplementedError,
2361 "The NPN extension requires OpenSSL 1.0.1 or later.");
2362 return NULL;
2363#endif
2364}
2365
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002366#ifdef HAVE_ALPN
2367static int
2368_selectALPN_cb(SSL *s,
2369 const unsigned char **out, unsigned char *outlen,
2370 const unsigned char *client_protocols, unsigned int client_protocols_len,
2371 void *args)
2372{
2373 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002374 return do_protocol_selection(1, (unsigned char **)out, outlen,
2375 ctx->alpn_protocols, ctx->alpn_protocols_len,
2376 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002377}
2378#endif
2379
2380static PyObject *
2381_set_alpn_protocols(PySSLContext *self, PyObject *args)
2382{
2383#ifdef HAVE_ALPN
2384 Py_buffer protos;
2385
2386 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2387 return NULL;
2388
2389 PyMem_FREE(self->alpn_protocols);
2390 self->alpn_protocols = PyMem_Malloc(protos.len);
2391 if (!self->alpn_protocols)
2392 return PyErr_NoMemory();
2393 memcpy(self->alpn_protocols, protos.buf, protos.len);
2394 self->alpn_protocols_len = protos.len;
2395 PyBuffer_Release(&protos);
2396
2397 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2398 return PyErr_NoMemory();
2399 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2400
2401 PyBuffer_Release(&protos);
2402 Py_RETURN_NONE;
2403#else
2404 PyErr_SetString(PyExc_NotImplementedError,
2405 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2406 return NULL;
2407#endif
2408}
2409
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002410static PyObject *
2411get_verify_mode(PySSLContext *self, void *c)
2412{
2413 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2414 case SSL_VERIFY_NONE:
2415 return PyLong_FromLong(PY_SSL_CERT_NONE);
2416 case SSL_VERIFY_PEER:
2417 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2418 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2419 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2420 }
2421 PyErr_SetString(PySSLErrorObject,
2422 "invalid return value from SSL_CTX_get_verify_mode");
2423 return NULL;
2424}
2425
2426static int
2427set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2428{
2429 int n, mode;
2430 if (!PyArg_Parse(arg, "i", &n))
2431 return -1;
2432 if (n == PY_SSL_CERT_NONE)
2433 mode = SSL_VERIFY_NONE;
2434 else if (n == PY_SSL_CERT_OPTIONAL)
2435 mode = SSL_VERIFY_PEER;
2436 else if (n == PY_SSL_CERT_REQUIRED)
2437 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2438 else {
2439 PyErr_SetString(PyExc_ValueError,
2440 "invalid value for verify_mode");
2441 return -1;
2442 }
2443 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2444 PyErr_SetString(PyExc_ValueError,
2445 "Cannot set verify_mode to CERT_NONE when "
2446 "check_hostname is enabled.");
2447 return -1;
2448 }
2449 SSL_CTX_set_verify(self->ctx, mode, NULL);
2450 return 0;
2451}
2452
2453#ifdef HAVE_OPENSSL_VERIFY_PARAM
2454static PyObject *
2455get_verify_flags(PySSLContext *self, void *c)
2456{
2457 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002458 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002459 unsigned long flags;
2460
2461 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002462 param = X509_STORE_get0_param(store);
2463 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002464 return PyLong_FromUnsignedLong(flags);
2465}
2466
2467static int
2468set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2469{
2470 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002471 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002472 unsigned long new_flags, flags, set, clear;
2473
2474 if (!PyArg_Parse(arg, "k", &new_flags))
2475 return -1;
2476 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002477 param = X509_STORE_get0_param(store);
2478 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002479 clear = flags & ~new_flags;
2480 set = ~flags & new_flags;
2481 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002482 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002483 _setSSLError(NULL, 0, __FILE__, __LINE__);
2484 return -1;
2485 }
2486 }
2487 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002488 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002489 _setSSLError(NULL, 0, __FILE__, __LINE__);
2490 return -1;
2491 }
2492 }
2493 return 0;
2494}
2495#endif
2496
2497static PyObject *
2498get_options(PySSLContext *self, void *c)
2499{
2500 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2501}
2502
2503static int
2504set_options(PySSLContext *self, PyObject *arg, void *c)
2505{
2506 long new_opts, opts, set, clear;
2507 if (!PyArg_Parse(arg, "l", &new_opts))
2508 return -1;
2509 opts = SSL_CTX_get_options(self->ctx);
2510 clear = opts & ~new_opts;
2511 set = ~opts & new_opts;
2512 if (clear) {
2513#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2514 SSL_CTX_clear_options(self->ctx, clear);
2515#else
2516 PyErr_SetString(PyExc_ValueError,
2517 "can't clear options before OpenSSL 0.9.8m");
2518 return -1;
2519#endif
2520 }
2521 if (set)
2522 SSL_CTX_set_options(self->ctx, set);
2523 return 0;
2524}
2525
2526static PyObject *
2527get_check_hostname(PySSLContext *self, void *c)
2528{
2529 return PyBool_FromLong(self->check_hostname);
2530}
2531
2532static int
2533set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2534{
2535 PyObject *py_check_hostname;
2536 int check_hostname;
2537 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2538 return -1;
2539
2540 check_hostname = PyObject_IsTrue(py_check_hostname);
2541 if (check_hostname < 0)
2542 return -1;
2543 if (check_hostname &&
2544 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2545 PyErr_SetString(PyExc_ValueError,
2546 "check_hostname needs a SSL context with either "
2547 "CERT_OPTIONAL or CERT_REQUIRED");
2548 return -1;
2549 }
2550 self->check_hostname = check_hostname;
2551 return 0;
2552}
2553
2554
2555typedef struct {
2556 PyThreadState *thread_state;
2557 PyObject *callable;
2558 char *password;
2559 int size;
2560 int error;
2561} _PySSLPasswordInfo;
2562
2563static int
2564_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2565 const char *bad_type_error)
2566{
2567 /* Set the password and size fields of a _PySSLPasswordInfo struct
2568 from a unicode, bytes, or byte array object.
2569 The password field will be dynamically allocated and must be freed
2570 by the caller */
2571 PyObject *password_bytes = NULL;
2572 const char *data = NULL;
2573 Py_ssize_t size;
2574
2575 if (PyUnicode_Check(password)) {
2576 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2577 if (!password_bytes) {
2578 goto error;
2579 }
2580 data = PyBytes_AS_STRING(password_bytes);
2581 size = PyBytes_GET_SIZE(password_bytes);
2582 } else if (PyBytes_Check(password)) {
2583 data = PyBytes_AS_STRING(password);
2584 size = PyBytes_GET_SIZE(password);
2585 } else if (PyByteArray_Check(password)) {
2586 data = PyByteArray_AS_STRING(password);
2587 size = PyByteArray_GET_SIZE(password);
2588 } else {
2589 PyErr_SetString(PyExc_TypeError, bad_type_error);
2590 goto error;
2591 }
2592
2593 if (size > (Py_ssize_t)INT_MAX) {
2594 PyErr_Format(PyExc_ValueError,
2595 "password cannot be longer than %d bytes", INT_MAX);
2596 goto error;
2597 }
2598
2599 PyMem_Free(pw_info->password);
2600 pw_info->password = PyMem_Malloc(size);
2601 if (!pw_info->password) {
2602 PyErr_SetString(PyExc_MemoryError,
2603 "unable to allocate password buffer");
2604 goto error;
2605 }
2606 memcpy(pw_info->password, data, size);
2607 pw_info->size = (int)size;
2608
2609 Py_XDECREF(password_bytes);
2610 return 1;
2611
2612error:
2613 Py_XDECREF(password_bytes);
2614 return 0;
2615}
2616
2617static int
2618_password_callback(char *buf, int size, int rwflag, void *userdata)
2619{
2620 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2621 PyObject *fn_ret = NULL;
2622
2623 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2624
2625 if (pw_info->callable) {
2626 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2627 if (!fn_ret) {
2628 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2629 core python API, so we could use it to add a frame here */
2630 goto error;
2631 }
2632
2633 if (!_pwinfo_set(pw_info, fn_ret,
2634 "password callback must return a string")) {
2635 goto error;
2636 }
2637 Py_CLEAR(fn_ret);
2638 }
2639
2640 if (pw_info->size > size) {
2641 PyErr_Format(PyExc_ValueError,
2642 "password cannot be longer than %d bytes", size);
2643 goto error;
2644 }
2645
2646 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2647 memcpy(buf, pw_info->password, pw_info->size);
2648 return pw_info->size;
2649
2650error:
2651 Py_XDECREF(fn_ret);
2652 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2653 pw_info->error = 1;
2654 return -1;
2655}
2656
2657static PyObject *
2658load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2659{
2660 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002661 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2662 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002663 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2664 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002665 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2666 int r;
2667
2668 errno = 0;
2669 ERR_clear_error();
2670 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002671 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002672 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002673 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002674 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002675
2676 if (keyfile && keyfile != Py_None) {
2677 if (PyString_Check(keyfile)) {
2678 Py_INCREF(keyfile);
2679 keyfile_bytes = keyfile;
2680 } else {
2681 PyObject *u = PyUnicode_FromObject(keyfile);
2682 if (!u)
2683 goto error;
2684 keyfile_bytes = PyUnicode_AsEncodedString(
2685 u, Py_FileSystemDefaultEncoding, NULL);
2686 Py_DECREF(u);
2687 if (!keyfile_bytes)
2688 goto error;
2689 }
2690 }
2691
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002692 if (password && password != Py_None) {
2693 if (PyCallable_Check(password)) {
2694 pw_info.callable = password;
2695 } else if (!_pwinfo_set(&pw_info, password,
2696 "password should be a string or callable")) {
2697 goto error;
2698 }
2699 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2700 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2701 }
2702 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2703 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2704 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2705 if (r != 1) {
2706 if (pw_info.error) {
2707 ERR_clear_error();
2708 /* the password callback has already set the error information */
2709 }
2710 else if (errno != 0) {
2711 ERR_clear_error();
2712 PyErr_SetFromErrno(PyExc_IOError);
2713 }
2714 else {
2715 _setSSLError(NULL, 0, __FILE__, __LINE__);
2716 }
2717 goto error;
2718 }
2719 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2720 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002721 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002722 SSL_FILETYPE_PEM);
2723 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2724 if (r != 1) {
2725 if (pw_info.error) {
2726 ERR_clear_error();
2727 /* the password callback has already set the error information */
2728 }
2729 else if (errno != 0) {
2730 ERR_clear_error();
2731 PyErr_SetFromErrno(PyExc_IOError);
2732 }
2733 else {
2734 _setSSLError(NULL, 0, __FILE__, __LINE__);
2735 }
2736 goto error;
2737 }
2738 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2739 r = SSL_CTX_check_private_key(self->ctx);
2740 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2741 if (r != 1) {
2742 _setSSLError(NULL, 0, __FILE__, __LINE__);
2743 goto error;
2744 }
2745 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2746 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002747 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002748 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002749 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002750 Py_RETURN_NONE;
2751
2752error:
2753 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2754 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002755 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002756 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002757 PyMem_Free(certfile_bytes);
2758 return NULL;
2759}
2760
2761/* internal helper function, returns -1 on error
2762 */
2763static int
2764_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2765 int filetype)
2766{
2767 BIO *biobuf = NULL;
2768 X509_STORE *store;
2769 int retval = 0, err, loaded = 0;
2770
2771 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2772
2773 if (len <= 0) {
2774 PyErr_SetString(PyExc_ValueError,
2775 "Empty certificate data");
2776 return -1;
2777 } else if (len > INT_MAX) {
2778 PyErr_SetString(PyExc_OverflowError,
2779 "Certificate data is too long.");
2780 return -1;
2781 }
2782
2783 biobuf = BIO_new_mem_buf(data, (int)len);
2784 if (biobuf == NULL) {
2785 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2786 return -1;
2787 }
2788
2789 store = SSL_CTX_get_cert_store(self->ctx);
2790 assert(store != NULL);
2791
2792 while (1) {
2793 X509 *cert = NULL;
2794 int r;
2795
2796 if (filetype == SSL_FILETYPE_ASN1) {
2797 cert = d2i_X509_bio(biobuf, NULL);
2798 } else {
2799 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002800 SSL_CTX_get_default_passwd_cb(self->ctx),
2801 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2802 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002803 }
2804 if (cert == NULL) {
2805 break;
2806 }
2807 r = X509_STORE_add_cert(store, cert);
2808 X509_free(cert);
2809 if (!r) {
2810 err = ERR_peek_last_error();
2811 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2812 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2813 /* cert already in hash table, not an error */
2814 ERR_clear_error();
2815 } else {
2816 break;
2817 }
2818 }
2819 loaded++;
2820 }
2821
2822 err = ERR_peek_last_error();
2823 if ((filetype == SSL_FILETYPE_ASN1) &&
2824 (loaded > 0) &&
2825 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2826 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2827 /* EOF ASN1 file, not an error */
2828 ERR_clear_error();
2829 retval = 0;
2830 } else if ((filetype == SSL_FILETYPE_PEM) &&
2831 (loaded > 0) &&
2832 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2833 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2834 /* EOF PEM file, not an error */
2835 ERR_clear_error();
2836 retval = 0;
2837 } else {
2838 _setSSLError(NULL, 0, __FILE__, __LINE__);
2839 retval = -1;
2840 }
2841
2842 BIO_free(biobuf);
2843 return retval;
2844}
2845
2846
2847static PyObject *
2848load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2849{
2850 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2851 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2852 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2853 const char *cafile_buf = NULL, *capath_buf = NULL;
2854 int r = 0, ok = 1;
2855
2856 errno = 0;
2857 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2858 "|OOO:load_verify_locations", kwlist,
2859 &cafile, &capath, &cadata))
2860 return NULL;
2861
2862 if (cafile == Py_None)
2863 cafile = NULL;
2864 if (capath == Py_None)
2865 capath = NULL;
2866 if (cadata == Py_None)
2867 cadata = NULL;
2868
2869 if (cafile == NULL && capath == NULL && cadata == NULL) {
2870 PyErr_SetString(PyExc_TypeError,
2871 "cafile, capath and cadata cannot be all omitted");
2872 goto error;
2873 }
2874
2875 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002876 if (PyString_Check(cafile)) {
2877 Py_INCREF(cafile);
2878 cafile_bytes = cafile;
2879 } else {
2880 PyObject *u = PyUnicode_FromObject(cafile);
2881 if (!u)
2882 goto error;
2883 cafile_bytes = PyUnicode_AsEncodedString(
2884 u, Py_FileSystemDefaultEncoding, NULL);
2885 Py_DECREF(u);
2886 if (!cafile_bytes)
2887 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002888 }
2889 }
2890 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002891 if (PyString_Check(capath)) {
2892 Py_INCREF(capath);
2893 capath_bytes = capath;
2894 } else {
2895 PyObject *u = PyUnicode_FromObject(capath);
2896 if (!u)
2897 goto error;
2898 capath_bytes = PyUnicode_AsEncodedString(
2899 u, Py_FileSystemDefaultEncoding, NULL);
2900 Py_DECREF(u);
2901 if (!capath_bytes)
2902 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002903 }
2904 }
2905
2906 /* validata cadata type and load cadata */
2907 if (cadata) {
2908 Py_buffer buf;
2909 PyObject *cadata_ascii = NULL;
2910
2911 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2912 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2913 PyBuffer_Release(&buf);
2914 PyErr_SetString(PyExc_TypeError,
2915 "cadata should be a contiguous buffer with "
2916 "a single dimension");
2917 goto error;
2918 }
2919 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2920 PyBuffer_Release(&buf);
2921 if (r == -1) {
2922 goto error;
2923 }
2924 } else {
2925 PyErr_Clear();
2926 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2927 if (cadata_ascii == NULL) {
2928 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002929 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002930 "bytes-like object");
2931 goto error;
2932 }
2933 r = _add_ca_certs(self,
2934 PyBytes_AS_STRING(cadata_ascii),
2935 PyBytes_GET_SIZE(cadata_ascii),
2936 SSL_FILETYPE_PEM);
2937 Py_DECREF(cadata_ascii);
2938 if (r == -1) {
2939 goto error;
2940 }
2941 }
2942 }
2943
2944 /* load cafile or capath */
2945 if (cafile_bytes || capath_bytes) {
2946 if (cafile)
2947 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2948 if (capath)
2949 capath_buf = PyBytes_AS_STRING(capath_bytes);
2950 PySSL_BEGIN_ALLOW_THREADS
2951 r = SSL_CTX_load_verify_locations(
2952 self->ctx,
2953 cafile_buf,
2954 capath_buf);
2955 PySSL_END_ALLOW_THREADS
2956 if (r != 1) {
2957 ok = 0;
2958 if (errno != 0) {
2959 ERR_clear_error();
2960 PyErr_SetFromErrno(PyExc_IOError);
2961 }
2962 else {
2963 _setSSLError(NULL, 0, __FILE__, __LINE__);
2964 }
2965 goto error;
2966 }
2967 }
2968 goto end;
2969
2970 error:
2971 ok = 0;
2972 end:
2973 Py_XDECREF(cafile_bytes);
2974 Py_XDECREF(capath_bytes);
2975 if (ok) {
2976 Py_RETURN_NONE;
2977 } else {
2978 return NULL;
2979 }
2980}
2981
2982static PyObject *
2983load_dh_params(PySSLContext *self, PyObject *filepath)
2984{
2985 BIO *bio;
2986 DH *dh;
2987 char *path = PyBytes_AsString(filepath);
2988 if (!path) {
2989 return NULL;
2990 }
2991
2992 bio = BIO_new_file(path, "r");
2993 if (bio == NULL) {
2994 ERR_clear_error();
2995 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2996 return NULL;
2997 }
2998 errno = 0;
2999 PySSL_BEGIN_ALLOW_THREADS
3000 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3001 BIO_free(bio);
3002 PySSL_END_ALLOW_THREADS
3003 if (dh == NULL) {
3004 if (errno != 0) {
3005 ERR_clear_error();
3006 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3007 }
3008 else {
3009 _setSSLError(NULL, 0, __FILE__, __LINE__);
3010 }
3011 return NULL;
3012 }
3013 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3014 _setSSLError(NULL, 0, __FILE__, __LINE__);
3015 DH_free(dh);
3016 Py_RETURN_NONE;
3017}
3018
3019static PyObject *
3020context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3021{
3022 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3023 PySocketSockObject *sock;
3024 int server_side = 0;
3025 char *hostname = NULL;
3026 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3027
3028 /* server_hostname is either None (or absent), or to be encoded
3029 using the idna encoding. */
3030 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3031 PySocketModule.Sock_Type,
3032 &sock, &server_side,
3033 Py_TYPE(Py_None), &hostname_obj,
3034 &ssl_sock)) {
3035 PyErr_Clear();
3036 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3037 PySocketModule.Sock_Type,
3038 &sock, &server_side,
3039 "idna", &hostname, &ssl_sock))
3040 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003041 }
3042
3043 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3044 hostname, ssl_sock);
3045 if (hostname != NULL)
3046 PyMem_Free(hostname);
3047 return res;
3048}
3049
3050static PyObject *
3051session_stats(PySSLContext *self, PyObject *unused)
3052{
3053 int r;
3054 PyObject *value, *stats = PyDict_New();
3055 if (!stats)
3056 return NULL;
3057
3058#define ADD_STATS(SSL_NAME, KEY_NAME) \
3059 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3060 if (value == NULL) \
3061 goto error; \
3062 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3063 Py_DECREF(value); \
3064 if (r < 0) \
3065 goto error;
3066
3067 ADD_STATS(number, "number");
3068 ADD_STATS(connect, "connect");
3069 ADD_STATS(connect_good, "connect_good");
3070 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3071 ADD_STATS(accept, "accept");
3072 ADD_STATS(accept_good, "accept_good");
3073 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3074 ADD_STATS(accept, "accept");
3075 ADD_STATS(hits, "hits");
3076 ADD_STATS(misses, "misses");
3077 ADD_STATS(timeouts, "timeouts");
3078 ADD_STATS(cache_full, "cache_full");
3079
3080#undef ADD_STATS
3081
3082 return stats;
3083
3084error:
3085 Py_DECREF(stats);
3086 return NULL;
3087}
3088
3089static PyObject *
3090set_default_verify_paths(PySSLContext *self, PyObject *unused)
3091{
3092 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3093 _setSSLError(NULL, 0, __FILE__, __LINE__);
3094 return NULL;
3095 }
3096 Py_RETURN_NONE;
3097}
3098
3099#ifndef OPENSSL_NO_ECDH
3100static PyObject *
3101set_ecdh_curve(PySSLContext *self, PyObject *name)
3102{
3103 char *name_bytes;
3104 int nid;
3105 EC_KEY *key;
3106
3107 name_bytes = PyBytes_AsString(name);
3108 if (!name_bytes) {
3109 return NULL;
3110 }
3111 nid = OBJ_sn2nid(name_bytes);
3112 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003113 PyObject *r = PyObject_Repr(name);
3114 if (!r)
3115 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003116 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003117 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3118 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003119 return NULL;
3120 }
3121 key = EC_KEY_new_by_curve_name(nid);
3122 if (key == NULL) {
3123 _setSSLError(NULL, 0, __FILE__, __LINE__);
3124 return NULL;
3125 }
3126 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3127 EC_KEY_free(key);
3128 Py_RETURN_NONE;
3129}
3130#endif
3131
3132#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3133static int
3134_servername_callback(SSL *s, int *al, void *args)
3135{
3136 int ret;
3137 PySSLContext *ssl_ctx = (PySSLContext *) args;
3138 PySSLSocket *ssl;
3139 PyObject *servername_o;
3140 PyObject *servername_idna;
3141 PyObject *result;
3142 /* The high-level ssl.SSLSocket object */
3143 PyObject *ssl_socket;
3144 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3145#ifdef WITH_THREAD
3146 PyGILState_STATE gstate = PyGILState_Ensure();
3147#endif
3148
3149 if (ssl_ctx->set_hostname == NULL) {
3150 /* remove race condition in this the call back while if removing the
3151 * callback is in progress */
3152#ifdef WITH_THREAD
3153 PyGILState_Release(gstate);
3154#endif
3155 return SSL_TLSEXT_ERR_OK;
3156 }
3157
3158 ssl = SSL_get_app_data(s);
3159 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003160 if (ssl->ssl_sock == NULL) {
3161 ssl_socket = Py_None;
3162 } else {
3163 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3164 Py_INCREF(ssl_socket);
3165 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003166 if (ssl_socket == Py_None) {
3167 goto error;
3168 }
3169
3170 if (servername == NULL) {
3171 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3172 Py_None, ssl_ctx, NULL);
3173 }
3174 else {
3175 servername_o = PyBytes_FromString(servername);
3176 if (servername_o == NULL) {
3177 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3178 goto error;
3179 }
3180 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3181 if (servername_idna == NULL) {
3182 PyErr_WriteUnraisable(servername_o);
3183 Py_DECREF(servername_o);
3184 goto error;
3185 }
3186 Py_DECREF(servername_o);
3187 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3188 servername_idna, ssl_ctx, NULL);
3189 Py_DECREF(servername_idna);
3190 }
3191 Py_DECREF(ssl_socket);
3192
3193 if (result == NULL) {
3194 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3195 *al = SSL_AD_HANDSHAKE_FAILURE;
3196 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3197 }
3198 else {
3199 if (result != Py_None) {
3200 *al = (int) PyLong_AsLong(result);
3201 if (PyErr_Occurred()) {
3202 PyErr_WriteUnraisable(result);
3203 *al = SSL_AD_INTERNAL_ERROR;
3204 }
3205 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3206 }
3207 else {
3208 ret = SSL_TLSEXT_ERR_OK;
3209 }
3210 Py_DECREF(result);
3211 }
3212
3213#ifdef WITH_THREAD
3214 PyGILState_Release(gstate);
3215#endif
3216 return ret;
3217
3218error:
3219 Py_DECREF(ssl_socket);
3220 *al = SSL_AD_INTERNAL_ERROR;
3221 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3222#ifdef WITH_THREAD
3223 PyGILState_Release(gstate);
3224#endif
3225 return ret;
3226}
3227#endif
3228
3229PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3230"set_servername_callback(method)\n\
3231\n\
3232This sets a callback that will be called when a server name is provided by\n\
3233the SSL/TLS client in the SNI extension.\n\
3234\n\
3235If the argument is None then the callback is disabled. The method is called\n\
3236with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3237See RFC 6066 for details of the SNI extension.");
3238
3239static PyObject *
3240set_servername_callback(PySSLContext *self, PyObject *args)
3241{
3242#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3243 PyObject *cb;
3244
3245 if (!PyArg_ParseTuple(args, "O", &cb))
3246 return NULL;
3247
3248 Py_CLEAR(self->set_hostname);
3249 if (cb == Py_None) {
3250 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3251 }
3252 else {
3253 if (!PyCallable_Check(cb)) {
3254 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3255 PyErr_SetString(PyExc_TypeError,
3256 "not a callable object");
3257 return NULL;
3258 }
3259 Py_INCREF(cb);
3260 self->set_hostname = cb;
3261 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3262 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3263 }
3264 Py_RETURN_NONE;
3265#else
3266 PyErr_SetString(PyExc_NotImplementedError,
3267 "The TLS extension servername callback, "
3268 "SSL_CTX_set_tlsext_servername_callback, "
3269 "is not in the current OpenSSL library.");
3270 return NULL;
3271#endif
3272}
3273
3274PyDoc_STRVAR(PySSL_get_stats_doc,
3275"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3276\n\
3277Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3278CA extension and certificate revocation lists inside the context's cert\n\
3279store.\n\
3280NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3281been used at least once.");
3282
3283static PyObject *
3284cert_store_stats(PySSLContext *self)
3285{
3286 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003287 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003288 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003289 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003290
3291 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003292 objs = X509_STORE_get0_objects(store);
3293 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3294 obj = sk_X509_OBJECT_value(objs, i);
3295 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003296 case X509_LU_X509:
3297 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003298 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003299 ca++;
3300 }
3301 break;
3302 case X509_LU_CRL:
3303 crl++;
3304 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003305 default:
3306 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3307 * As far as I can tell they are internal states and never
3308 * stored in a cert store */
3309 break;
3310 }
3311 }
3312 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3313 "x509_ca", ca);
3314}
3315
3316PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3317"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3318\n\
3319Returns a list of dicts with information of loaded CA certs. If the\n\
3320optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3321NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3322been used at least once.");
3323
3324static PyObject *
3325get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3326{
3327 char *kwlist[] = {"binary_form", NULL};
3328 X509_STORE *store;
3329 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003330 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003331 int i;
3332 int binary_mode = 0;
3333
3334 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3335 kwlist, &py_binary_mode)) {
3336 return NULL;
3337 }
3338 binary_mode = PyObject_IsTrue(py_binary_mode);
3339 if (binary_mode < 0) {
3340 return NULL;
3341 }
3342
3343 if ((rlist = PyList_New(0)) == NULL) {
3344 return NULL;
3345 }
3346
3347 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003348 objs = X509_STORE_get0_objects(store);
3349 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003350 X509_OBJECT *obj;
3351 X509 *cert;
3352
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003353 obj = sk_X509_OBJECT_value(objs, i);
3354 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003355 /* not a x509 cert */
3356 continue;
3357 }
3358 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003359 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003360 if (!X509_check_ca(cert)) {
3361 continue;
3362 }
3363 if (binary_mode) {
3364 ci = _certificate_to_der(cert);
3365 } else {
3366 ci = _decode_certificate(cert);
3367 }
3368 if (ci == NULL) {
3369 goto error;
3370 }
3371 if (PyList_Append(rlist, ci) == -1) {
3372 goto error;
3373 }
3374 Py_CLEAR(ci);
3375 }
3376 return rlist;
3377
3378 error:
3379 Py_XDECREF(ci);
3380 Py_XDECREF(rlist);
3381 return NULL;
3382}
3383
3384
3385static PyGetSetDef context_getsetlist[] = {
3386 {"check_hostname", (getter) get_check_hostname,
3387 (setter) set_check_hostname, NULL},
3388 {"options", (getter) get_options,
3389 (setter) set_options, NULL},
3390#ifdef HAVE_OPENSSL_VERIFY_PARAM
3391 {"verify_flags", (getter) get_verify_flags,
3392 (setter) set_verify_flags, NULL},
3393#endif
3394 {"verify_mode", (getter) get_verify_mode,
3395 (setter) set_verify_mode, NULL},
3396 {NULL}, /* sentinel */
3397};
3398
3399static struct PyMethodDef context_methods[] = {
3400 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3401 METH_VARARGS | METH_KEYWORDS, NULL},
3402 {"set_ciphers", (PyCFunction) set_ciphers,
3403 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003404 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3405 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003406 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3407 METH_VARARGS, NULL},
3408 {"load_cert_chain", (PyCFunction) load_cert_chain,
3409 METH_VARARGS | METH_KEYWORDS, NULL},
3410 {"load_dh_params", (PyCFunction) load_dh_params,
3411 METH_O, NULL},
3412 {"load_verify_locations", (PyCFunction) load_verify_locations,
3413 METH_VARARGS | METH_KEYWORDS, NULL},
3414 {"session_stats", (PyCFunction) session_stats,
3415 METH_NOARGS, NULL},
3416 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3417 METH_NOARGS, NULL},
3418#ifndef OPENSSL_NO_ECDH
3419 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3420 METH_O, NULL},
3421#endif
3422 {"set_servername_callback", (PyCFunction) set_servername_callback,
3423 METH_VARARGS, PySSL_set_servername_callback_doc},
3424 {"cert_store_stats", (PyCFunction) cert_store_stats,
3425 METH_NOARGS, PySSL_get_stats_doc},
3426 {"get_ca_certs", (PyCFunction) get_ca_certs,
3427 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3428 {NULL, NULL} /* sentinel */
3429};
3430
3431static PyTypeObject PySSLContext_Type = {
3432 PyVarObject_HEAD_INIT(NULL, 0)
3433 "_ssl._SSLContext", /*tp_name*/
3434 sizeof(PySSLContext), /*tp_basicsize*/
3435 0, /*tp_itemsize*/
3436 (destructor)context_dealloc, /*tp_dealloc*/
3437 0, /*tp_print*/
3438 0, /*tp_getattr*/
3439 0, /*tp_setattr*/
3440 0, /*tp_reserved*/
3441 0, /*tp_repr*/
3442 0, /*tp_as_number*/
3443 0, /*tp_as_sequence*/
3444 0, /*tp_as_mapping*/
3445 0, /*tp_hash*/
3446 0, /*tp_call*/
3447 0, /*tp_str*/
3448 0, /*tp_getattro*/
3449 0, /*tp_setattro*/
3450 0, /*tp_as_buffer*/
3451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3452 0, /*tp_doc*/
3453 (traverseproc) context_traverse, /*tp_traverse*/
3454 (inquiry) context_clear, /*tp_clear*/
3455 0, /*tp_richcompare*/
3456 0, /*tp_weaklistoffset*/
3457 0, /*tp_iter*/
3458 0, /*tp_iternext*/
3459 context_methods, /*tp_methods*/
3460 0, /*tp_members*/
3461 context_getsetlist, /*tp_getset*/
3462 0, /*tp_base*/
3463 0, /*tp_dict*/
3464 0, /*tp_descr_get*/
3465 0, /*tp_descr_set*/
3466 0, /*tp_dictoffset*/
3467 0, /*tp_init*/
3468 0, /*tp_alloc*/
3469 context_new, /*tp_new*/
3470};
3471
3472
3473
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003474#ifdef HAVE_OPENSSL_RAND
3475
3476/* helper routines for seeding the SSL PRNG */
3477static PyObject *
3478PySSL_RAND_add(PyObject *self, PyObject *args)
3479{
3480 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003481 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003482 double entropy;
3483
3484 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003485 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003486 do {
3487 if (len >= INT_MAX) {
3488 written = INT_MAX;
3489 } else {
3490 written = len;
3491 }
3492 RAND_add(buf, (int)written, entropy);
3493 buf += written;
3494 len -= written;
3495 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003496 Py_INCREF(Py_None);
3497 return Py_None;
3498}
3499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003500PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003501"RAND_add(string, entropy)\n\
3502\n\
3503Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003504bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003505
3506static PyObject *
3507PySSL_RAND_status(PyObject *self)
3508{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003509 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003510}
3511
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003512PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003513"RAND_status() -> 0 or 1\n\
3514\n\
3515Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3516It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003517using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003518
Victor Stinner7c906672015-01-06 13:53:37 +01003519#endif /* HAVE_OPENSSL_RAND */
3520
3521
Benjamin Peterson42e10292016-07-07 00:02:31 -07003522#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003523
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003524static PyObject *
3525PySSL_RAND_egd(PyObject *self, PyObject *arg)
3526{
3527 int bytes;
3528
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003529 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003530 return PyErr_Format(PyExc_TypeError,
3531 "RAND_egd() expected string, found %s",
3532 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003533 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003534 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003535 PyErr_SetString(PySSLErrorObject,
3536 "EGD connection failed or EGD did not return "
3537 "enough data to seed the PRNG");
3538 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003539 }
3540 return PyInt_FromLong(bytes);
3541}
3542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003543PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003544"RAND_egd(path) -> bytes\n\
3545\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003546Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3547Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003548fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003549
Benjamin Peterson42e10292016-07-07 00:02:31 -07003550#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003551
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003552
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003553PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3554"get_default_verify_paths() -> tuple\n\
3555\n\
3556Return search paths and environment vars that are used by SSLContext's\n\
3557set_default_verify_paths() to load default CAs. The values are\n\
3558'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3559
3560static PyObject *
3561PySSL_get_default_verify_paths(PyObject *self)
3562{
3563 PyObject *ofile_env = NULL;
3564 PyObject *ofile = NULL;
3565 PyObject *odir_env = NULL;
3566 PyObject *odir = NULL;
3567
Benjamin Peterson65192c12015-07-18 10:59:13 -07003568#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003569 const char *tmp = (info); \
3570 target = NULL; \
3571 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3572 else { target = PyBytes_FromString(tmp); } \
3573 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003574 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003575
Benjamin Peterson65192c12015-07-18 10:59:13 -07003576 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3577 CONVERT(X509_get_default_cert_file(), ofile);
3578 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3579 CONVERT(X509_get_default_cert_dir(), odir);
3580#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003581
3582 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3583
3584 error:
3585 Py_XDECREF(ofile_env);
3586 Py_XDECREF(ofile);
3587 Py_XDECREF(odir_env);
3588 Py_XDECREF(odir);
3589 return NULL;
3590}
3591
3592static PyObject*
3593asn1obj2py(ASN1_OBJECT *obj)
3594{
3595 int nid;
3596 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003597
3598 nid = OBJ_obj2nid(obj);
3599 if (nid == NID_undef) {
3600 PyErr_Format(PyExc_ValueError, "Unknown object");
3601 return NULL;
3602 }
3603 sn = OBJ_nid2sn(nid);
3604 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003605 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003606}
3607
3608PyDoc_STRVAR(PySSL_txt2obj_doc,
3609"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3610\n\
3611Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3612objects are looked up by OID. With name=True short and long name are also\n\
3613matched.");
3614
3615static PyObject*
3616PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3617{
3618 char *kwlist[] = {"txt", "name", NULL};
3619 PyObject *result = NULL;
3620 char *txt;
3621 PyObject *pyname = Py_None;
3622 int name = 0;
3623 ASN1_OBJECT *obj;
3624
3625 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3626 kwlist, &txt, &pyname)) {
3627 return NULL;
3628 }
3629 name = PyObject_IsTrue(pyname);
3630 if (name < 0)
3631 return NULL;
3632 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3633 if (obj == NULL) {
3634 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3635 return NULL;
3636 }
3637 result = asn1obj2py(obj);
3638 ASN1_OBJECT_free(obj);
3639 return result;
3640}
3641
3642PyDoc_STRVAR(PySSL_nid2obj_doc,
3643"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3644\n\
3645Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3646
3647static PyObject*
3648PySSL_nid2obj(PyObject *self, PyObject *args)
3649{
3650 PyObject *result = NULL;
3651 int nid;
3652 ASN1_OBJECT *obj;
3653
3654 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3655 return NULL;
3656 }
3657 if (nid < NID_undef) {
3658 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3659 return NULL;
3660 }
3661 obj = OBJ_nid2obj(nid);
3662 if (obj == NULL) {
3663 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3664 return NULL;
3665 }
3666 result = asn1obj2py(obj);
3667 ASN1_OBJECT_free(obj);
3668 return result;
3669}
3670
3671#ifdef _MSC_VER
3672
3673static PyObject*
3674certEncodingType(DWORD encodingType)
3675{
3676 static PyObject *x509_asn = NULL;
3677 static PyObject *pkcs_7_asn = NULL;
3678
3679 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003680 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003681 if (x509_asn == NULL)
3682 return NULL;
3683 }
3684 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003685 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003686 if (pkcs_7_asn == NULL)
3687 return NULL;
3688 }
3689 switch(encodingType) {
3690 case X509_ASN_ENCODING:
3691 Py_INCREF(x509_asn);
3692 return x509_asn;
3693 case PKCS_7_ASN_ENCODING:
3694 Py_INCREF(pkcs_7_asn);
3695 return pkcs_7_asn;
3696 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003697 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003698 }
3699}
3700
3701static PyObject*
3702parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3703{
3704 CERT_ENHKEY_USAGE *usage;
3705 DWORD size, error, i;
3706 PyObject *retval;
3707
3708 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3709 error = GetLastError();
3710 if (error == CRYPT_E_NOT_FOUND) {
3711 Py_RETURN_TRUE;
3712 }
3713 return PyErr_SetFromWindowsErr(error);
3714 }
3715
3716 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3717 if (usage == NULL) {
3718 return PyErr_NoMemory();
3719 }
3720
3721 /* Now get the actual enhanced usage property */
3722 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3723 PyMem_Free(usage);
3724 error = GetLastError();
3725 if (error == CRYPT_E_NOT_FOUND) {
3726 Py_RETURN_TRUE;
3727 }
3728 return PyErr_SetFromWindowsErr(error);
3729 }
3730 retval = PySet_New(NULL);
3731 if (retval == NULL) {
3732 goto error;
3733 }
3734 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3735 if (usage->rgpszUsageIdentifier[i]) {
3736 PyObject *oid;
3737 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003738 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003739 if (oid == NULL) {
3740 Py_CLEAR(retval);
3741 goto error;
3742 }
3743 err = PySet_Add(retval, oid);
3744 Py_DECREF(oid);
3745 if (err == -1) {
3746 Py_CLEAR(retval);
3747 goto error;
3748 }
3749 }
3750 }
3751 error:
3752 PyMem_Free(usage);
3753 return retval;
3754}
3755
3756PyDoc_STRVAR(PySSL_enum_certificates_doc,
3757"enum_certificates(store_name) -> []\n\
3758\n\
3759Retrieve certificates from Windows' cert store. store_name may be one of\n\
3760'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3761The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3762encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3763PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3764boolean True.");
3765
3766static PyObject *
3767PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3768{
3769 char *kwlist[] = {"store_name", NULL};
3770 char *store_name;
3771 HCERTSTORE hStore = NULL;
3772 PCCERT_CONTEXT pCertCtx = NULL;
3773 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3774 PyObject *result = NULL;
3775
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003776 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003777 kwlist, &store_name)) {
3778 return NULL;
3779 }
3780 result = PyList_New(0);
3781 if (result == NULL) {
3782 return NULL;
3783 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003784 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3785 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3786 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003787 if (hStore == NULL) {
3788 Py_DECREF(result);
3789 return PyErr_SetFromWindowsErr(GetLastError());
3790 }
3791
3792 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3793 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3794 pCertCtx->cbCertEncoded);
3795 if (!cert) {
3796 Py_CLEAR(result);
3797 break;
3798 }
3799 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3800 Py_CLEAR(result);
3801 break;
3802 }
3803 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3804 if (keyusage == Py_True) {
3805 Py_DECREF(keyusage);
3806 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3807 }
3808 if (keyusage == NULL) {
3809 Py_CLEAR(result);
3810 break;
3811 }
3812 if ((tup = PyTuple_New(3)) == NULL) {
3813 Py_CLEAR(result);
3814 break;
3815 }
3816 PyTuple_SET_ITEM(tup, 0, cert);
3817 cert = NULL;
3818 PyTuple_SET_ITEM(tup, 1, enc);
3819 enc = NULL;
3820 PyTuple_SET_ITEM(tup, 2, keyusage);
3821 keyusage = NULL;
3822 if (PyList_Append(result, tup) < 0) {
3823 Py_CLEAR(result);
3824 break;
3825 }
3826 Py_CLEAR(tup);
3827 }
3828 if (pCertCtx) {
3829 /* loop ended with an error, need to clean up context manually */
3830 CertFreeCertificateContext(pCertCtx);
3831 }
3832
3833 /* In error cases cert, enc and tup may not be NULL */
3834 Py_XDECREF(cert);
3835 Py_XDECREF(enc);
3836 Py_XDECREF(keyusage);
3837 Py_XDECREF(tup);
3838
3839 if (!CertCloseStore(hStore, 0)) {
3840 /* This error case might shadow another exception.*/
3841 Py_XDECREF(result);
3842 return PyErr_SetFromWindowsErr(GetLastError());
3843 }
3844 return result;
3845}
3846
3847PyDoc_STRVAR(PySSL_enum_crls_doc,
3848"enum_crls(store_name) -> []\n\
3849\n\
3850Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3851'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3852The function returns a list of (bytes, encoding_type) tuples. The\n\
3853encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3854PKCS_7_ASN_ENCODING.");
3855
3856static PyObject *
3857PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3858{
3859 char *kwlist[] = {"store_name", NULL};
3860 char *store_name;
3861 HCERTSTORE hStore = NULL;
3862 PCCRL_CONTEXT pCrlCtx = NULL;
3863 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3864 PyObject *result = NULL;
3865
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003866 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003867 kwlist, &store_name)) {
3868 return NULL;
3869 }
3870 result = PyList_New(0);
3871 if (result == NULL) {
3872 return NULL;
3873 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003874 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3875 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3876 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003877 if (hStore == NULL) {
3878 Py_DECREF(result);
3879 return PyErr_SetFromWindowsErr(GetLastError());
3880 }
3881
3882 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3883 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3884 pCrlCtx->cbCrlEncoded);
3885 if (!crl) {
3886 Py_CLEAR(result);
3887 break;
3888 }
3889 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3890 Py_CLEAR(result);
3891 break;
3892 }
3893 if ((tup = PyTuple_New(2)) == NULL) {
3894 Py_CLEAR(result);
3895 break;
3896 }
3897 PyTuple_SET_ITEM(tup, 0, crl);
3898 crl = NULL;
3899 PyTuple_SET_ITEM(tup, 1, enc);
3900 enc = NULL;
3901
3902 if (PyList_Append(result, tup) < 0) {
3903 Py_CLEAR(result);
3904 break;
3905 }
3906 Py_CLEAR(tup);
3907 }
3908 if (pCrlCtx) {
3909 /* loop ended with an error, need to clean up context manually */
3910 CertFreeCRLContext(pCrlCtx);
3911 }
3912
3913 /* In error cases cert, enc and tup may not be NULL */
3914 Py_XDECREF(crl);
3915 Py_XDECREF(enc);
3916 Py_XDECREF(tup);
3917
3918 if (!CertCloseStore(hStore, 0)) {
3919 /* This error case might shadow another exception.*/
3920 Py_XDECREF(result);
3921 return PyErr_SetFromWindowsErr(GetLastError());
3922 }
3923 return result;
3924}
3925
3926#endif /* _MSC_VER */
3927
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003928/* List of functions exported by this module. */
3929
3930static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003931 {"_test_decode_cert", PySSL_test_decode_certificate,
3932 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003933#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003934 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3935 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003936 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3937 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003938#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003939#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003940 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3941 PySSL_RAND_egd_doc},
3942#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003943 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3944 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3945#ifdef _MSC_VER
3946 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3947 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3948 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3949 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3950#endif
3951 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3952 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3953 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3954 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003955 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003956};
3957
3958
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003959#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003960
3961/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003962 * of the Python C thread library
3963 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3964 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003965
3966static PyThread_type_lock *_ssl_locks = NULL;
3967
Christian Heimes10107812013-08-19 17:36:29 +02003968#if OPENSSL_VERSION_NUMBER >= 0x10000000
3969/* use new CRYPTO_THREADID API. */
3970static void
3971_ssl_threadid_callback(CRYPTO_THREADID *id)
3972{
3973 CRYPTO_THREADID_set_numeric(id,
3974 (unsigned long)PyThread_get_thread_ident());
3975}
3976#else
3977/* deprecated CRYPTO_set_id_callback() API. */
3978static unsigned long
3979_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003980 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003981}
Christian Heimes10107812013-08-19 17:36:29 +02003982#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003983
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003984static void _ssl_thread_locking_function
3985 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003986 /* this function is needed to perform locking on shared data
3987 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003988 structures that will be implicitly shared whenever multiple
3989 threads use OpenSSL.) Multi-threaded applications will
3990 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003991
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003992 locking_function() must be able to handle up to
3993 CRYPTO_num_locks() different mutex locks. It sets the n-th
3994 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003995
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003996 file and line are the file number of the function setting the
3997 lock. They can be useful for debugging.
3998 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003999
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004000 if ((_ssl_locks == NULL) ||
4001 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4002 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004003
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004004 if (mode & CRYPTO_LOCK) {
4005 PyThread_acquire_lock(_ssl_locks[n], 1);
4006 } else {
4007 PyThread_release_lock(_ssl_locks[n]);
4008 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004009}
4010
4011static int _setup_ssl_threads(void) {
4012
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004013 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004014
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004015 if (_ssl_locks == NULL) {
4016 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004017 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4018 if (_ssl_locks == NULL) {
4019 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004020 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004021 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004022 memset(_ssl_locks, 0,
4023 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004024 for (i = 0; i < _ssl_locks_count; i++) {
4025 _ssl_locks[i] = PyThread_allocate_lock();
4026 if (_ssl_locks[i] == NULL) {
4027 unsigned int j;
4028 for (j = 0; j < i; j++) {
4029 PyThread_free_lock(_ssl_locks[j]);
4030 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004031 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004032 return 0;
4033 }
4034 }
4035 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004036#if OPENSSL_VERSION_NUMBER >= 0x10000000
4037 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4038#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004039 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004040#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004041 }
4042 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004043}
4044
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004045#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004047PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004048"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004049for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004050
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004051
4052
4053
4054static void
4055parse_openssl_version(unsigned long libver,
4056 unsigned int *major, unsigned int *minor,
4057 unsigned int *fix, unsigned int *patch,
4058 unsigned int *status)
4059{
4060 *status = libver & 0xF;
4061 libver >>= 4;
4062 *patch = libver & 0xFF;
4063 libver >>= 8;
4064 *fix = libver & 0xFF;
4065 libver >>= 8;
4066 *minor = libver & 0xFF;
4067 libver >>= 8;
4068 *major = libver & 0xFF;
4069}
4070
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004071PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004072init_ssl(void)
4073{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004074 PyObject *m, *d, *r;
4075 unsigned long libver;
4076 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004077 struct py_ssl_error_code *errcode;
4078 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004079
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004080 if (PyType_Ready(&PySSLContext_Type) < 0)
4081 return;
4082 if (PyType_Ready(&PySSLSocket_Type) < 0)
4083 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004084
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004085 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4086 if (m == NULL)
4087 return;
4088 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004089
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004090 /* Load _socket module and its C API */
4091 if (PySocketModule_ImportModuleAndAPI())
4092 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004093
Christian Heimes7daa45d2017-09-05 17:12:12 +02004094#ifndef OPENSSL_VERSION_1_1
4095 /* Load all algorithms and initialize cpuid */
4096 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004097 /* Init OpenSSL */
4098 SSL_load_error_strings();
4099 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004100#endif
4101
Bill Janssen98d19da2007-09-10 21:51:02 +00004102#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004103#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004104 /* note that this will start threading if not already started */
4105 if (!_setup_ssl_threads()) {
4106 return;
4107 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004108#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4109 /* OpenSSL 1.1.0 builtin thread support is enabled */
4110 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004111#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004112#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004113
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004114 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004115 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4116 "ssl.SSLError", SSLError_doc,
4117 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004118 if (PySSLErrorObject == NULL)
4119 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004120 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4121
4122 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4123 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4124 PySSLErrorObject, NULL);
4125 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4126 "ssl.SSLWantReadError", SSLWantReadError_doc,
4127 PySSLErrorObject, NULL);
4128 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4129 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4130 PySSLErrorObject, NULL);
4131 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4132 "ssl.SSLSyscallError", SSLSyscallError_doc,
4133 PySSLErrorObject, NULL);
4134 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4135 "ssl.SSLEOFError", SSLEOFError_doc,
4136 PySSLErrorObject, NULL);
4137 if (PySSLZeroReturnErrorObject == NULL
4138 || PySSLWantReadErrorObject == NULL
4139 || PySSLWantWriteErrorObject == NULL
4140 || PySSLSyscallErrorObject == NULL
4141 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004142 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004143
4144 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4145 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4146 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4147 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4148 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4149
4150 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4151 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4152 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4153 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4154 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4155 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4156 return;
4157 if (PyDict_SetItemString(d, "_SSLContext",
4158 (PyObject *)&PySSLContext_Type) != 0)
4159 return;
4160 if (PyDict_SetItemString(d, "_SSLSocket",
4161 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004162 return;
4163 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4164 PY_SSL_ERROR_ZERO_RETURN);
4165 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4166 PY_SSL_ERROR_WANT_READ);
4167 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4168 PY_SSL_ERROR_WANT_WRITE);
4169 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4170 PY_SSL_ERROR_WANT_X509_LOOKUP);
4171 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4172 PY_SSL_ERROR_SYSCALL);
4173 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4174 PY_SSL_ERROR_SSL);
4175 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4176 PY_SSL_ERROR_WANT_CONNECT);
4177 /* non ssl.h errorcodes */
4178 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4179 PY_SSL_ERROR_EOF);
4180 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4181 PY_SSL_ERROR_INVALID_ERROR_CODE);
4182 /* cert requirements */
4183 PyModule_AddIntConstant(m, "CERT_NONE",
4184 PY_SSL_CERT_NONE);
4185 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4186 PY_SSL_CERT_OPTIONAL);
4187 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4188 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004189 /* CRL verification for verification_flags */
4190 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4191 0);
4192 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4193 X509_V_FLAG_CRL_CHECK);
4194 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4195 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4196 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4197 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004198#ifdef X509_V_FLAG_TRUSTED_FIRST
4199 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4200 X509_V_FLAG_TRUSTED_FIRST);
4201#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004202
4203 /* Alert Descriptions from ssl.h */
4204 /* note RESERVED constants no longer intended for use have been removed */
4205 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4206
4207#define ADD_AD_CONSTANT(s) \
4208 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4209 SSL_AD_##s)
4210
4211 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4212 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4213 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4214 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4215 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4216 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4217 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4218 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4219 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4220 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4221 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4222 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4223 ADD_AD_CONSTANT(UNKNOWN_CA);
4224 ADD_AD_CONSTANT(ACCESS_DENIED);
4225 ADD_AD_CONSTANT(DECODE_ERROR);
4226 ADD_AD_CONSTANT(DECRYPT_ERROR);
4227 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4228 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4229 ADD_AD_CONSTANT(INTERNAL_ERROR);
4230 ADD_AD_CONSTANT(USER_CANCELLED);
4231 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4232 /* Not all constants are in old OpenSSL versions */
4233#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4234 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4235#endif
4236#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4237 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4238#endif
4239#ifdef SSL_AD_UNRECOGNIZED_NAME
4240 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4241#endif
4242#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4243 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4244#endif
4245#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4246 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4247#endif
4248#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4249 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4250#endif
4251
4252#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004253
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004254 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004255#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004256 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4257 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004258#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004259#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004260 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4261 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004262#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004263 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004264 PY_SSL_VERSION_TLS);
4265 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4266 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004267 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4268 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004269#if HAVE_TLSv1_2
4270 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4271 PY_SSL_VERSION_TLS1_1);
4272 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4273 PY_SSL_VERSION_TLS1_2);
4274#endif
4275
4276 /* protocol options */
4277 PyModule_AddIntConstant(m, "OP_ALL",
4278 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4279 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4280 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4281 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4282#if HAVE_TLSv1_2
4283 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4284 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4285#endif
4286 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4287 SSL_OP_CIPHER_SERVER_PREFERENCE);
4288 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4289#ifdef SSL_OP_SINGLE_ECDH_USE
4290 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4291#endif
4292#ifdef SSL_OP_NO_COMPRESSION
4293 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4294 SSL_OP_NO_COMPRESSION);
4295#endif
4296
4297#if HAVE_SNI
4298 r = Py_True;
4299#else
4300 r = Py_False;
4301#endif
4302 Py_INCREF(r);
4303 PyModule_AddObject(m, "HAS_SNI", r);
4304
4305#if HAVE_OPENSSL_FINISHED
4306 r = Py_True;
4307#else
4308 r = Py_False;
4309#endif
4310 Py_INCREF(r);
4311 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4312
4313#ifdef OPENSSL_NO_ECDH
4314 r = Py_False;
4315#else
4316 r = Py_True;
4317#endif
4318 Py_INCREF(r);
4319 PyModule_AddObject(m, "HAS_ECDH", r);
4320
Christian Heimes72ed2332017-09-05 01:11:40 +02004321#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004322 r = Py_True;
4323#else
4324 r = Py_False;
4325#endif
4326 Py_INCREF(r);
4327 PyModule_AddObject(m, "HAS_NPN", r);
4328
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004329#ifdef HAVE_ALPN
4330 r = Py_True;
4331#else
4332 r = Py_False;
4333#endif
4334 Py_INCREF(r);
4335 PyModule_AddObject(m, "HAS_ALPN", r);
4336
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004337 /* Mappings for error codes */
4338 err_codes_to_names = PyDict_New();
4339 err_names_to_codes = PyDict_New();
4340 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4341 return;
4342 errcode = error_codes;
4343 while (errcode->mnemonic != NULL) {
4344 PyObject *mnemo, *key;
4345 mnemo = PyUnicode_FromString(errcode->mnemonic);
4346 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4347 if (mnemo == NULL || key == NULL)
4348 return;
4349 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4350 return;
4351 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4352 return;
4353 Py_DECREF(key);
4354 Py_DECREF(mnemo);
4355 errcode++;
4356 }
4357 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4358 return;
4359 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4360 return;
4361
4362 lib_codes_to_names = PyDict_New();
4363 if (lib_codes_to_names == NULL)
4364 return;
4365 libcode = library_codes;
4366 while (libcode->library != NULL) {
4367 PyObject *mnemo, *key;
4368 key = PyLong_FromLong(libcode->code);
4369 mnemo = PyUnicode_FromString(libcode->library);
4370 if (key == NULL || mnemo == NULL)
4371 return;
4372 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4373 return;
4374 Py_DECREF(key);
4375 Py_DECREF(mnemo);
4376 libcode++;
4377 }
4378 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4379 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004380
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004381 /* OpenSSL version */
4382 /* SSLeay() gives us the version of the library linked against,
4383 which could be different from the headers version.
4384 */
4385 libver = SSLeay();
4386 r = PyLong_FromUnsignedLong(libver);
4387 if (r == NULL)
4388 return;
4389 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4390 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004391 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004392 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4393 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4394 return;
4395 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4396 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4397 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004398
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004399 libver = OPENSSL_VERSION_NUMBER;
4400 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4401 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4402 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4403 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004404}