blob: 5b4cec203addf68df154c439376f7c06a7da23e9 [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) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002149 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002150 return NULL;
2151 }
2152
2153 assert(type != NULL && type->tp_alloc != NULL);
2154 self = (PySSLContext *) type->tp_alloc(type, 0);
2155 if (self == NULL) {
2156 SSL_CTX_free(ctx);
2157 return NULL;
2158 }
2159 self->ctx = ctx;
Christian Heimes72ed2332017-09-05 01:11:40 +02002160#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002161 self->npn_protocols = NULL;
2162#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002163#ifdef HAVE_ALPN
2164 self->alpn_protocols = NULL;
2165#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002166#ifndef OPENSSL_NO_TLSEXT
2167 self->set_hostname = NULL;
2168#endif
2169 /* Don't check host name by default */
2170 self->check_hostname = 0;
2171 /* Defaults */
2172 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2173 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2174 if (proto_version != PY_SSL_VERSION_SSL2)
2175 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002176 if (proto_version != PY_SSL_VERSION_SSL3)
2177 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002178 SSL_CTX_set_options(self->ctx, options);
2179
Donald Stufftf1a696e2017-03-02 12:37:07 -05002180#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002181 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2182 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002183 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2184 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002185#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002186 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2187#else
2188 {
2189 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2190 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2191 EC_KEY_free(key);
2192 }
2193#endif
2194#endif
2195
2196#define SID_CTX "Python"
2197 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2198 sizeof(SID_CTX));
2199#undef SID_CTX
2200
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002201#ifdef X509_V_FLAG_TRUSTED_FIRST
2202 {
2203 /* Improve trust chain building when cross-signed intermediate
2204 certificates are present. See https://bugs.python.org/issue23476. */
2205 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2206 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2207 }
2208#endif
2209
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002210 return (PyObject *)self;
2211}
2212
2213static int
2214context_traverse(PySSLContext *self, visitproc visit, void *arg)
2215{
2216#ifndef OPENSSL_NO_TLSEXT
2217 Py_VISIT(self->set_hostname);
2218#endif
2219 return 0;
2220}
2221
2222static int
2223context_clear(PySSLContext *self)
2224{
2225#ifndef OPENSSL_NO_TLSEXT
2226 Py_CLEAR(self->set_hostname);
2227#endif
2228 return 0;
2229}
2230
2231static void
2232context_dealloc(PySSLContext *self)
2233{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002234 /* bpo-31095: UnTrack is needed before calling any callbacks */
2235 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002236 context_clear(self);
2237 SSL_CTX_free(self->ctx);
Christian Heimes72ed2332017-09-05 01:11:40 +02002238#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002239 PyMem_FREE(self->npn_protocols);
2240#endif
2241#ifdef HAVE_ALPN
2242 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002243#endif
2244 Py_TYPE(self)->tp_free(self);
2245}
2246
2247static PyObject *
2248set_ciphers(PySSLContext *self, PyObject *args)
2249{
2250 int ret;
2251 const char *cipherlist;
2252
2253 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2254 return NULL;
2255 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2256 if (ret == 0) {
2257 /* Clearing the error queue is necessary on some OpenSSL versions,
2258 otherwise the error will be reported again when another SSL call
2259 is done. */
2260 ERR_clear_error();
2261 PyErr_SetString(PySSLErrorObject,
2262 "No cipher can be selected.");
2263 return NULL;
2264 }
2265 Py_RETURN_NONE;
2266}
2267
Christian Heimes72ed2332017-09-05 01:11:40 +02002268#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002269static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002270do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2271 const unsigned char *server_protocols, unsigned int server_protocols_len,
2272 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002273{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002274 int ret;
2275 if (client_protocols == NULL) {
2276 client_protocols = (unsigned char *)"";
2277 client_protocols_len = 0;
2278 }
2279 if (server_protocols == NULL) {
2280 server_protocols = (unsigned char *)"";
2281 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002282 }
2283
Benjamin Petersonaa707582015-01-23 17:30:26 -05002284 ret = SSL_select_next_proto(out, outlen,
2285 server_protocols, server_protocols_len,
2286 client_protocols, client_protocols_len);
2287 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2288 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002289
2290 return SSL_TLSEXT_ERR_OK;
2291}
Christian Heimes72ed2332017-09-05 01:11:40 +02002292#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002293
Christian Heimes72ed2332017-09-05 01:11:40 +02002294#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002295/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2296static int
2297_advertiseNPN_cb(SSL *s,
2298 const unsigned char **data, unsigned int *len,
2299 void *args)
2300{
2301 PySSLContext *ssl_ctx = (PySSLContext *) args;
2302
2303 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002304 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002305 *len = 0;
2306 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002307 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002308 *len = ssl_ctx->npn_protocols_len;
2309 }
2310
2311 return SSL_TLSEXT_ERR_OK;
2312}
2313/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2314static int
2315_selectNPN_cb(SSL *s,
2316 unsigned char **out, unsigned char *outlen,
2317 const unsigned char *server, unsigned int server_len,
2318 void *args)
2319{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002320 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002321 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002322 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002323}
2324#endif
2325
2326static PyObject *
2327_set_npn_protocols(PySSLContext *self, PyObject *args)
2328{
Christian Heimes72ed2332017-09-05 01:11:40 +02002329#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002330 Py_buffer protos;
2331
2332 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2333 return NULL;
2334
2335 if (self->npn_protocols != NULL) {
2336 PyMem_Free(self->npn_protocols);
2337 }
2338
2339 self->npn_protocols = PyMem_Malloc(protos.len);
2340 if (self->npn_protocols == NULL) {
2341 PyBuffer_Release(&protos);
2342 return PyErr_NoMemory();
2343 }
2344 memcpy(self->npn_protocols, protos.buf, protos.len);
2345 self->npn_protocols_len = (int) protos.len;
2346
2347 /* set both server and client callbacks, because the context can
2348 * be used to create both types of sockets */
2349 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2350 _advertiseNPN_cb,
2351 self);
2352 SSL_CTX_set_next_proto_select_cb(self->ctx,
2353 _selectNPN_cb,
2354 self);
2355
2356 PyBuffer_Release(&protos);
2357 Py_RETURN_NONE;
2358#else
2359 PyErr_SetString(PyExc_NotImplementedError,
2360 "The NPN extension requires OpenSSL 1.0.1 or later.");
2361 return NULL;
2362#endif
2363}
2364
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002365#ifdef HAVE_ALPN
2366static int
2367_selectALPN_cb(SSL *s,
2368 const unsigned char **out, unsigned char *outlen,
2369 const unsigned char *client_protocols, unsigned int client_protocols_len,
2370 void *args)
2371{
2372 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002373 return do_protocol_selection(1, (unsigned char **)out, outlen,
2374 ctx->alpn_protocols, ctx->alpn_protocols_len,
2375 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002376}
2377#endif
2378
2379static PyObject *
2380_set_alpn_protocols(PySSLContext *self, PyObject *args)
2381{
2382#ifdef HAVE_ALPN
2383 Py_buffer protos;
2384
2385 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2386 return NULL;
2387
2388 PyMem_FREE(self->alpn_protocols);
2389 self->alpn_protocols = PyMem_Malloc(protos.len);
2390 if (!self->alpn_protocols)
2391 return PyErr_NoMemory();
2392 memcpy(self->alpn_protocols, protos.buf, protos.len);
2393 self->alpn_protocols_len = protos.len;
2394 PyBuffer_Release(&protos);
2395
2396 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2397 return PyErr_NoMemory();
2398 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2399
2400 PyBuffer_Release(&protos);
2401 Py_RETURN_NONE;
2402#else
2403 PyErr_SetString(PyExc_NotImplementedError,
2404 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2405 return NULL;
2406#endif
2407}
2408
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002409static PyObject *
2410get_verify_mode(PySSLContext *self, void *c)
2411{
2412 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2413 case SSL_VERIFY_NONE:
2414 return PyLong_FromLong(PY_SSL_CERT_NONE);
2415 case SSL_VERIFY_PEER:
2416 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2417 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2418 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2419 }
2420 PyErr_SetString(PySSLErrorObject,
2421 "invalid return value from SSL_CTX_get_verify_mode");
2422 return NULL;
2423}
2424
2425static int
2426set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2427{
2428 int n, mode;
2429 if (!PyArg_Parse(arg, "i", &n))
2430 return -1;
2431 if (n == PY_SSL_CERT_NONE)
2432 mode = SSL_VERIFY_NONE;
2433 else if (n == PY_SSL_CERT_OPTIONAL)
2434 mode = SSL_VERIFY_PEER;
2435 else if (n == PY_SSL_CERT_REQUIRED)
2436 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2437 else {
2438 PyErr_SetString(PyExc_ValueError,
2439 "invalid value for verify_mode");
2440 return -1;
2441 }
2442 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2443 PyErr_SetString(PyExc_ValueError,
2444 "Cannot set verify_mode to CERT_NONE when "
2445 "check_hostname is enabled.");
2446 return -1;
2447 }
2448 SSL_CTX_set_verify(self->ctx, mode, NULL);
2449 return 0;
2450}
2451
2452#ifdef HAVE_OPENSSL_VERIFY_PARAM
2453static PyObject *
2454get_verify_flags(PySSLContext *self, void *c)
2455{
2456 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002457 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002458 unsigned long flags;
2459
2460 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002461 param = X509_STORE_get0_param(store);
2462 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002463 return PyLong_FromUnsignedLong(flags);
2464}
2465
2466static int
2467set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2468{
2469 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002470 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002471 unsigned long new_flags, flags, set, clear;
2472
2473 if (!PyArg_Parse(arg, "k", &new_flags))
2474 return -1;
2475 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002476 param = X509_STORE_get0_param(store);
2477 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002478 clear = flags & ~new_flags;
2479 set = ~flags & new_flags;
2480 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002481 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002482 _setSSLError(NULL, 0, __FILE__, __LINE__);
2483 return -1;
2484 }
2485 }
2486 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002487 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002488 _setSSLError(NULL, 0, __FILE__, __LINE__);
2489 return -1;
2490 }
2491 }
2492 return 0;
2493}
2494#endif
2495
2496static PyObject *
2497get_options(PySSLContext *self, void *c)
2498{
2499 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2500}
2501
2502static int
2503set_options(PySSLContext *self, PyObject *arg, void *c)
2504{
2505 long new_opts, opts, set, clear;
2506 if (!PyArg_Parse(arg, "l", &new_opts))
2507 return -1;
2508 opts = SSL_CTX_get_options(self->ctx);
2509 clear = opts & ~new_opts;
2510 set = ~opts & new_opts;
2511 if (clear) {
2512#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2513 SSL_CTX_clear_options(self->ctx, clear);
2514#else
2515 PyErr_SetString(PyExc_ValueError,
2516 "can't clear options before OpenSSL 0.9.8m");
2517 return -1;
2518#endif
2519 }
2520 if (set)
2521 SSL_CTX_set_options(self->ctx, set);
2522 return 0;
2523}
2524
2525static PyObject *
2526get_check_hostname(PySSLContext *self, void *c)
2527{
2528 return PyBool_FromLong(self->check_hostname);
2529}
2530
2531static int
2532set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2533{
2534 PyObject *py_check_hostname;
2535 int check_hostname;
2536 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2537 return -1;
2538
2539 check_hostname = PyObject_IsTrue(py_check_hostname);
2540 if (check_hostname < 0)
2541 return -1;
2542 if (check_hostname &&
2543 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2544 PyErr_SetString(PyExc_ValueError,
2545 "check_hostname needs a SSL context with either "
2546 "CERT_OPTIONAL or CERT_REQUIRED");
2547 return -1;
2548 }
2549 self->check_hostname = check_hostname;
2550 return 0;
2551}
2552
2553
2554typedef struct {
2555 PyThreadState *thread_state;
2556 PyObject *callable;
2557 char *password;
2558 int size;
2559 int error;
2560} _PySSLPasswordInfo;
2561
2562static int
2563_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2564 const char *bad_type_error)
2565{
2566 /* Set the password and size fields of a _PySSLPasswordInfo struct
2567 from a unicode, bytes, or byte array object.
2568 The password field will be dynamically allocated and must be freed
2569 by the caller */
2570 PyObject *password_bytes = NULL;
2571 const char *data = NULL;
2572 Py_ssize_t size;
2573
2574 if (PyUnicode_Check(password)) {
2575 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2576 if (!password_bytes) {
2577 goto error;
2578 }
2579 data = PyBytes_AS_STRING(password_bytes);
2580 size = PyBytes_GET_SIZE(password_bytes);
2581 } else if (PyBytes_Check(password)) {
2582 data = PyBytes_AS_STRING(password);
2583 size = PyBytes_GET_SIZE(password);
2584 } else if (PyByteArray_Check(password)) {
2585 data = PyByteArray_AS_STRING(password);
2586 size = PyByteArray_GET_SIZE(password);
2587 } else {
2588 PyErr_SetString(PyExc_TypeError, bad_type_error);
2589 goto error;
2590 }
2591
2592 if (size > (Py_ssize_t)INT_MAX) {
2593 PyErr_Format(PyExc_ValueError,
2594 "password cannot be longer than %d bytes", INT_MAX);
2595 goto error;
2596 }
2597
2598 PyMem_Free(pw_info->password);
2599 pw_info->password = PyMem_Malloc(size);
2600 if (!pw_info->password) {
2601 PyErr_SetString(PyExc_MemoryError,
2602 "unable to allocate password buffer");
2603 goto error;
2604 }
2605 memcpy(pw_info->password, data, size);
2606 pw_info->size = (int)size;
2607
2608 Py_XDECREF(password_bytes);
2609 return 1;
2610
2611error:
2612 Py_XDECREF(password_bytes);
2613 return 0;
2614}
2615
2616static int
2617_password_callback(char *buf, int size, int rwflag, void *userdata)
2618{
2619 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2620 PyObject *fn_ret = NULL;
2621
2622 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2623
2624 if (pw_info->callable) {
2625 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2626 if (!fn_ret) {
2627 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2628 core python API, so we could use it to add a frame here */
2629 goto error;
2630 }
2631
2632 if (!_pwinfo_set(pw_info, fn_ret,
2633 "password callback must return a string")) {
2634 goto error;
2635 }
2636 Py_CLEAR(fn_ret);
2637 }
2638
2639 if (pw_info->size > size) {
2640 PyErr_Format(PyExc_ValueError,
2641 "password cannot be longer than %d bytes", size);
2642 goto error;
2643 }
2644
2645 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2646 memcpy(buf, pw_info->password, pw_info->size);
2647 return pw_info->size;
2648
2649error:
2650 Py_XDECREF(fn_ret);
2651 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2652 pw_info->error = 1;
2653 return -1;
2654}
2655
2656static PyObject *
2657load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2658{
2659 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002660 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2661 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002662 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2663 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002664 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2665 int r;
2666
2667 errno = 0;
2668 ERR_clear_error();
2669 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002670 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002671 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002672 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002673 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002674
2675 if (keyfile && keyfile != Py_None) {
2676 if (PyString_Check(keyfile)) {
2677 Py_INCREF(keyfile);
2678 keyfile_bytes = keyfile;
2679 } else {
2680 PyObject *u = PyUnicode_FromObject(keyfile);
2681 if (!u)
2682 goto error;
2683 keyfile_bytes = PyUnicode_AsEncodedString(
2684 u, Py_FileSystemDefaultEncoding, NULL);
2685 Py_DECREF(u);
2686 if (!keyfile_bytes)
2687 goto error;
2688 }
2689 }
2690
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002691 if (password && password != Py_None) {
2692 if (PyCallable_Check(password)) {
2693 pw_info.callable = password;
2694 } else if (!_pwinfo_set(&pw_info, password,
2695 "password should be a string or callable")) {
2696 goto error;
2697 }
2698 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2699 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2700 }
2701 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2702 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2703 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2704 if (r != 1) {
2705 if (pw_info.error) {
2706 ERR_clear_error();
2707 /* the password callback has already set the error information */
2708 }
2709 else if (errno != 0) {
2710 ERR_clear_error();
2711 PyErr_SetFromErrno(PyExc_IOError);
2712 }
2713 else {
2714 _setSSLError(NULL, 0, __FILE__, __LINE__);
2715 }
2716 goto error;
2717 }
2718 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2719 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002720 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002721 SSL_FILETYPE_PEM);
2722 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2723 if (r != 1) {
2724 if (pw_info.error) {
2725 ERR_clear_error();
2726 /* the password callback has already set the error information */
2727 }
2728 else if (errno != 0) {
2729 ERR_clear_error();
2730 PyErr_SetFromErrno(PyExc_IOError);
2731 }
2732 else {
2733 _setSSLError(NULL, 0, __FILE__, __LINE__);
2734 }
2735 goto error;
2736 }
2737 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2738 r = SSL_CTX_check_private_key(self->ctx);
2739 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2740 if (r != 1) {
2741 _setSSLError(NULL, 0, __FILE__, __LINE__);
2742 goto error;
2743 }
2744 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2745 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002746 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002747 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002748 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002749 Py_RETURN_NONE;
2750
2751error:
2752 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2753 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002754 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002755 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002756 PyMem_Free(certfile_bytes);
2757 return NULL;
2758}
2759
2760/* internal helper function, returns -1 on error
2761 */
2762static int
2763_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2764 int filetype)
2765{
2766 BIO *biobuf = NULL;
2767 X509_STORE *store;
2768 int retval = 0, err, loaded = 0;
2769
2770 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2771
2772 if (len <= 0) {
2773 PyErr_SetString(PyExc_ValueError,
2774 "Empty certificate data");
2775 return -1;
2776 } else if (len > INT_MAX) {
2777 PyErr_SetString(PyExc_OverflowError,
2778 "Certificate data is too long.");
2779 return -1;
2780 }
2781
2782 biobuf = BIO_new_mem_buf(data, (int)len);
2783 if (biobuf == NULL) {
2784 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2785 return -1;
2786 }
2787
2788 store = SSL_CTX_get_cert_store(self->ctx);
2789 assert(store != NULL);
2790
2791 while (1) {
2792 X509 *cert = NULL;
2793 int r;
2794
2795 if (filetype == SSL_FILETYPE_ASN1) {
2796 cert = d2i_X509_bio(biobuf, NULL);
2797 } else {
2798 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002799 SSL_CTX_get_default_passwd_cb(self->ctx),
2800 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2801 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002802 }
2803 if (cert == NULL) {
2804 break;
2805 }
2806 r = X509_STORE_add_cert(store, cert);
2807 X509_free(cert);
2808 if (!r) {
2809 err = ERR_peek_last_error();
2810 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2811 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2812 /* cert already in hash table, not an error */
2813 ERR_clear_error();
2814 } else {
2815 break;
2816 }
2817 }
2818 loaded++;
2819 }
2820
2821 err = ERR_peek_last_error();
2822 if ((filetype == SSL_FILETYPE_ASN1) &&
2823 (loaded > 0) &&
2824 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2825 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2826 /* EOF ASN1 file, not an error */
2827 ERR_clear_error();
2828 retval = 0;
2829 } else if ((filetype == SSL_FILETYPE_PEM) &&
2830 (loaded > 0) &&
2831 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2832 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2833 /* EOF PEM file, not an error */
2834 ERR_clear_error();
2835 retval = 0;
2836 } else {
2837 _setSSLError(NULL, 0, __FILE__, __LINE__);
2838 retval = -1;
2839 }
2840
2841 BIO_free(biobuf);
2842 return retval;
2843}
2844
2845
2846static PyObject *
2847load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2848{
2849 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2850 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2851 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2852 const char *cafile_buf = NULL, *capath_buf = NULL;
2853 int r = 0, ok = 1;
2854
2855 errno = 0;
2856 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2857 "|OOO:load_verify_locations", kwlist,
2858 &cafile, &capath, &cadata))
2859 return NULL;
2860
2861 if (cafile == Py_None)
2862 cafile = NULL;
2863 if (capath == Py_None)
2864 capath = NULL;
2865 if (cadata == Py_None)
2866 cadata = NULL;
2867
2868 if (cafile == NULL && capath == NULL && cadata == NULL) {
2869 PyErr_SetString(PyExc_TypeError,
2870 "cafile, capath and cadata cannot be all omitted");
2871 goto error;
2872 }
2873
2874 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002875 if (PyString_Check(cafile)) {
2876 Py_INCREF(cafile);
2877 cafile_bytes = cafile;
2878 } else {
2879 PyObject *u = PyUnicode_FromObject(cafile);
2880 if (!u)
2881 goto error;
2882 cafile_bytes = PyUnicode_AsEncodedString(
2883 u, Py_FileSystemDefaultEncoding, NULL);
2884 Py_DECREF(u);
2885 if (!cafile_bytes)
2886 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002887 }
2888 }
2889 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002890 if (PyString_Check(capath)) {
2891 Py_INCREF(capath);
2892 capath_bytes = capath;
2893 } else {
2894 PyObject *u = PyUnicode_FromObject(capath);
2895 if (!u)
2896 goto error;
2897 capath_bytes = PyUnicode_AsEncodedString(
2898 u, Py_FileSystemDefaultEncoding, NULL);
2899 Py_DECREF(u);
2900 if (!capath_bytes)
2901 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002902 }
2903 }
2904
2905 /* validata cadata type and load cadata */
2906 if (cadata) {
2907 Py_buffer buf;
2908 PyObject *cadata_ascii = NULL;
2909
2910 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2911 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2912 PyBuffer_Release(&buf);
2913 PyErr_SetString(PyExc_TypeError,
2914 "cadata should be a contiguous buffer with "
2915 "a single dimension");
2916 goto error;
2917 }
2918 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2919 PyBuffer_Release(&buf);
2920 if (r == -1) {
2921 goto error;
2922 }
2923 } else {
2924 PyErr_Clear();
2925 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2926 if (cadata_ascii == NULL) {
2927 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002928 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002929 "bytes-like object");
2930 goto error;
2931 }
2932 r = _add_ca_certs(self,
2933 PyBytes_AS_STRING(cadata_ascii),
2934 PyBytes_GET_SIZE(cadata_ascii),
2935 SSL_FILETYPE_PEM);
2936 Py_DECREF(cadata_ascii);
2937 if (r == -1) {
2938 goto error;
2939 }
2940 }
2941 }
2942
2943 /* load cafile or capath */
2944 if (cafile_bytes || capath_bytes) {
2945 if (cafile)
2946 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2947 if (capath)
2948 capath_buf = PyBytes_AS_STRING(capath_bytes);
2949 PySSL_BEGIN_ALLOW_THREADS
2950 r = SSL_CTX_load_verify_locations(
2951 self->ctx,
2952 cafile_buf,
2953 capath_buf);
2954 PySSL_END_ALLOW_THREADS
2955 if (r != 1) {
2956 ok = 0;
2957 if (errno != 0) {
2958 ERR_clear_error();
2959 PyErr_SetFromErrno(PyExc_IOError);
2960 }
2961 else {
2962 _setSSLError(NULL, 0, __FILE__, __LINE__);
2963 }
2964 goto error;
2965 }
2966 }
2967 goto end;
2968
2969 error:
2970 ok = 0;
2971 end:
2972 Py_XDECREF(cafile_bytes);
2973 Py_XDECREF(capath_bytes);
2974 if (ok) {
2975 Py_RETURN_NONE;
2976 } else {
2977 return NULL;
2978 }
2979}
2980
2981static PyObject *
2982load_dh_params(PySSLContext *self, PyObject *filepath)
2983{
2984 BIO *bio;
2985 DH *dh;
2986 char *path = PyBytes_AsString(filepath);
2987 if (!path) {
2988 return NULL;
2989 }
2990
2991 bio = BIO_new_file(path, "r");
2992 if (bio == NULL) {
2993 ERR_clear_error();
2994 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2995 return NULL;
2996 }
2997 errno = 0;
2998 PySSL_BEGIN_ALLOW_THREADS
2999 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3000 BIO_free(bio);
3001 PySSL_END_ALLOW_THREADS
3002 if (dh == NULL) {
3003 if (errno != 0) {
3004 ERR_clear_error();
3005 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3006 }
3007 else {
3008 _setSSLError(NULL, 0, __FILE__, __LINE__);
3009 }
3010 return NULL;
3011 }
3012 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3013 _setSSLError(NULL, 0, __FILE__, __LINE__);
3014 DH_free(dh);
3015 Py_RETURN_NONE;
3016}
3017
3018static PyObject *
3019context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3020{
3021 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3022 PySocketSockObject *sock;
3023 int server_side = 0;
3024 char *hostname = NULL;
3025 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3026
3027 /* server_hostname is either None (or absent), or to be encoded
3028 using the idna encoding. */
3029 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3030 PySocketModule.Sock_Type,
3031 &sock, &server_side,
3032 Py_TYPE(Py_None), &hostname_obj,
3033 &ssl_sock)) {
3034 PyErr_Clear();
3035 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3036 PySocketModule.Sock_Type,
3037 &sock, &server_side,
3038 "idna", &hostname, &ssl_sock))
3039 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003040 }
3041
3042 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3043 hostname, ssl_sock);
3044 if (hostname != NULL)
3045 PyMem_Free(hostname);
3046 return res;
3047}
3048
3049static PyObject *
3050session_stats(PySSLContext *self, PyObject *unused)
3051{
3052 int r;
3053 PyObject *value, *stats = PyDict_New();
3054 if (!stats)
3055 return NULL;
3056
3057#define ADD_STATS(SSL_NAME, KEY_NAME) \
3058 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3059 if (value == NULL) \
3060 goto error; \
3061 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3062 Py_DECREF(value); \
3063 if (r < 0) \
3064 goto error;
3065
3066 ADD_STATS(number, "number");
3067 ADD_STATS(connect, "connect");
3068 ADD_STATS(connect_good, "connect_good");
3069 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3070 ADD_STATS(accept, "accept");
3071 ADD_STATS(accept_good, "accept_good");
3072 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3073 ADD_STATS(accept, "accept");
3074 ADD_STATS(hits, "hits");
3075 ADD_STATS(misses, "misses");
3076 ADD_STATS(timeouts, "timeouts");
3077 ADD_STATS(cache_full, "cache_full");
3078
3079#undef ADD_STATS
3080
3081 return stats;
3082
3083error:
3084 Py_DECREF(stats);
3085 return NULL;
3086}
3087
3088static PyObject *
3089set_default_verify_paths(PySSLContext *self, PyObject *unused)
3090{
3091 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3092 _setSSLError(NULL, 0, __FILE__, __LINE__);
3093 return NULL;
3094 }
3095 Py_RETURN_NONE;
3096}
3097
3098#ifndef OPENSSL_NO_ECDH
3099static PyObject *
3100set_ecdh_curve(PySSLContext *self, PyObject *name)
3101{
3102 char *name_bytes;
3103 int nid;
3104 EC_KEY *key;
3105
3106 name_bytes = PyBytes_AsString(name);
3107 if (!name_bytes) {
3108 return NULL;
3109 }
3110 nid = OBJ_sn2nid(name_bytes);
3111 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003112 PyObject *r = PyObject_Repr(name);
3113 if (!r)
3114 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003115 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003116 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3117 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003118 return NULL;
3119 }
3120 key = EC_KEY_new_by_curve_name(nid);
3121 if (key == NULL) {
3122 _setSSLError(NULL, 0, __FILE__, __LINE__);
3123 return NULL;
3124 }
3125 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3126 EC_KEY_free(key);
3127 Py_RETURN_NONE;
3128}
3129#endif
3130
3131#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3132static int
3133_servername_callback(SSL *s, int *al, void *args)
3134{
3135 int ret;
3136 PySSLContext *ssl_ctx = (PySSLContext *) args;
3137 PySSLSocket *ssl;
3138 PyObject *servername_o;
3139 PyObject *servername_idna;
3140 PyObject *result;
3141 /* The high-level ssl.SSLSocket object */
3142 PyObject *ssl_socket;
3143 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3144#ifdef WITH_THREAD
3145 PyGILState_STATE gstate = PyGILState_Ensure();
3146#endif
3147
3148 if (ssl_ctx->set_hostname == NULL) {
3149 /* remove race condition in this the call back while if removing the
3150 * callback is in progress */
3151#ifdef WITH_THREAD
3152 PyGILState_Release(gstate);
3153#endif
3154 return SSL_TLSEXT_ERR_OK;
3155 }
3156
3157 ssl = SSL_get_app_data(s);
3158 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003159 if (ssl->ssl_sock == NULL) {
3160 ssl_socket = Py_None;
3161 } else {
3162 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3163 Py_INCREF(ssl_socket);
3164 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003165 if (ssl_socket == Py_None) {
3166 goto error;
3167 }
3168
3169 if (servername == NULL) {
3170 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3171 Py_None, ssl_ctx, NULL);
3172 }
3173 else {
3174 servername_o = PyBytes_FromString(servername);
3175 if (servername_o == NULL) {
3176 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3177 goto error;
3178 }
3179 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3180 if (servername_idna == NULL) {
3181 PyErr_WriteUnraisable(servername_o);
3182 Py_DECREF(servername_o);
3183 goto error;
3184 }
3185 Py_DECREF(servername_o);
3186 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3187 servername_idna, ssl_ctx, NULL);
3188 Py_DECREF(servername_idna);
3189 }
3190 Py_DECREF(ssl_socket);
3191
3192 if (result == NULL) {
3193 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3194 *al = SSL_AD_HANDSHAKE_FAILURE;
3195 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3196 }
3197 else {
3198 if (result != Py_None) {
3199 *al = (int) PyLong_AsLong(result);
3200 if (PyErr_Occurred()) {
3201 PyErr_WriteUnraisable(result);
3202 *al = SSL_AD_INTERNAL_ERROR;
3203 }
3204 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3205 }
3206 else {
3207 ret = SSL_TLSEXT_ERR_OK;
3208 }
3209 Py_DECREF(result);
3210 }
3211
3212#ifdef WITH_THREAD
3213 PyGILState_Release(gstate);
3214#endif
3215 return ret;
3216
3217error:
3218 Py_DECREF(ssl_socket);
3219 *al = SSL_AD_INTERNAL_ERROR;
3220 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3221#ifdef WITH_THREAD
3222 PyGILState_Release(gstate);
3223#endif
3224 return ret;
3225}
3226#endif
3227
3228PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3229"set_servername_callback(method)\n\
3230\n\
3231This sets a callback that will be called when a server name is provided by\n\
3232the SSL/TLS client in the SNI extension.\n\
3233\n\
3234If the argument is None then the callback is disabled. The method is called\n\
3235with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3236See RFC 6066 for details of the SNI extension.");
3237
3238static PyObject *
3239set_servername_callback(PySSLContext *self, PyObject *args)
3240{
3241#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3242 PyObject *cb;
3243
3244 if (!PyArg_ParseTuple(args, "O", &cb))
3245 return NULL;
3246
3247 Py_CLEAR(self->set_hostname);
3248 if (cb == Py_None) {
3249 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3250 }
3251 else {
3252 if (!PyCallable_Check(cb)) {
3253 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3254 PyErr_SetString(PyExc_TypeError,
3255 "not a callable object");
3256 return NULL;
3257 }
3258 Py_INCREF(cb);
3259 self->set_hostname = cb;
3260 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3261 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3262 }
3263 Py_RETURN_NONE;
3264#else
3265 PyErr_SetString(PyExc_NotImplementedError,
3266 "The TLS extension servername callback, "
3267 "SSL_CTX_set_tlsext_servername_callback, "
3268 "is not in the current OpenSSL library.");
3269 return NULL;
3270#endif
3271}
3272
3273PyDoc_STRVAR(PySSL_get_stats_doc,
3274"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3275\n\
3276Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3277CA extension and certificate revocation lists inside the context's cert\n\
3278store.\n\
3279NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3280been used at least once.");
3281
3282static PyObject *
3283cert_store_stats(PySSLContext *self)
3284{
3285 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003286 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003287 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003288 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003289
3290 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003291 objs = X509_STORE_get0_objects(store);
3292 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3293 obj = sk_X509_OBJECT_value(objs, i);
3294 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003295 case X509_LU_X509:
3296 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003297 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003298 ca++;
3299 }
3300 break;
3301 case X509_LU_CRL:
3302 crl++;
3303 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003304 default:
3305 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3306 * As far as I can tell they are internal states and never
3307 * stored in a cert store */
3308 break;
3309 }
3310 }
3311 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3312 "x509_ca", ca);
3313}
3314
3315PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3316"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3317\n\
3318Returns a list of dicts with information of loaded CA certs. If the\n\
3319optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3320NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3321been used at least once.");
3322
3323static PyObject *
3324get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3325{
3326 char *kwlist[] = {"binary_form", NULL};
3327 X509_STORE *store;
3328 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003329 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003330 int i;
3331 int binary_mode = 0;
3332
3333 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3334 kwlist, &py_binary_mode)) {
3335 return NULL;
3336 }
3337 binary_mode = PyObject_IsTrue(py_binary_mode);
3338 if (binary_mode < 0) {
3339 return NULL;
3340 }
3341
3342 if ((rlist = PyList_New(0)) == NULL) {
3343 return NULL;
3344 }
3345
3346 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003347 objs = X509_STORE_get0_objects(store);
3348 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003349 X509_OBJECT *obj;
3350 X509 *cert;
3351
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003352 obj = sk_X509_OBJECT_value(objs, i);
3353 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003354 /* not a x509 cert */
3355 continue;
3356 }
3357 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003358 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003359 if (!X509_check_ca(cert)) {
3360 continue;
3361 }
3362 if (binary_mode) {
3363 ci = _certificate_to_der(cert);
3364 } else {
3365 ci = _decode_certificate(cert);
3366 }
3367 if (ci == NULL) {
3368 goto error;
3369 }
3370 if (PyList_Append(rlist, ci) == -1) {
3371 goto error;
3372 }
3373 Py_CLEAR(ci);
3374 }
3375 return rlist;
3376
3377 error:
3378 Py_XDECREF(ci);
3379 Py_XDECREF(rlist);
3380 return NULL;
3381}
3382
3383
3384static PyGetSetDef context_getsetlist[] = {
3385 {"check_hostname", (getter) get_check_hostname,
3386 (setter) set_check_hostname, NULL},
3387 {"options", (getter) get_options,
3388 (setter) set_options, NULL},
3389#ifdef HAVE_OPENSSL_VERIFY_PARAM
3390 {"verify_flags", (getter) get_verify_flags,
3391 (setter) set_verify_flags, NULL},
3392#endif
3393 {"verify_mode", (getter) get_verify_mode,
3394 (setter) set_verify_mode, NULL},
3395 {NULL}, /* sentinel */
3396};
3397
3398static struct PyMethodDef context_methods[] = {
3399 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3400 METH_VARARGS | METH_KEYWORDS, NULL},
3401 {"set_ciphers", (PyCFunction) set_ciphers,
3402 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003403 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3404 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003405 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3406 METH_VARARGS, NULL},
3407 {"load_cert_chain", (PyCFunction) load_cert_chain,
3408 METH_VARARGS | METH_KEYWORDS, NULL},
3409 {"load_dh_params", (PyCFunction) load_dh_params,
3410 METH_O, NULL},
3411 {"load_verify_locations", (PyCFunction) load_verify_locations,
3412 METH_VARARGS | METH_KEYWORDS, NULL},
3413 {"session_stats", (PyCFunction) session_stats,
3414 METH_NOARGS, NULL},
3415 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3416 METH_NOARGS, NULL},
3417#ifndef OPENSSL_NO_ECDH
3418 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3419 METH_O, NULL},
3420#endif
3421 {"set_servername_callback", (PyCFunction) set_servername_callback,
3422 METH_VARARGS, PySSL_set_servername_callback_doc},
3423 {"cert_store_stats", (PyCFunction) cert_store_stats,
3424 METH_NOARGS, PySSL_get_stats_doc},
3425 {"get_ca_certs", (PyCFunction) get_ca_certs,
3426 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3427 {NULL, NULL} /* sentinel */
3428};
3429
3430static PyTypeObject PySSLContext_Type = {
3431 PyVarObject_HEAD_INIT(NULL, 0)
3432 "_ssl._SSLContext", /*tp_name*/
3433 sizeof(PySSLContext), /*tp_basicsize*/
3434 0, /*tp_itemsize*/
3435 (destructor)context_dealloc, /*tp_dealloc*/
3436 0, /*tp_print*/
3437 0, /*tp_getattr*/
3438 0, /*tp_setattr*/
3439 0, /*tp_reserved*/
3440 0, /*tp_repr*/
3441 0, /*tp_as_number*/
3442 0, /*tp_as_sequence*/
3443 0, /*tp_as_mapping*/
3444 0, /*tp_hash*/
3445 0, /*tp_call*/
3446 0, /*tp_str*/
3447 0, /*tp_getattro*/
3448 0, /*tp_setattro*/
3449 0, /*tp_as_buffer*/
3450 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3451 0, /*tp_doc*/
3452 (traverseproc) context_traverse, /*tp_traverse*/
3453 (inquiry) context_clear, /*tp_clear*/
3454 0, /*tp_richcompare*/
3455 0, /*tp_weaklistoffset*/
3456 0, /*tp_iter*/
3457 0, /*tp_iternext*/
3458 context_methods, /*tp_methods*/
3459 0, /*tp_members*/
3460 context_getsetlist, /*tp_getset*/
3461 0, /*tp_base*/
3462 0, /*tp_dict*/
3463 0, /*tp_descr_get*/
3464 0, /*tp_descr_set*/
3465 0, /*tp_dictoffset*/
3466 0, /*tp_init*/
3467 0, /*tp_alloc*/
3468 context_new, /*tp_new*/
3469};
3470
3471
3472
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003473#ifdef HAVE_OPENSSL_RAND
3474
3475/* helper routines for seeding the SSL PRNG */
3476static PyObject *
3477PySSL_RAND_add(PyObject *self, PyObject *args)
3478{
3479 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003480 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003481 double entropy;
3482
3483 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003484 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003485 do {
3486 if (len >= INT_MAX) {
3487 written = INT_MAX;
3488 } else {
3489 written = len;
3490 }
3491 RAND_add(buf, (int)written, entropy);
3492 buf += written;
3493 len -= written;
3494 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003495 Py_INCREF(Py_None);
3496 return Py_None;
3497}
3498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003499PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003500"RAND_add(string, entropy)\n\
3501\n\
3502Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003503bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003504
3505static PyObject *
3506PySSL_RAND_status(PyObject *self)
3507{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003508 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003509}
3510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003511PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003512"RAND_status() -> 0 or 1\n\
3513\n\
3514Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3515It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003516using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003517
Victor Stinner7c906672015-01-06 13:53:37 +01003518#endif /* HAVE_OPENSSL_RAND */
3519
3520
Benjamin Peterson42e10292016-07-07 00:02:31 -07003521#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003522
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003523static PyObject *
3524PySSL_RAND_egd(PyObject *self, PyObject *arg)
3525{
3526 int bytes;
3527
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003528 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003529 return PyErr_Format(PyExc_TypeError,
3530 "RAND_egd() expected string, found %s",
3531 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003532 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003533 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003534 PyErr_SetString(PySSLErrorObject,
3535 "EGD connection failed or EGD did not return "
3536 "enough data to seed the PRNG");
3537 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003538 }
3539 return PyInt_FromLong(bytes);
3540}
3541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003542PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003543"RAND_egd(path) -> bytes\n\
3544\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003545Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3546Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003547fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003548
Benjamin Peterson42e10292016-07-07 00:02:31 -07003549#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003550
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003551
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003552PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3553"get_default_verify_paths() -> tuple\n\
3554\n\
3555Return search paths and environment vars that are used by SSLContext's\n\
3556set_default_verify_paths() to load default CAs. The values are\n\
3557'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3558
3559static PyObject *
3560PySSL_get_default_verify_paths(PyObject *self)
3561{
3562 PyObject *ofile_env = NULL;
3563 PyObject *ofile = NULL;
3564 PyObject *odir_env = NULL;
3565 PyObject *odir = NULL;
3566
Benjamin Peterson65192c12015-07-18 10:59:13 -07003567#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003568 const char *tmp = (info); \
3569 target = NULL; \
3570 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3571 else { target = PyBytes_FromString(tmp); } \
3572 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003573 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003574
Benjamin Peterson65192c12015-07-18 10:59:13 -07003575 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3576 CONVERT(X509_get_default_cert_file(), ofile);
3577 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3578 CONVERT(X509_get_default_cert_dir(), odir);
3579#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003580
3581 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3582
3583 error:
3584 Py_XDECREF(ofile_env);
3585 Py_XDECREF(ofile);
3586 Py_XDECREF(odir_env);
3587 Py_XDECREF(odir);
3588 return NULL;
3589}
3590
3591static PyObject*
3592asn1obj2py(ASN1_OBJECT *obj)
3593{
3594 int nid;
3595 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003596
3597 nid = OBJ_obj2nid(obj);
3598 if (nid == NID_undef) {
3599 PyErr_Format(PyExc_ValueError, "Unknown object");
3600 return NULL;
3601 }
3602 sn = OBJ_nid2sn(nid);
3603 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003604 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003605}
3606
3607PyDoc_STRVAR(PySSL_txt2obj_doc,
3608"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3609\n\
3610Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3611objects are looked up by OID. With name=True short and long name are also\n\
3612matched.");
3613
3614static PyObject*
3615PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3616{
3617 char *kwlist[] = {"txt", "name", NULL};
3618 PyObject *result = NULL;
3619 char *txt;
3620 PyObject *pyname = Py_None;
3621 int name = 0;
3622 ASN1_OBJECT *obj;
3623
3624 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3625 kwlist, &txt, &pyname)) {
3626 return NULL;
3627 }
3628 name = PyObject_IsTrue(pyname);
3629 if (name < 0)
3630 return NULL;
3631 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3632 if (obj == NULL) {
3633 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3634 return NULL;
3635 }
3636 result = asn1obj2py(obj);
3637 ASN1_OBJECT_free(obj);
3638 return result;
3639}
3640
3641PyDoc_STRVAR(PySSL_nid2obj_doc,
3642"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3643\n\
3644Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3645
3646static PyObject*
3647PySSL_nid2obj(PyObject *self, PyObject *args)
3648{
3649 PyObject *result = NULL;
3650 int nid;
3651 ASN1_OBJECT *obj;
3652
3653 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3654 return NULL;
3655 }
3656 if (nid < NID_undef) {
3657 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3658 return NULL;
3659 }
3660 obj = OBJ_nid2obj(nid);
3661 if (obj == NULL) {
3662 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3663 return NULL;
3664 }
3665 result = asn1obj2py(obj);
3666 ASN1_OBJECT_free(obj);
3667 return result;
3668}
3669
3670#ifdef _MSC_VER
3671
3672static PyObject*
3673certEncodingType(DWORD encodingType)
3674{
3675 static PyObject *x509_asn = NULL;
3676 static PyObject *pkcs_7_asn = NULL;
3677
3678 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003679 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003680 if (x509_asn == NULL)
3681 return NULL;
3682 }
3683 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003684 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003685 if (pkcs_7_asn == NULL)
3686 return NULL;
3687 }
3688 switch(encodingType) {
3689 case X509_ASN_ENCODING:
3690 Py_INCREF(x509_asn);
3691 return x509_asn;
3692 case PKCS_7_ASN_ENCODING:
3693 Py_INCREF(pkcs_7_asn);
3694 return pkcs_7_asn;
3695 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003696 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003697 }
3698}
3699
3700static PyObject*
3701parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3702{
3703 CERT_ENHKEY_USAGE *usage;
3704 DWORD size, error, i;
3705 PyObject *retval;
3706
3707 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3708 error = GetLastError();
3709 if (error == CRYPT_E_NOT_FOUND) {
3710 Py_RETURN_TRUE;
3711 }
3712 return PyErr_SetFromWindowsErr(error);
3713 }
3714
3715 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3716 if (usage == NULL) {
3717 return PyErr_NoMemory();
3718 }
3719
3720 /* Now get the actual enhanced usage property */
3721 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3722 PyMem_Free(usage);
3723 error = GetLastError();
3724 if (error == CRYPT_E_NOT_FOUND) {
3725 Py_RETURN_TRUE;
3726 }
3727 return PyErr_SetFromWindowsErr(error);
3728 }
3729 retval = PySet_New(NULL);
3730 if (retval == NULL) {
3731 goto error;
3732 }
3733 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3734 if (usage->rgpszUsageIdentifier[i]) {
3735 PyObject *oid;
3736 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003737 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003738 if (oid == NULL) {
3739 Py_CLEAR(retval);
3740 goto error;
3741 }
3742 err = PySet_Add(retval, oid);
3743 Py_DECREF(oid);
3744 if (err == -1) {
3745 Py_CLEAR(retval);
3746 goto error;
3747 }
3748 }
3749 }
3750 error:
3751 PyMem_Free(usage);
3752 return retval;
3753}
3754
3755PyDoc_STRVAR(PySSL_enum_certificates_doc,
3756"enum_certificates(store_name) -> []\n\
3757\n\
3758Retrieve certificates from Windows' cert store. store_name may be one of\n\
3759'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3760The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3761encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3762PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3763boolean True.");
3764
3765static PyObject *
3766PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3767{
3768 char *kwlist[] = {"store_name", NULL};
3769 char *store_name;
3770 HCERTSTORE hStore = NULL;
3771 PCCERT_CONTEXT pCertCtx = NULL;
3772 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3773 PyObject *result = NULL;
3774
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003775 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003776 kwlist, &store_name)) {
3777 return NULL;
3778 }
3779 result = PyList_New(0);
3780 if (result == NULL) {
3781 return NULL;
3782 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003783 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3784 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3785 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003786 if (hStore == NULL) {
3787 Py_DECREF(result);
3788 return PyErr_SetFromWindowsErr(GetLastError());
3789 }
3790
3791 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3792 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3793 pCertCtx->cbCertEncoded);
3794 if (!cert) {
3795 Py_CLEAR(result);
3796 break;
3797 }
3798 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3799 Py_CLEAR(result);
3800 break;
3801 }
3802 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3803 if (keyusage == Py_True) {
3804 Py_DECREF(keyusage);
3805 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3806 }
3807 if (keyusage == NULL) {
3808 Py_CLEAR(result);
3809 break;
3810 }
3811 if ((tup = PyTuple_New(3)) == NULL) {
3812 Py_CLEAR(result);
3813 break;
3814 }
3815 PyTuple_SET_ITEM(tup, 0, cert);
3816 cert = NULL;
3817 PyTuple_SET_ITEM(tup, 1, enc);
3818 enc = NULL;
3819 PyTuple_SET_ITEM(tup, 2, keyusage);
3820 keyusage = NULL;
3821 if (PyList_Append(result, tup) < 0) {
3822 Py_CLEAR(result);
3823 break;
3824 }
3825 Py_CLEAR(tup);
3826 }
3827 if (pCertCtx) {
3828 /* loop ended with an error, need to clean up context manually */
3829 CertFreeCertificateContext(pCertCtx);
3830 }
3831
3832 /* In error cases cert, enc and tup may not be NULL */
3833 Py_XDECREF(cert);
3834 Py_XDECREF(enc);
3835 Py_XDECREF(keyusage);
3836 Py_XDECREF(tup);
3837
3838 if (!CertCloseStore(hStore, 0)) {
3839 /* This error case might shadow another exception.*/
3840 Py_XDECREF(result);
3841 return PyErr_SetFromWindowsErr(GetLastError());
3842 }
3843 return result;
3844}
3845
3846PyDoc_STRVAR(PySSL_enum_crls_doc,
3847"enum_crls(store_name) -> []\n\
3848\n\
3849Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3850'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3851The function returns a list of (bytes, encoding_type) tuples. The\n\
3852encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3853PKCS_7_ASN_ENCODING.");
3854
3855static PyObject *
3856PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3857{
3858 char *kwlist[] = {"store_name", NULL};
3859 char *store_name;
3860 HCERTSTORE hStore = NULL;
3861 PCCRL_CONTEXT pCrlCtx = NULL;
3862 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3863 PyObject *result = NULL;
3864
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003865 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003866 kwlist, &store_name)) {
3867 return NULL;
3868 }
3869 result = PyList_New(0);
3870 if (result == NULL) {
3871 return NULL;
3872 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003873 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3874 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3875 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003876 if (hStore == NULL) {
3877 Py_DECREF(result);
3878 return PyErr_SetFromWindowsErr(GetLastError());
3879 }
3880
3881 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3882 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3883 pCrlCtx->cbCrlEncoded);
3884 if (!crl) {
3885 Py_CLEAR(result);
3886 break;
3887 }
3888 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3889 Py_CLEAR(result);
3890 break;
3891 }
3892 if ((tup = PyTuple_New(2)) == NULL) {
3893 Py_CLEAR(result);
3894 break;
3895 }
3896 PyTuple_SET_ITEM(tup, 0, crl);
3897 crl = NULL;
3898 PyTuple_SET_ITEM(tup, 1, enc);
3899 enc = NULL;
3900
3901 if (PyList_Append(result, tup) < 0) {
3902 Py_CLEAR(result);
3903 break;
3904 }
3905 Py_CLEAR(tup);
3906 }
3907 if (pCrlCtx) {
3908 /* loop ended with an error, need to clean up context manually */
3909 CertFreeCRLContext(pCrlCtx);
3910 }
3911
3912 /* In error cases cert, enc and tup may not be NULL */
3913 Py_XDECREF(crl);
3914 Py_XDECREF(enc);
3915 Py_XDECREF(tup);
3916
3917 if (!CertCloseStore(hStore, 0)) {
3918 /* This error case might shadow another exception.*/
3919 Py_XDECREF(result);
3920 return PyErr_SetFromWindowsErr(GetLastError());
3921 }
3922 return result;
3923}
3924
3925#endif /* _MSC_VER */
3926
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003927/* List of functions exported by this module. */
3928
3929static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003930 {"_test_decode_cert", PySSL_test_decode_certificate,
3931 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003932#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003933 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3934 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003935 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3936 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003937#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003938#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003939 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3940 PySSL_RAND_egd_doc},
3941#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003942 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3943 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3944#ifdef _MSC_VER
3945 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3946 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3947 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3948 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3949#endif
3950 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3951 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3952 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3953 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003954 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003955};
3956
3957
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003958#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003959
3960/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003961 * of the Python C thread library
3962 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3963 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003964
3965static PyThread_type_lock *_ssl_locks = NULL;
3966
Christian Heimes10107812013-08-19 17:36:29 +02003967#if OPENSSL_VERSION_NUMBER >= 0x10000000
3968/* use new CRYPTO_THREADID API. */
3969static void
3970_ssl_threadid_callback(CRYPTO_THREADID *id)
3971{
3972 CRYPTO_THREADID_set_numeric(id,
3973 (unsigned long)PyThread_get_thread_ident());
3974}
3975#else
3976/* deprecated CRYPTO_set_id_callback() API. */
3977static unsigned long
3978_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003979 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003980}
Christian Heimes10107812013-08-19 17:36:29 +02003981#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003982
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003983static void _ssl_thread_locking_function
3984 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003985 /* this function is needed to perform locking on shared data
3986 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003987 structures that will be implicitly shared whenever multiple
3988 threads use OpenSSL.) Multi-threaded applications will
3989 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003990
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003991 locking_function() must be able to handle up to
3992 CRYPTO_num_locks() different mutex locks. It sets the n-th
3993 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003994
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003995 file and line are the file number of the function setting the
3996 lock. They can be useful for debugging.
3997 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003998
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003999 if ((_ssl_locks == NULL) ||
4000 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4001 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004002
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004003 if (mode & CRYPTO_LOCK) {
4004 PyThread_acquire_lock(_ssl_locks[n], 1);
4005 } else {
4006 PyThread_release_lock(_ssl_locks[n]);
4007 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004008}
4009
4010static int _setup_ssl_threads(void) {
4011
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004012 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004013
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004014 if (_ssl_locks == NULL) {
4015 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004016 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4017 if (_ssl_locks == NULL) {
4018 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004019 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004020 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004021 memset(_ssl_locks, 0,
4022 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004023 for (i = 0; i < _ssl_locks_count; i++) {
4024 _ssl_locks[i] = PyThread_allocate_lock();
4025 if (_ssl_locks[i] == NULL) {
4026 unsigned int j;
4027 for (j = 0; j < i; j++) {
4028 PyThread_free_lock(_ssl_locks[j]);
4029 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004030 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004031 return 0;
4032 }
4033 }
4034 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004035#if OPENSSL_VERSION_NUMBER >= 0x10000000
4036 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4037#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004038 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004039#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004040 }
4041 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004042}
4043
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004044#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004046PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004047"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004048for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004049
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004050
4051
4052
4053static void
4054parse_openssl_version(unsigned long libver,
4055 unsigned int *major, unsigned int *minor,
4056 unsigned int *fix, unsigned int *patch,
4057 unsigned int *status)
4058{
4059 *status = libver & 0xF;
4060 libver >>= 4;
4061 *patch = libver & 0xFF;
4062 libver >>= 8;
4063 *fix = libver & 0xFF;
4064 libver >>= 8;
4065 *minor = libver & 0xFF;
4066 libver >>= 8;
4067 *major = libver & 0xFF;
4068}
4069
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004070PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004071init_ssl(void)
4072{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004073 PyObject *m, *d, *r;
4074 unsigned long libver;
4075 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004076 struct py_ssl_error_code *errcode;
4077 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004078
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004079 if (PyType_Ready(&PySSLContext_Type) < 0)
4080 return;
4081 if (PyType_Ready(&PySSLSocket_Type) < 0)
4082 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004083
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004084 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4085 if (m == NULL)
4086 return;
4087 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004088
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004089 /* Load _socket module and its C API */
4090 if (PySocketModule_ImportModuleAndAPI())
4091 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004092
Christian Heimes7daa45d2017-09-05 17:12:12 +02004093#ifndef OPENSSL_VERSION_1_1
4094 /* Load all algorithms and initialize cpuid */
4095 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004096 /* Init OpenSSL */
4097 SSL_load_error_strings();
4098 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004099#endif
4100
Bill Janssen98d19da2007-09-10 21:51:02 +00004101#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004102#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004103 /* note that this will start threading if not already started */
4104 if (!_setup_ssl_threads()) {
4105 return;
4106 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004107#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4108 /* OpenSSL 1.1.0 builtin thread support is enabled */
4109 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004110#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004111#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004112
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004113 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004114 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4115 "ssl.SSLError", SSLError_doc,
4116 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004117 if (PySSLErrorObject == NULL)
4118 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004119 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4120
4121 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4122 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4123 PySSLErrorObject, NULL);
4124 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4125 "ssl.SSLWantReadError", SSLWantReadError_doc,
4126 PySSLErrorObject, NULL);
4127 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4128 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4129 PySSLErrorObject, NULL);
4130 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4131 "ssl.SSLSyscallError", SSLSyscallError_doc,
4132 PySSLErrorObject, NULL);
4133 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4134 "ssl.SSLEOFError", SSLEOFError_doc,
4135 PySSLErrorObject, NULL);
4136 if (PySSLZeroReturnErrorObject == NULL
4137 || PySSLWantReadErrorObject == NULL
4138 || PySSLWantWriteErrorObject == NULL
4139 || PySSLSyscallErrorObject == NULL
4140 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004141 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004142
4143 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4144 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4145 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4146 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4147 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4148
4149 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4150 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4151 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4152 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4153 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4154 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4155 return;
4156 if (PyDict_SetItemString(d, "_SSLContext",
4157 (PyObject *)&PySSLContext_Type) != 0)
4158 return;
4159 if (PyDict_SetItemString(d, "_SSLSocket",
4160 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004161 return;
4162 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4163 PY_SSL_ERROR_ZERO_RETURN);
4164 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4165 PY_SSL_ERROR_WANT_READ);
4166 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4167 PY_SSL_ERROR_WANT_WRITE);
4168 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4169 PY_SSL_ERROR_WANT_X509_LOOKUP);
4170 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4171 PY_SSL_ERROR_SYSCALL);
4172 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4173 PY_SSL_ERROR_SSL);
4174 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4175 PY_SSL_ERROR_WANT_CONNECT);
4176 /* non ssl.h errorcodes */
4177 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4178 PY_SSL_ERROR_EOF);
4179 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4180 PY_SSL_ERROR_INVALID_ERROR_CODE);
4181 /* cert requirements */
4182 PyModule_AddIntConstant(m, "CERT_NONE",
4183 PY_SSL_CERT_NONE);
4184 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4185 PY_SSL_CERT_OPTIONAL);
4186 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4187 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004188 /* CRL verification for verification_flags */
4189 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4190 0);
4191 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4192 X509_V_FLAG_CRL_CHECK);
4193 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4194 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4195 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4196 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004197#ifdef X509_V_FLAG_TRUSTED_FIRST
4198 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4199 X509_V_FLAG_TRUSTED_FIRST);
4200#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004201
4202 /* Alert Descriptions from ssl.h */
4203 /* note RESERVED constants no longer intended for use have been removed */
4204 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4205
4206#define ADD_AD_CONSTANT(s) \
4207 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4208 SSL_AD_##s)
4209
4210 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4211 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4212 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4213 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4214 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4215 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4216 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4217 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4218 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4219 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4220 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4221 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4222 ADD_AD_CONSTANT(UNKNOWN_CA);
4223 ADD_AD_CONSTANT(ACCESS_DENIED);
4224 ADD_AD_CONSTANT(DECODE_ERROR);
4225 ADD_AD_CONSTANT(DECRYPT_ERROR);
4226 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4227 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4228 ADD_AD_CONSTANT(INTERNAL_ERROR);
4229 ADD_AD_CONSTANT(USER_CANCELLED);
4230 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4231 /* Not all constants are in old OpenSSL versions */
4232#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4233 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4234#endif
4235#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4236 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4237#endif
4238#ifdef SSL_AD_UNRECOGNIZED_NAME
4239 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4240#endif
4241#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4242 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4243#endif
4244#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4245 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4246#endif
4247#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4248 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4249#endif
4250
4251#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004252
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004253 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004254#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004255 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4256 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004257#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004258#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004259 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4260 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004261#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004262 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004263 PY_SSL_VERSION_TLS);
4264 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4265 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004266 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4267 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004268#if HAVE_TLSv1_2
4269 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4270 PY_SSL_VERSION_TLS1_1);
4271 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4272 PY_SSL_VERSION_TLS1_2);
4273#endif
4274
4275 /* protocol options */
4276 PyModule_AddIntConstant(m, "OP_ALL",
4277 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4278 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4279 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4280 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4281#if HAVE_TLSv1_2
4282 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4283 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4284#endif
4285 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4286 SSL_OP_CIPHER_SERVER_PREFERENCE);
4287 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4288#ifdef SSL_OP_SINGLE_ECDH_USE
4289 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4290#endif
4291#ifdef SSL_OP_NO_COMPRESSION
4292 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4293 SSL_OP_NO_COMPRESSION);
4294#endif
4295
4296#if HAVE_SNI
4297 r = Py_True;
4298#else
4299 r = Py_False;
4300#endif
4301 Py_INCREF(r);
4302 PyModule_AddObject(m, "HAS_SNI", r);
4303
4304#if HAVE_OPENSSL_FINISHED
4305 r = Py_True;
4306#else
4307 r = Py_False;
4308#endif
4309 Py_INCREF(r);
4310 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4311
4312#ifdef OPENSSL_NO_ECDH
4313 r = Py_False;
4314#else
4315 r = Py_True;
4316#endif
4317 Py_INCREF(r);
4318 PyModule_AddObject(m, "HAS_ECDH", r);
4319
Christian Heimes72ed2332017-09-05 01:11:40 +02004320#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004321 r = Py_True;
4322#else
4323 r = Py_False;
4324#endif
4325 Py_INCREF(r);
4326 PyModule_AddObject(m, "HAS_NPN", r);
4327
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004328#ifdef HAVE_ALPN
4329 r = Py_True;
4330#else
4331 r = Py_False;
4332#endif
4333 Py_INCREF(r);
4334 PyModule_AddObject(m, "HAS_ALPN", r);
4335
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004336 /* Mappings for error codes */
4337 err_codes_to_names = PyDict_New();
4338 err_names_to_codes = PyDict_New();
4339 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4340 return;
4341 errcode = error_codes;
4342 while (errcode->mnemonic != NULL) {
4343 PyObject *mnemo, *key;
4344 mnemo = PyUnicode_FromString(errcode->mnemonic);
4345 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4346 if (mnemo == NULL || key == NULL)
4347 return;
4348 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4349 return;
4350 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4351 return;
4352 Py_DECREF(key);
4353 Py_DECREF(mnemo);
4354 errcode++;
4355 }
4356 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4357 return;
4358 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4359 return;
4360
4361 lib_codes_to_names = PyDict_New();
4362 if (lib_codes_to_names == NULL)
4363 return;
4364 libcode = library_codes;
4365 while (libcode->library != NULL) {
4366 PyObject *mnemo, *key;
4367 key = PyLong_FromLong(libcode->code);
4368 mnemo = PyUnicode_FromString(libcode->library);
4369 if (key == NULL || mnemo == NULL)
4370 return;
4371 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4372 return;
4373 Py_DECREF(key);
4374 Py_DECREF(mnemo);
4375 libcode++;
4376 }
4377 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4378 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004379
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004380 /* OpenSSL version */
4381 /* SSLeay() gives us the version of the library linked against,
4382 which could be different from the headers version.
4383 */
4384 libver = SSLeay();
4385 r = PyLong_FromUnsignedLong(libver);
4386 if (r == NULL)
4387 return;
4388 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4389 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004390 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004391 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4392 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4393 return;
4394 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4395 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4396 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004397
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004398 libver = OPENSSL_VERSION_NUMBER;
4399 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4400 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4401 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4402 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004403}