blob: d1f790032801ba9b9d730bd45d27ad2e45d471cd [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}
151
152static const char *COMP_get_name(const COMP_METHOD *meth)
153{
154 return meth->name;
155}
156#endif
157
158static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
159{
160 return ctx->default_passwd_callback;
161}
162
163static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
164{
165 return ctx->default_passwd_callback_userdata;
166}
167
168static int X509_OBJECT_get_type(X509_OBJECT *x)
169{
170 return x->type;
171}
172
173static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
174{
175 return x->data.x509;
176}
177
178static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
179 return store->objs;
180}
181
182static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
183{
184 return store->param;
185}
186#endif /* OpenSSL < 1.1.0 or LibreSSL */
187
188
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500189enum py_ssl_error {
190 /* these mirror ssl.h */
191 PY_SSL_ERROR_NONE,
192 PY_SSL_ERROR_SSL,
193 PY_SSL_ERROR_WANT_READ,
194 PY_SSL_ERROR_WANT_WRITE,
195 PY_SSL_ERROR_WANT_X509_LOOKUP,
196 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
197 PY_SSL_ERROR_ZERO_RETURN,
198 PY_SSL_ERROR_WANT_CONNECT,
199 /* start of non ssl.h errorcodes */
200 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
201 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
202 PY_SSL_ERROR_INVALID_ERROR_CODE
203};
204
205enum py_ssl_server_or_client {
206 PY_SSL_CLIENT,
207 PY_SSL_SERVER
208};
209
210enum py_ssl_cert_requirements {
211 PY_SSL_CERT_NONE,
212 PY_SSL_CERT_OPTIONAL,
213 PY_SSL_CERT_REQUIRED
214};
215
216enum py_ssl_version {
217 PY_SSL_VERSION_SSL2,
218 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200219 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500220#if HAVE_TLSv1_2
221 PY_SSL_VERSION_TLS1,
222 PY_SSL_VERSION_TLS1_1,
223 PY_SSL_VERSION_TLS1_2
224#else
225 PY_SSL_VERSION_TLS1
226#endif
227};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000228
Bill Janssen98d19da2007-09-10 21:51:02 +0000229#ifdef WITH_THREAD
230
231/* serves as a flag to see whether we've initialized the SSL thread support. */
232/* 0 means no, greater than 0 means yes */
233
234static unsigned int _ssl_locks_count = 0;
235
236#endif /* def WITH_THREAD */
237
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238/* SSL socket object */
239
240#define X509_NAME_MAXLEN 256
241
242/* RAND_* APIs got added to OpenSSL in 0.9.5 */
243#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
244# define HAVE_OPENSSL_RAND 1
245#else
246# undef HAVE_OPENSSL_RAND
247#endif
248
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500249/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
250 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
251 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
252#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
253# define HAVE_SSL_CTX_CLEAR_OPTIONS
254#else
255# undef HAVE_SSL_CTX_CLEAR_OPTIONS
256#endif
257
258/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
259 * older SSL, but let's be safe */
260#define PySSL_CB_MAXLEN 128
261
262/* SSL_get_finished got added to OpenSSL in 0.9.5 */
263#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
264# define HAVE_OPENSSL_FINISHED 1
265#else
266# define HAVE_OPENSSL_FINISHED 0
267#endif
268
269/* ECDH support got added to OpenSSL in 0.9.8 */
270#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
271# define OPENSSL_NO_ECDH
272#endif
273
274/* compression support got added to OpenSSL in 0.9.8 */
275#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
276# define OPENSSL_NO_COMP
277#endif
278
279/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
280#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
281# define HAVE_OPENSSL_VERIFY_PARAM
282#endif
283
284
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000285typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000286 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500287 SSL_CTX *ctx;
288#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500289 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500290 int npn_protocols_len;
291#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500292#ifdef HAVE_ALPN
293 unsigned char *alpn_protocols;
294 int alpn_protocols_len;
295#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500296#ifndef OPENSSL_NO_TLSEXT
297 PyObject *set_hostname;
298#endif
299 int check_hostname;
300} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000301
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500302typedef struct {
303 PyObject_HEAD
304 PySocketSockObject *Socket;
305 PyObject *ssl_sock;
306 SSL *ssl;
307 PySSLContext *ctx; /* weakref to SSL context */
308 X509 *peer_cert;
309 char shutdown_seen_zero;
310 char handshake_done;
311 enum py_ssl_server_or_client socket_type;
312} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500314static PyTypeObject PySSLContext_Type;
315static PyTypeObject PySSLSocket_Type;
316
317static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
318static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000319static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000320 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500321static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
322static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000323
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500324#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
325#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000327typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000328 SOCKET_IS_NONBLOCKING,
329 SOCKET_IS_BLOCKING,
330 SOCKET_HAS_TIMED_OUT,
331 SOCKET_HAS_BEEN_CLOSED,
332 SOCKET_TOO_LARGE_FOR_SELECT,
333 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000334} timeout_state;
335
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000336/* Wrap error strings with filename and line # */
337#define STRINGIFY1(x) #x
338#define STRINGIFY2(x) STRINGIFY1(x)
339#define ERRSTR1(x,y,z) (x ":" y ": " z)
340#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
341
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500342
343/*
344 * SSL errors.
345 */
346
347PyDoc_STRVAR(SSLError_doc,
348"An error occurred in the SSL implementation.");
349
350PyDoc_STRVAR(SSLZeroReturnError_doc,
351"SSL/TLS session closed cleanly.");
352
353PyDoc_STRVAR(SSLWantReadError_doc,
354"Non-blocking SSL socket needs to read more data\n"
355"before the requested operation can be completed.");
356
357PyDoc_STRVAR(SSLWantWriteError_doc,
358"Non-blocking SSL socket needs to write more data\n"
359"before the requested operation can be completed.");
360
361PyDoc_STRVAR(SSLSyscallError_doc,
362"System error when attempting SSL operation.");
363
364PyDoc_STRVAR(SSLEOFError_doc,
365"SSL/TLS connection terminated abruptly.");
366
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000367
368static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500369SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000370{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500371 if (self->strerror != NULL) {
372 Py_INCREF(self->strerror);
373 return self->strerror;
374 }
375 else
376 return PyObject_Str(self->args);
377}
378
379static void
380fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
381 int lineno, unsigned long errcode)
382{
383 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
384 PyObject *init_value, *msg, *key;
385
386 if (errcode != 0) {
387 int lib, reason;
388
389 lib = ERR_GET_LIB(errcode);
390 reason = ERR_GET_REASON(errcode);
391 key = Py_BuildValue("ii", lib, reason);
392 if (key == NULL)
393 goto fail;
394 reason_obj = PyDict_GetItem(err_codes_to_names, key);
395 Py_DECREF(key);
396 if (reason_obj == NULL) {
397 /* XXX if reason < 100, it might reflect a library number (!!) */
398 PyErr_Clear();
399 }
400 key = PyLong_FromLong(lib);
401 if (key == NULL)
402 goto fail;
403 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
404 Py_DECREF(key);
405 if (lib_obj == NULL) {
406 PyErr_Clear();
407 }
408 if (errstr == NULL)
409 errstr = ERR_reason_error_string(errcode);
410 }
411 if (errstr == NULL)
412 errstr = "unknown error";
413
414 if (reason_obj && lib_obj)
415 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
416 lib_obj, reason_obj, errstr, lineno);
417 else if (lib_obj)
418 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
419 lib_obj, errstr, lineno);
420 else
421 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
422 if (msg == NULL)
423 goto fail;
424
425 init_value = Py_BuildValue("iN", ssl_errno, msg);
426 if (init_value == NULL)
427 goto fail;
428
429 err_value = PyObject_CallObject(type, init_value);
430 Py_DECREF(init_value);
431 if (err_value == NULL)
432 goto fail;
433
434 if (reason_obj == NULL)
435 reason_obj = Py_None;
436 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
437 goto fail;
438 if (lib_obj == NULL)
439 lib_obj = Py_None;
440 if (PyObject_SetAttrString(err_value, "library", lib_obj))
441 goto fail;
442 PyErr_SetObject(type, err_value);
443fail:
444 Py_XDECREF(err_value);
445}
446
447static PyObject *
448PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
449{
450 PyObject *type = PySSLErrorObject;
451 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000452 int err;
453 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500454 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000456 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500457 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000458
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000459 if (obj->ssl != NULL) {
460 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000461
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000462 switch (err) {
463 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500464 errstr = "TLS/SSL connection has been closed (EOF)";
465 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000466 p = PY_SSL_ERROR_ZERO_RETURN;
467 break;
468 case SSL_ERROR_WANT_READ:
469 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500470 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000471 p = PY_SSL_ERROR_WANT_READ;
472 break;
473 case SSL_ERROR_WANT_WRITE:
474 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500475 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000476 errstr = "The operation did not complete (write)";
477 break;
478 case SSL_ERROR_WANT_X509_LOOKUP:
479 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000480 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000481 break;
482 case SSL_ERROR_WANT_CONNECT:
483 p = PY_SSL_ERROR_WANT_CONNECT;
484 errstr = "The operation did not complete (connect)";
485 break;
486 case SSL_ERROR_SYSCALL:
487 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000488 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500489 PySocketSockObject *s = obj->Socket;
490 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000491 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500492 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000493 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000494 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000495 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500496 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000497 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500498 s->errorhandler();
499 Py_DECREF(s);
500 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000501 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000502 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500503 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000504 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000505 }
506 } else {
507 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000508 }
509 break;
510 }
511 case SSL_ERROR_SSL:
512 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000513 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500514 if (e == 0)
515 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000516 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000517 break;
518 }
519 default:
520 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
521 errstr = "Invalid error code";
522 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000523 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500524 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000525 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000526 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000527}
528
Bill Janssen98d19da2007-09-10 21:51:02 +0000529static PyObject *
530_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
531
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500532 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000533 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500534 else
535 errcode = 0;
536 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000537 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000538 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000539}
540
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500541/*
542 * SSL objects
543 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000544
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500545static PySSLSocket *
546newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
547 enum py_ssl_server_or_client socket_type,
548 char *server_hostname, PyObject *ssl_sock)
549{
550 PySSLSocket *self;
551 SSL_CTX *ctx = sslctx->ctx;
552 long mode;
553
554 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000555 if (self == NULL)
556 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500557
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000558 self->peer_cert = NULL;
559 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000560 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500561 self->ssl_sock = NULL;
562 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200563 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500564 self->handshake_done = 0;
565 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000566
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000567 /* Make sure the SSL error state is initialized */
568 (void) ERR_get_state();
569 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000570
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000571 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500572 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000573 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500574 SSL_set_app_data(self->ssl,self);
575 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
576 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000577#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500578 mode |= SSL_MODE_AUTO_RETRY;
579#endif
580 SSL_set_mode(self->ssl, mode);
581
582#if HAVE_SNI
583 if (server_hostname != NULL)
584 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000585#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000586
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000587 /* If the socket is in non-blocking mode or timeout mode, set the BIO
588 * to non-blocking mode (blocking is the default)
589 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500590 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000591 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
592 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
593 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000594
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000595 PySSL_BEGIN_ALLOW_THREADS
596 if (socket_type == PY_SSL_CLIENT)
597 SSL_set_connect_state(self->ssl);
598 else
599 SSL_set_accept_state(self->ssl);
600 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000601
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500602 self->socket_type = socket_type;
603 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000604 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400605 if (ssl_sock != Py_None) {
606 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
607 if (self->ssl_sock == NULL) {
608 Py_DECREF(self);
609 return NULL;
610 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500611 }
612 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613}
614
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000615
616/* SSL object methods */
617
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500618static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000619{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000620 int ret;
621 int err;
622 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500623 PySocketSockObject *sock = self->Socket;
624
625 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000626
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000627 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500628 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000629 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
630 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000631
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000632 /* Actually negotiate SSL connection */
633 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
634 do {
635 PySSL_BEGIN_ALLOW_THREADS
636 ret = SSL_do_handshake(self->ssl);
637 err = SSL_get_error(self->ssl, ret);
638 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500639 if (PyErr_CheckSignals())
640 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000641 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500642 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000643 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500644 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000645 } else {
646 sockstate = SOCKET_OPERATION_OK;
647 }
648 if (sockstate == SOCKET_HAS_TIMED_OUT) {
649 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000650 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500651 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000652 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
653 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000654 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500655 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000656 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
657 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000658 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500659 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000660 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
661 break;
662 }
663 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500664 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000665 if (ret < 1)
666 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000667
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000668 if (self->peer_cert)
669 X509_free (self->peer_cert);
670 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500671 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000672 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500673 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000674
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000675 Py_INCREF(Py_None);
676 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000677
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500678error:
679 Py_DECREF(sock);
680 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000681}
682
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000683static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000684_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000685
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000686 char namebuf[X509_NAME_MAXLEN];
687 int buflen;
688 PyObject *name_obj;
689 PyObject *value_obj;
690 PyObject *attr;
691 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000692
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000693 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
694 if (buflen < 0) {
695 _setSSLError(NULL, 0, __FILE__, __LINE__);
696 goto fail;
697 }
698 name_obj = PyString_FromStringAndSize(namebuf, buflen);
699 if (name_obj == NULL)
700 goto fail;
701
702 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
703 if (buflen < 0) {
704 _setSSLError(NULL, 0, __FILE__, __LINE__);
705 Py_DECREF(name_obj);
706 goto fail;
707 }
708 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000709 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000710 OPENSSL_free(valuebuf);
711 if (value_obj == NULL) {
712 Py_DECREF(name_obj);
713 goto fail;
714 }
715 attr = PyTuple_New(2);
716 if (attr == NULL) {
717 Py_DECREF(name_obj);
718 Py_DECREF(value_obj);
719 goto fail;
720 }
721 PyTuple_SET_ITEM(attr, 0, name_obj);
722 PyTuple_SET_ITEM(attr, 1, value_obj);
723 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000724
Bill Janssen98d19da2007-09-10 21:51:02 +0000725 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000726 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000727}
728
729static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000730_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000731{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000732 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
733 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
734 PyObject *rdnt;
735 PyObject *attr = NULL; /* tuple to hold an attribute */
736 int entry_count = X509_NAME_entry_count(xname);
737 X509_NAME_ENTRY *entry;
738 ASN1_OBJECT *name;
739 ASN1_STRING *value;
740 int index_counter;
741 int rdn_level = -1;
742 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000744 dn = PyList_New(0);
745 if (dn == NULL)
746 return NULL;
747 /* now create another tuple to hold the top-level RDN */
748 rdn = PyList_New(0);
749 if (rdn == NULL)
750 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000751
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000752 for (index_counter = 0;
753 index_counter < entry_count;
754 index_counter++)
755 {
756 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000757
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000758 /* check to see if we've gotten to a new RDN */
759 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200760 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000761 /* yes, new RDN */
762 /* add old RDN to DN */
763 rdnt = PyList_AsTuple(rdn);
764 Py_DECREF(rdn);
765 if (rdnt == NULL)
766 goto fail0;
767 retcode = PyList_Append(dn, rdnt);
768 Py_DECREF(rdnt);
769 if (retcode < 0)
770 goto fail0;
771 /* create new RDN */
772 rdn = PyList_New(0);
773 if (rdn == NULL)
774 goto fail0;
775 }
776 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200777 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000778
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000779 /* now add this attribute to the current RDN */
780 name = X509_NAME_ENTRY_get_object(entry);
781 value = X509_NAME_ENTRY_get_data(entry);
782 attr = _create_tuple_for_attribute(name, value);
783 /*
784 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
785 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500786 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
787 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000788 */
789 if (attr == NULL)
790 goto fail1;
791 retcode = PyList_Append(rdn, attr);
792 Py_DECREF(attr);
793 if (retcode < 0)
794 goto fail1;
795 }
796 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100797 if (rdn != NULL) {
798 if (PyList_GET_SIZE(rdn) > 0) {
799 rdnt = PyList_AsTuple(rdn);
800 Py_DECREF(rdn);
801 if (rdnt == NULL)
802 goto fail0;
803 retcode = PyList_Append(dn, rdnt);
804 Py_DECREF(rdnt);
805 if (retcode < 0)
806 goto fail0;
807 }
808 else {
809 Py_DECREF(rdn);
810 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000811 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000812
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000813 /* convert list to tuple */
814 rdnt = PyList_AsTuple(dn);
815 Py_DECREF(dn);
816 if (rdnt == NULL)
817 return NULL;
818 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000819
820 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000821 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000822
823 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000824 Py_XDECREF(dn);
825 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000826}
827
828static PyObject *
829_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000830
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000831 /* this code follows the procedure outlined in
832 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
833 function to extract the STACK_OF(GENERAL_NAME),
834 then iterates through the stack to add the
835 names. */
836
837 int i, j;
838 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200839 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000840 X509_EXTENSION *ext = NULL;
841 GENERAL_NAMES *names = NULL;
842 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000843 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000844 BIO *biobuf = NULL;
845 char buf[2048];
846 char *vptr;
847 int len;
848 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000849#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000850 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000851#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000852 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000853#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000854
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000855 if (certificate == NULL)
856 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000857
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000858 /* get a memory buffer */
859 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000860
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200861 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000862 while ((i = X509_get_ext_by_NID(
863 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000864
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000865 if (peer_alt_names == Py_None) {
866 peer_alt_names = PyList_New(0);
867 if (peer_alt_names == NULL)
868 goto fail;
869 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000870
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000871 /* now decode the altName */
872 ext = X509_get_ext(certificate, i);
873 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500874 PyErr_SetString
875 (PySSLErrorObject,
876 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000877 goto fail;
878 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000879
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200880 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000881 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500882 names = (GENERAL_NAMES*)
883 (ASN1_item_d2i(NULL,
884 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200885 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500886 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000887 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500888 names = (GENERAL_NAMES*)
889 (method->d2i(NULL,
890 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200891 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000893 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000894 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200895 int gntype;
896 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000897
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000898 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200899 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200900 switch (gntype) {
901 case GEN_DIRNAME:
902 /* we special-case DirName as a tuple of
903 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000904
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000905 t = PyTuple_New(2);
906 if (t == NULL) {
907 goto fail;
908 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000909
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000910 v = PyString_FromString("DirName");
911 if (v == NULL) {
912 Py_DECREF(t);
913 goto fail;
914 }
915 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000916
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000917 v = _create_tuple_for_X509_NAME (name->d.dirn);
918 if (v == NULL) {
919 Py_DECREF(t);
920 goto fail;
921 }
922 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200923 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000924
Christian Heimes88b174c2013-08-17 00:54:47 +0200925 case GEN_EMAIL:
926 case GEN_DNS:
927 case GEN_URI:
928 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
929 correctly, CVE-2013-4238 */
930 t = PyTuple_New(2);
931 if (t == NULL)
932 goto fail;
933 switch (gntype) {
934 case GEN_EMAIL:
935 v = PyString_FromString("email");
936 as = name->d.rfc822Name;
937 break;
938 case GEN_DNS:
939 v = PyString_FromString("DNS");
940 as = name->d.dNSName;
941 break;
942 case GEN_URI:
943 v = PyString_FromString("URI");
944 as = name->d.uniformResourceIdentifier;
945 break;
946 }
947 if (v == NULL) {
948 Py_DECREF(t);
949 goto fail;
950 }
951 PyTuple_SET_ITEM(t, 0, v);
952 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
953 ASN1_STRING_length(as));
954 if (v == NULL) {
955 Py_DECREF(t);
956 goto fail;
957 }
958 PyTuple_SET_ITEM(t, 1, v);
959 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000960
Christian Heimes88b174c2013-08-17 00:54:47 +0200961 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000962 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200963 switch (gntype) {
964 /* check for new general name type */
965 case GEN_OTHERNAME:
966 case GEN_X400:
967 case GEN_EDIPARTY:
968 case GEN_IPADD:
969 case GEN_RID:
970 break;
971 default:
972 if (PyErr_Warn(PyExc_RuntimeWarning,
973 "Unknown general name type") == -1) {
974 goto fail;
975 }
976 break;
977 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000978 (void) BIO_reset(biobuf);
979 GENERAL_NAME_print(biobuf, name);
980 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
981 if (len < 0) {
982 _setSSLError(NULL, 0, __FILE__, __LINE__);
983 goto fail;
984 }
985 vptr = strchr(buf, ':');
986 if (vptr == NULL)
987 goto fail;
988 t = PyTuple_New(2);
989 if (t == NULL)
990 goto fail;
991 v = PyString_FromStringAndSize(buf, (vptr - buf));
992 if (v == NULL) {
993 Py_DECREF(t);
994 goto fail;
995 }
996 PyTuple_SET_ITEM(t, 0, v);
997 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
998 if (v == NULL) {
999 Py_DECREF(t);
1000 goto fail;
1001 }
1002 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001003 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001004 }
1005
1006 /* and add that rendering to the list */
1007
1008 if (PyList_Append(peer_alt_names, t) < 0) {
1009 Py_DECREF(t);
1010 goto fail;
1011 }
1012 Py_DECREF(t);
1013 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001014 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001015 }
1016 BIO_free(biobuf);
1017 if (peer_alt_names != Py_None) {
1018 v = PyList_AsTuple(peer_alt_names);
1019 Py_DECREF(peer_alt_names);
1020 return v;
1021 } else {
1022 return peer_alt_names;
1023 }
1024
Bill Janssen98d19da2007-09-10 21:51:02 +00001025
1026 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001027 if (biobuf != NULL)
1028 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001029
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001030 if (peer_alt_names != Py_None) {
1031 Py_XDECREF(peer_alt_names);
1032 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001033
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001034 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001035}
1036
1037static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001038_get_aia_uri(X509 *certificate, int nid) {
1039 PyObject *lst = NULL, *ostr = NULL;
1040 int i, result;
1041 AUTHORITY_INFO_ACCESS *info;
1042
1043 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001044 if (info == NULL)
1045 return Py_None;
1046 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1047 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001048 return Py_None;
1049 }
1050
1051 if ((lst = PyList_New(0)) == NULL) {
1052 goto fail;
1053 }
1054
1055 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1056 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1057 ASN1_IA5STRING *uri;
1058
1059 if ((OBJ_obj2nid(ad->method) != nid) ||
1060 (ad->location->type != GEN_URI)) {
1061 continue;
1062 }
1063 uri = ad->location->d.uniformResourceIdentifier;
1064 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1065 uri->length);
1066 if (ostr == NULL) {
1067 goto fail;
1068 }
1069 result = PyList_Append(lst, ostr);
1070 Py_DECREF(ostr);
1071 if (result < 0) {
1072 goto fail;
1073 }
1074 }
1075 AUTHORITY_INFO_ACCESS_free(info);
1076
1077 /* convert to tuple or None */
1078 if (PyList_Size(lst) == 0) {
1079 Py_DECREF(lst);
1080 return Py_None;
1081 } else {
1082 PyObject *tup;
1083 tup = PyList_AsTuple(lst);
1084 Py_DECREF(lst);
1085 return tup;
1086 }
1087
1088 fail:
1089 AUTHORITY_INFO_ACCESS_free(info);
1090 Py_XDECREF(lst);
1091 return NULL;
1092}
1093
1094static PyObject *
1095_get_crl_dp(X509 *certificate) {
1096 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001097 int i, j;
1098 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001099
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001100#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001101 /* Calls x509v3_cache_extensions and sets up crldp */
1102 X509_check_ca(certificate);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001103#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001104 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001105
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001106 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001107 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001108
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001109 lst = PyList_New(0);
1110 if (lst == NULL)
1111 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001112
1113 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1114 DIST_POINT *dp;
1115 STACK_OF(GENERAL_NAME) *gns;
1116
1117 dp = sk_DIST_POINT_value(dps, i);
1118 gns = dp->distpoint->name.fullname;
1119
1120 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1121 GENERAL_NAME *gn;
1122 ASN1_IA5STRING *uri;
1123 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001124 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001125
1126 gn = sk_GENERAL_NAME_value(gns, j);
1127 if (gn->type != GEN_URI) {
1128 continue;
1129 }
1130 uri = gn->d.uniformResourceIdentifier;
1131 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1132 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001133 if (ouri == NULL)
1134 goto done;
1135
1136 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001137 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001138 if (err < 0)
1139 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001140 }
1141 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001142
1143 /* Convert to tuple. */
1144 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1145
1146 done:
1147 Py_XDECREF(lst);
1148#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersonb1c1e672015-11-14 00:09:22 -08001149 sk_DIST_POINT_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001150#endif
1151 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001152}
1153
1154static PyObject *
1155_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001156
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001157 PyObject *retval = NULL;
1158 BIO *biobuf = NULL;
1159 PyObject *peer;
1160 PyObject *peer_alt_names = NULL;
1161 PyObject *issuer;
1162 PyObject *version;
1163 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001164 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001165 ASN1_INTEGER *serialNumber;
1166 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001167 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001168 ASN1_TIME *notBefore, *notAfter;
1169 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001170
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001171 retval = PyDict_New();
1172 if (retval == NULL)
1173 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001174
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001175 peer = _create_tuple_for_X509_NAME(
1176 X509_get_subject_name(certificate));
1177 if (peer == NULL)
1178 goto fail0;
1179 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1180 Py_DECREF(peer);
1181 goto fail0;
1182 }
1183 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001184
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001185 issuer = _create_tuple_for_X509_NAME(
1186 X509_get_issuer_name(certificate));
1187 if (issuer == NULL)
1188 goto fail0;
1189 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001190 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001191 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001192 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001193 Py_DECREF(issuer);
1194
1195 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1196 if (version == NULL)
1197 goto fail0;
1198 if (PyDict_SetItemString(retval, "version", version) < 0) {
1199 Py_DECREF(version);
1200 goto fail0;
1201 }
1202 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001203
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001204 /* get a memory buffer */
1205 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001206
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001207 (void) BIO_reset(biobuf);
1208 serialNumber = X509_get_serialNumber(certificate);
1209 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1210 i2a_ASN1_INTEGER(biobuf, serialNumber);
1211 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1212 if (len < 0) {
1213 _setSSLError(NULL, 0, __FILE__, __LINE__);
1214 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001215 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001216 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1217 if (sn_obj == NULL)
1218 goto fail1;
1219 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1220 Py_DECREF(sn_obj);
1221 goto fail1;
1222 }
1223 Py_DECREF(sn_obj);
1224
1225 (void) BIO_reset(biobuf);
1226 notBefore = X509_get_notBefore(certificate);
1227 ASN1_TIME_print(biobuf, notBefore);
1228 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1229 if (len < 0) {
1230 _setSSLError(NULL, 0, __FILE__, __LINE__);
1231 goto fail1;
1232 }
1233 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1234 if (pnotBefore == NULL)
1235 goto fail1;
1236 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1237 Py_DECREF(pnotBefore);
1238 goto fail1;
1239 }
1240 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001241
1242 (void) BIO_reset(biobuf);
1243 notAfter = X509_get_notAfter(certificate);
1244 ASN1_TIME_print(biobuf, notAfter);
1245 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1246 if (len < 0) {
1247 _setSSLError(NULL, 0, __FILE__, __LINE__);
1248 goto fail1;
1249 }
1250 pnotAfter = PyString_FromStringAndSize(buf, len);
1251 if (pnotAfter == NULL)
1252 goto fail1;
1253 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1254 Py_DECREF(pnotAfter);
1255 goto fail1;
1256 }
1257 Py_DECREF(pnotAfter);
1258
1259 /* Now look for subjectAltName */
1260
1261 peer_alt_names = _get_peer_alt_names(certificate);
1262 if (peer_alt_names == NULL)
1263 goto fail1;
1264 else if (peer_alt_names != Py_None) {
1265 if (PyDict_SetItemString(retval, "subjectAltName",
1266 peer_alt_names) < 0) {
1267 Py_DECREF(peer_alt_names);
1268 goto fail1;
1269 }
1270 Py_DECREF(peer_alt_names);
1271 }
1272
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001273 /* Authority Information Access: OCSP URIs */
1274 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1275 if (obj == NULL) {
1276 goto fail1;
1277 } else if (obj != Py_None) {
1278 result = PyDict_SetItemString(retval, "OCSP", obj);
1279 Py_DECREF(obj);
1280 if (result < 0) {
1281 goto fail1;
1282 }
1283 }
1284
1285 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1286 if (obj == NULL) {
1287 goto fail1;
1288 } else if (obj != Py_None) {
1289 result = PyDict_SetItemString(retval, "caIssuers", obj);
1290 Py_DECREF(obj);
1291 if (result < 0) {
1292 goto fail1;
1293 }
1294 }
1295
1296 /* CDP (CRL distribution points) */
1297 obj = _get_crl_dp(certificate);
1298 if (obj == NULL) {
1299 goto fail1;
1300 } else if (obj != Py_None) {
1301 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1302 Py_DECREF(obj);
1303 if (result < 0) {
1304 goto fail1;
1305 }
1306 }
1307
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001308 BIO_free(biobuf);
1309 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001310
1311 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001312 if (biobuf != NULL)
1313 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001314 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001315 Py_XDECREF(retval);
1316 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001317}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001318
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001319static PyObject *
1320_certificate_to_der(X509 *certificate)
1321{
1322 unsigned char *bytes_buf = NULL;
1323 int len;
1324 PyObject *retval;
1325
1326 bytes_buf = NULL;
1327 len = i2d_X509(certificate, &bytes_buf);
1328 if (len < 0) {
1329 _setSSLError(NULL, 0, __FILE__, __LINE__);
1330 return NULL;
1331 }
1332 /* this is actually an immutable bytes sequence */
1333 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1334 OPENSSL_free(bytes_buf);
1335 return retval;
1336}
Bill Janssen98d19da2007-09-10 21:51:02 +00001337
1338static PyObject *
1339PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1340
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001341 PyObject *retval = NULL;
1342 char *filename = NULL;
1343 X509 *x=NULL;
1344 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001345
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001346 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001347 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001348
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001349 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001350 PyErr_SetString(PySSLErrorObject,
1351 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001352 goto fail0;
1353 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001354
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001355 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001356 PyErr_SetString(PySSLErrorObject,
1357 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001358 goto fail0;
1359 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001360
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001361 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1362 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001363 PyErr_SetString(PySSLErrorObject,
1364 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001365 goto fail0;
1366 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001367
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001368 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001369 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001370
1371 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001372
1373 if (cert != NULL) BIO_free(cert);
1374 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001375}
1376
1377
1378static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001379PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001380{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001381 int verification;
1382 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001383 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001384
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001385 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1386 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001387
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001388 if (!self->handshake_done) {
1389 PyErr_SetString(PyExc_ValueError,
1390 "handshake not done yet");
1391 return NULL;
1392 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001393 if (!self->peer_cert)
1394 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001395
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001396 b = PyObject_IsTrue(binary_mode);
1397 if (b < 0)
1398 return NULL;
1399 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001400 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001401 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001402 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001403 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001404 if ((verification & SSL_VERIFY_PEER) == 0)
1405 return PyDict_New();
1406 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001407 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001408 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001409}
1410
1411PyDoc_STRVAR(PySSL_peercert_doc,
1412"peer_certificate([der=False]) -> certificate\n\
1413\n\
1414Returns the certificate for the peer. If no certificate was provided,\n\
1415returns None. If a certificate was provided, but not validated, returns\n\
1416an empty dictionary. Otherwise returns a dict containing information\n\
1417about the peer certificate.\n\
1418\n\
1419If the optional argument is True, returns a DER-encoded copy of the\n\
1420peer certificate, or None if no certificate was provided. This will\n\
1421return the certificate even if it wasn't validated.");
1422
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001423static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001424
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001425 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001426 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001427 char *cipher_name;
1428 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001429
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001430 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001431 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001432 current = SSL_get_current_cipher(self->ssl);
1433 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001434 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001435
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001436 retval = PyTuple_New(3);
1437 if (retval == NULL)
1438 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001439
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001440 cipher_name = (char *) SSL_CIPHER_get_name(current);
1441 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001442 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001443 PyTuple_SET_ITEM(retval, 0, Py_None);
1444 } else {
1445 v = PyString_FromString(cipher_name);
1446 if (v == NULL)
1447 goto fail0;
1448 PyTuple_SET_ITEM(retval, 0, v);
1449 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001450 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001451 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001452 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001453 PyTuple_SET_ITEM(retval, 1, Py_None);
1454 } else {
1455 v = PyString_FromString(cipher_protocol);
1456 if (v == NULL)
1457 goto fail0;
1458 PyTuple_SET_ITEM(retval, 1, v);
1459 }
1460 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1461 if (v == NULL)
1462 goto fail0;
1463 PyTuple_SET_ITEM(retval, 2, v);
1464 return retval;
1465
Bill Janssen98d19da2007-09-10 21:51:02 +00001466 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001467 Py_DECREF(retval);
1468 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001469}
1470
Alex Gaynore98205d2014-09-04 13:33:22 -07001471static PyObject *PySSL_version(PySSLSocket *self)
1472{
1473 const char *version;
1474
1475 if (self->ssl == NULL)
1476 Py_RETURN_NONE;
1477 version = SSL_get_version(self->ssl);
1478 if (!strcmp(version, "unknown"))
1479 Py_RETURN_NONE;
1480 return PyUnicode_FromString(version);
1481}
1482
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001483#ifdef OPENSSL_NPN_NEGOTIATED
1484static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1485 const unsigned char *out;
1486 unsigned int outlen;
1487
1488 SSL_get0_next_proto_negotiated(self->ssl,
1489 &out, &outlen);
1490
1491 if (out == NULL)
1492 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001493 return PyString_FromStringAndSize((char *)out, outlen);
1494}
1495#endif
1496
1497#ifdef HAVE_ALPN
1498static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1499 const unsigned char *out;
1500 unsigned int outlen;
1501
1502 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1503
1504 if (out == NULL)
1505 Py_RETURN_NONE;
1506 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001507}
1508#endif
1509
1510static PyObject *PySSL_compression(PySSLSocket *self) {
1511#ifdef OPENSSL_NO_COMP
1512 Py_RETURN_NONE;
1513#else
1514 const COMP_METHOD *comp_method;
1515 const char *short_name;
1516
1517 if (self->ssl == NULL)
1518 Py_RETURN_NONE;
1519 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001520 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001521 Py_RETURN_NONE;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001522 short_name = COMP_get_name(comp_method);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001523 if (short_name == NULL)
1524 Py_RETURN_NONE;
1525 return PyBytes_FromString(short_name);
1526#endif
1527}
1528
1529static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1530 Py_INCREF(self->ctx);
1531 return self->ctx;
1532}
1533
1534static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1535 void *closure) {
1536
1537 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1538#if !HAVE_SNI
1539 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1540 "context is not supported by your OpenSSL library");
1541 return -1;
1542#else
1543 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001544 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001545 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1546#endif
1547 } else {
1548 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1549 return -1;
1550 }
1551
1552 return 0;
1553}
1554
1555PyDoc_STRVAR(PySSL_set_context_doc,
1556"_setter_context(ctx)\n\
1557\
1558This changes the context associated with the SSLSocket. This is typically\n\
1559used from within a callback function set by the set_servername_callback\n\
1560on the SSLContext to change the certificate information associated with the\n\
1561SSLSocket before the cryptographic exchange handshake messages\n");
1562
1563
1564
1565static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001566{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001567 if (self->peer_cert) /* Possible not to have one? */
1568 X509_free (self->peer_cert);
1569 if (self->ssl)
1570 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001571 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001572 Py_XDECREF(self->ssl_sock);
1573 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001574 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001575}
1576
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001577/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001578 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001579 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001580 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001581
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001582static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001583check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001584{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001585 fd_set fds;
1586 struct timeval tv;
1587 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001588
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001589 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1590 if (s->sock_timeout < 0.0)
1591 return SOCKET_IS_BLOCKING;
1592 else if (s->sock_timeout == 0.0)
1593 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001594
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001595 /* Guard against closed socket */
1596 if (s->sock_fd < 0)
1597 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001599 /* Prefer poll, if available, since you can poll() any fd
1600 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001601#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001602 {
1603 struct pollfd pollfd;
1604 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001605
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001606 pollfd.fd = s->sock_fd;
1607 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001608
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001609 /* s->sock_timeout is in seconds, timeout in ms */
1610 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1611 PySSL_BEGIN_ALLOW_THREADS
1612 rc = poll(&pollfd, 1, timeout);
1613 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001614
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001615 goto normal_return;
1616 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001617#endif
1618
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001619 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001620 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001621 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001622
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001623 /* Construct the arguments to select */
1624 tv.tv_sec = (int)s->sock_timeout;
1625 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1626 FD_ZERO(&fds);
1627 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001628
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001629 /* See if the socket is ready */
1630 PySSL_BEGIN_ALLOW_THREADS
1631 if (writing)
1632 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1633 else
1634 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1635 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001636
Bill Janssen934b16d2008-06-28 22:19:33 +00001637#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001638normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001639#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001640 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1641 (when we are able to write or when there's something to read) */
1642 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001643}
1644
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001645static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001646{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001647 Py_buffer buf;
1648 int len;
1649 int sockstate;
1650 int err;
1651 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001652 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001653
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001654 Py_INCREF(sock);
1655
1656 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1657 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001658 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001659 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001660
Victor Stinnerc1a44262013-06-25 00:48:02 +02001661 if (buf.len > INT_MAX) {
1662 PyErr_Format(PyExc_OverflowError,
1663 "string longer than %d bytes", INT_MAX);
1664 goto error;
1665 }
1666
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001667 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001668 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001669 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1670 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001671
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001672 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001673 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1674 PyErr_SetString(PySSLErrorObject,
1675 "The write operation timed out");
1676 goto error;
1677 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1678 PyErr_SetString(PySSLErrorObject,
1679 "Underlying socket has been closed.");
1680 goto error;
1681 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1682 PyErr_SetString(PySSLErrorObject,
1683 "Underlying socket too large for select().");
1684 goto error;
1685 }
1686 do {
1687 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001688 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001689 err = SSL_get_error(self->ssl, len);
1690 PySSL_END_ALLOW_THREADS
1691 if (PyErr_CheckSignals()) {
1692 goto error;
1693 }
1694 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001695 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001696 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001697 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001698 } else {
1699 sockstate = SOCKET_OPERATION_OK;
1700 }
1701 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1702 PyErr_SetString(PySSLErrorObject,
1703 "The write operation timed out");
1704 goto error;
1705 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1706 PyErr_SetString(PySSLErrorObject,
1707 "Underlying socket has been closed.");
1708 goto error;
1709 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1710 break;
1711 }
1712 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001713
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001714 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001715 PyBuffer_Release(&buf);
1716 if (len > 0)
1717 return PyInt_FromLong(len);
1718 else
1719 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001720
1721error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001722 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001723 PyBuffer_Release(&buf);
1724 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001725}
1726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001727PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001728"write(s) -> len\n\
1729\n\
1730Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001731of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001732
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001733static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001734{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001735 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001736
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001737 PySSL_BEGIN_ALLOW_THREADS
1738 count = SSL_pending(self->ssl);
1739 PySSL_END_ALLOW_THREADS
1740 if (count < 0)
1741 return PySSL_SetError(self, count, __FILE__, __LINE__);
1742 else
1743 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001744}
1745
1746PyDoc_STRVAR(PySSL_SSLpending_doc,
1747"pending() -> count\n\
1748\n\
1749Returns the number of already decrypted bytes available for read,\n\
1750pending on the connection.\n");
1751
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001752static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001753{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001754 PyObject *dest = NULL;
1755 Py_buffer buf;
1756 char *mem;
1757 int len, count;
1758 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001759 int sockstate;
1760 int err;
1761 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001762 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001763
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001764 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001765
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001766 buf.obj = NULL;
1767 buf.buf = NULL;
1768 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1769 goto error;
1770
1771 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001772 if (len < 0) {
1773 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1774 goto error;
1775 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001776 dest = PyBytes_FromStringAndSize(NULL, len);
1777 if (dest == NULL)
1778 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001779 if (len == 0) {
1780 Py_XDECREF(sock);
1781 return dest;
1782 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001783 mem = PyBytes_AS_STRING(dest);
1784 }
1785 else {
1786 buf_passed = 1;
1787 mem = buf.buf;
1788 if (len <= 0 || len > buf.len) {
1789 len = (int) buf.len;
1790 if (buf.len != len) {
1791 PyErr_SetString(PyExc_OverflowError,
1792 "maximum length can't fit in a C 'int'");
1793 goto error;
1794 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001795 if (len == 0) {
1796 count = 0;
1797 goto done;
1798 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001799 }
1800 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001801
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001802 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001803 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001804 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1805 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001806
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001807 do {
1808 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001809 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001810 err = SSL_get_error(self->ssl, count);
1811 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001812 if (PyErr_CheckSignals())
1813 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001814 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001815 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001816 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001817 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001818 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1819 (SSL_get_shutdown(self->ssl) ==
1820 SSL_RECEIVED_SHUTDOWN))
1821 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001822 count = 0;
1823 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001824 } else {
1825 sockstate = SOCKET_OPERATION_OK;
1826 }
1827 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1828 PyErr_SetString(PySSLErrorObject,
1829 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001830 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001831 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1832 break;
1833 }
1834 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1835 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001836 PySSL_SetError(self, count, __FILE__, __LINE__);
1837 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001838 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839
1840done:
1841 Py_DECREF(sock);
1842 if (!buf_passed) {
1843 _PyBytes_Resize(&dest, count);
1844 return dest;
1845 }
1846 else {
1847 PyBuffer_Release(&buf);
1848 return PyLong_FromLong(count);
1849 }
1850
1851error:
1852 Py_DECREF(sock);
1853 if (!buf_passed)
1854 Py_XDECREF(dest);
1855 else
1856 PyBuffer_Release(&buf);
1857 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001858}
1859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001860PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001861"read([len]) -> string\n\
1862\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001863Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001864
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001865static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001866{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001867 int err, ssl_err, sockstate, nonblocking;
1868 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001869 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001870
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001871 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001872 if (sock->sock_fd < 0) {
1873 _setSSLError("Underlying socket connection gone",
1874 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001875 return NULL;
1876 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001877 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001878
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001879 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001880 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001881 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1882 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001883
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001884 while (1) {
1885 PySSL_BEGIN_ALLOW_THREADS
1886 /* Disable read-ahead so that unwrap can work correctly.
1887 * Otherwise OpenSSL might read in too much data,
1888 * eating clear text data that happens to be
1889 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001890 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001891 * function is used and the shutdown_seen_zero != 0
1892 * condition is met.
1893 */
1894 if (self->shutdown_seen_zero)
1895 SSL_set_read_ahead(self->ssl, 0);
1896 err = SSL_shutdown(self->ssl);
1897 PySSL_END_ALLOW_THREADS
1898 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1899 if (err > 0)
1900 break;
1901 if (err == 0) {
1902 /* Don't loop endlessly; instead preserve legacy
1903 behaviour of trying SSL_shutdown() only twice.
1904 This looks necessary for OpenSSL < 0.9.8m */
1905 if (++zeros > 1)
1906 break;
1907 /* Shutdown was sent, now try receiving */
1908 self->shutdown_seen_zero = 1;
1909 continue;
1910 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001911
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001912 /* Possibly retry shutdown until timeout or failure */
1913 ssl_err = SSL_get_error(self->ssl, err);
1914 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001915 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001916 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001917 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001918 else
1919 break;
1920 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1921 if (ssl_err == SSL_ERROR_WANT_READ)
1922 PyErr_SetString(PySSLErrorObject,
1923 "The read operation timed out");
1924 else
1925 PyErr_SetString(PySSLErrorObject,
1926 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001927 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001928 }
1929 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1930 PyErr_SetString(PySSLErrorObject,
1931 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001932 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001933 }
1934 else if (sockstate != SOCKET_OPERATION_OK)
1935 /* Retain the SSL error code */
1936 break;
1937 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001938
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001939 if (err < 0) {
1940 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001941 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001942 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001943 else
1944 /* It's already INCREF'ed */
1945 return (PyObject *) sock;
1946
1947error:
1948 Py_DECREF(sock);
1949 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001950}
1951
1952PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1953"shutdown(s) -> socket\n\
1954\n\
1955Does the SSL shutdown handshake with the remote end, and returns\n\
1956the underlying socket object.");
1957
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001958#if HAVE_OPENSSL_FINISHED
1959static PyObject *
1960PySSL_tls_unique_cb(PySSLSocket *self)
1961{
1962 PyObject *retval = NULL;
1963 char buf[PySSL_CB_MAXLEN];
1964 size_t len;
1965
1966 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1967 /* if session is resumed XOR we are the client */
1968 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1969 }
1970 else {
1971 /* if a new session XOR we are the server */
1972 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1973 }
1974
1975 /* It cannot be negative in current OpenSSL version as of July 2011 */
1976 if (len == 0)
1977 Py_RETURN_NONE;
1978
1979 retval = PyBytes_FromStringAndSize(buf, len);
1980
1981 return retval;
1982}
1983
1984PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1985"tls_unique_cb() -> bytes\n\
1986\n\
1987Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1988\n\
1989If the TLS handshake is not yet complete, None is returned");
1990
1991#endif /* HAVE_OPENSSL_FINISHED */
1992
1993static PyGetSetDef ssl_getsetlist[] = {
1994 {"context", (getter) PySSL_get_context,
1995 (setter) PySSL_set_context, PySSL_set_context_doc},
1996 {NULL}, /* sentinel */
1997};
1998
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001999static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002000 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2001 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2002 PySSL_SSLwrite_doc},
2003 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2004 PySSL_SSLread_doc},
2005 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2006 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002007 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2008 PySSL_peercert_doc},
2009 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002010 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002011#ifdef OPENSSL_NPN_NEGOTIATED
2012 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2013#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002014#ifdef HAVE_ALPN
2015 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2016#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002017 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002018 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2019 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002020#if HAVE_OPENSSL_FINISHED
2021 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2022 PySSL_tls_unique_cb_doc},
2023#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002024 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002025};
2026
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002027static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002028 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002029 "_ssl._SSLSocket", /*tp_name*/
2030 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002031 0, /*tp_itemsize*/
2032 /* methods */
2033 (destructor)PySSL_dealloc, /*tp_dealloc*/
2034 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002035 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002036 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002037 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002038 0, /*tp_repr*/
2039 0, /*tp_as_number*/
2040 0, /*tp_as_sequence*/
2041 0, /*tp_as_mapping*/
2042 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002043 0, /*tp_call*/
2044 0, /*tp_str*/
2045 0, /*tp_getattro*/
2046 0, /*tp_setattro*/
2047 0, /*tp_as_buffer*/
2048 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2049 0, /*tp_doc*/
2050 0, /*tp_traverse*/
2051 0, /*tp_clear*/
2052 0, /*tp_richcompare*/
2053 0, /*tp_weaklistoffset*/
2054 0, /*tp_iter*/
2055 0, /*tp_iternext*/
2056 PySSLMethods, /*tp_methods*/
2057 0, /*tp_members*/
2058 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002059};
2060
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002061
2062/*
2063 * _SSLContext objects
2064 */
2065
2066static PyObject *
2067context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2068{
2069 char *kwlist[] = {"protocol", NULL};
2070 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002071 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002072 long options;
2073 SSL_CTX *ctx = NULL;
2074
2075 if (!PyArg_ParseTupleAndKeywords(
2076 args, kwds, "i:_SSLContext", kwlist,
2077 &proto_version))
2078 return NULL;
2079
2080 PySSL_BEGIN_ALLOW_THREADS
2081 if (proto_version == PY_SSL_VERSION_TLS1)
2082 ctx = SSL_CTX_new(TLSv1_method());
2083#if HAVE_TLSv1_2
2084 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2085 ctx = SSL_CTX_new(TLSv1_1_method());
2086 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2087 ctx = SSL_CTX_new(TLSv1_2_method());
2088#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002089#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002090 else if (proto_version == PY_SSL_VERSION_SSL3)
2091 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002092#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002093#ifndef OPENSSL_NO_SSL2
2094 else if (proto_version == PY_SSL_VERSION_SSL2)
2095 ctx = SSL_CTX_new(SSLv2_method());
2096#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002097 else if (proto_version == PY_SSL_VERSION_TLS)
2098 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002099 else
2100 proto_version = -1;
2101 PySSL_END_ALLOW_THREADS
2102
2103 if (proto_version == -1) {
2104 PyErr_SetString(PyExc_ValueError,
2105 "invalid protocol version");
2106 return NULL;
2107 }
2108 if (ctx == NULL) {
2109 PyErr_SetString(PySSLErrorObject,
2110 "failed to allocate SSL context");
2111 return NULL;
2112 }
2113
2114 assert(type != NULL && type->tp_alloc != NULL);
2115 self = (PySSLContext *) type->tp_alloc(type, 0);
2116 if (self == NULL) {
2117 SSL_CTX_free(ctx);
2118 return NULL;
2119 }
2120 self->ctx = ctx;
2121#ifdef OPENSSL_NPN_NEGOTIATED
2122 self->npn_protocols = NULL;
2123#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002124#ifdef HAVE_ALPN
2125 self->alpn_protocols = NULL;
2126#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002127#ifndef OPENSSL_NO_TLSEXT
2128 self->set_hostname = NULL;
2129#endif
2130 /* Don't check host name by default */
2131 self->check_hostname = 0;
2132 /* Defaults */
2133 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2134 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2135 if (proto_version != PY_SSL_VERSION_SSL2)
2136 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002137 if (proto_version != PY_SSL_VERSION_SSL3)
2138 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002139 SSL_CTX_set_options(self->ctx, options);
2140
2141#ifndef OPENSSL_NO_ECDH
2142 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2143 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002144 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2145 */
2146#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002147 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2148#else
2149 {
2150 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2151 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2152 EC_KEY_free(key);
2153 }
2154#endif
2155#endif
2156
2157#define SID_CTX "Python"
2158 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2159 sizeof(SID_CTX));
2160#undef SID_CTX
2161
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002162#ifdef X509_V_FLAG_TRUSTED_FIRST
2163 {
2164 /* Improve trust chain building when cross-signed intermediate
2165 certificates are present. See https://bugs.python.org/issue23476. */
2166 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2167 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2168 }
2169#endif
2170
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002171 return (PyObject *)self;
2172}
2173
2174static int
2175context_traverse(PySSLContext *self, visitproc visit, void *arg)
2176{
2177#ifndef OPENSSL_NO_TLSEXT
2178 Py_VISIT(self->set_hostname);
2179#endif
2180 return 0;
2181}
2182
2183static int
2184context_clear(PySSLContext *self)
2185{
2186#ifndef OPENSSL_NO_TLSEXT
2187 Py_CLEAR(self->set_hostname);
2188#endif
2189 return 0;
2190}
2191
2192static void
2193context_dealloc(PySSLContext *self)
2194{
2195 context_clear(self);
2196 SSL_CTX_free(self->ctx);
2197#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002198 PyMem_FREE(self->npn_protocols);
2199#endif
2200#ifdef HAVE_ALPN
2201 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002202#endif
2203 Py_TYPE(self)->tp_free(self);
2204}
2205
2206static PyObject *
2207set_ciphers(PySSLContext *self, PyObject *args)
2208{
2209 int ret;
2210 const char *cipherlist;
2211
2212 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2213 return NULL;
2214 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2215 if (ret == 0) {
2216 /* Clearing the error queue is necessary on some OpenSSL versions,
2217 otherwise the error will be reported again when another SSL call
2218 is done. */
2219 ERR_clear_error();
2220 PyErr_SetString(PySSLErrorObject,
2221 "No cipher can be selected.");
2222 return NULL;
2223 }
2224 Py_RETURN_NONE;
2225}
2226
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002227#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002228static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002229do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2230 const unsigned char *server_protocols, unsigned int server_protocols_len,
2231 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002232{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002233 int ret;
2234 if (client_protocols == NULL) {
2235 client_protocols = (unsigned char *)"";
2236 client_protocols_len = 0;
2237 }
2238 if (server_protocols == NULL) {
2239 server_protocols = (unsigned char *)"";
2240 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002241 }
2242
Benjamin Petersonaa707582015-01-23 17:30:26 -05002243 ret = SSL_select_next_proto(out, outlen,
2244 server_protocols, server_protocols_len,
2245 client_protocols, client_protocols_len);
2246 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2247 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002248
2249 return SSL_TLSEXT_ERR_OK;
2250}
2251
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002252/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2253static int
2254_advertiseNPN_cb(SSL *s,
2255 const unsigned char **data, unsigned int *len,
2256 void *args)
2257{
2258 PySSLContext *ssl_ctx = (PySSLContext *) args;
2259
2260 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002261 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002262 *len = 0;
2263 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002264 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002265 *len = ssl_ctx->npn_protocols_len;
2266 }
2267
2268 return SSL_TLSEXT_ERR_OK;
2269}
2270/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2271static int
2272_selectNPN_cb(SSL *s,
2273 unsigned char **out, unsigned char *outlen,
2274 const unsigned char *server, unsigned int server_len,
2275 void *args)
2276{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002277 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002278 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002279 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002280}
2281#endif
2282
2283static PyObject *
2284_set_npn_protocols(PySSLContext *self, PyObject *args)
2285{
2286#ifdef OPENSSL_NPN_NEGOTIATED
2287 Py_buffer protos;
2288
2289 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2290 return NULL;
2291
2292 if (self->npn_protocols != NULL) {
2293 PyMem_Free(self->npn_protocols);
2294 }
2295
2296 self->npn_protocols = PyMem_Malloc(protos.len);
2297 if (self->npn_protocols == NULL) {
2298 PyBuffer_Release(&protos);
2299 return PyErr_NoMemory();
2300 }
2301 memcpy(self->npn_protocols, protos.buf, protos.len);
2302 self->npn_protocols_len = (int) protos.len;
2303
2304 /* set both server and client callbacks, because the context can
2305 * be used to create both types of sockets */
2306 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2307 _advertiseNPN_cb,
2308 self);
2309 SSL_CTX_set_next_proto_select_cb(self->ctx,
2310 _selectNPN_cb,
2311 self);
2312
2313 PyBuffer_Release(&protos);
2314 Py_RETURN_NONE;
2315#else
2316 PyErr_SetString(PyExc_NotImplementedError,
2317 "The NPN extension requires OpenSSL 1.0.1 or later.");
2318 return NULL;
2319#endif
2320}
2321
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002322#ifdef HAVE_ALPN
2323static int
2324_selectALPN_cb(SSL *s,
2325 const unsigned char **out, unsigned char *outlen,
2326 const unsigned char *client_protocols, unsigned int client_protocols_len,
2327 void *args)
2328{
2329 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002330 return do_protocol_selection(1, (unsigned char **)out, outlen,
2331 ctx->alpn_protocols, ctx->alpn_protocols_len,
2332 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002333}
2334#endif
2335
2336static PyObject *
2337_set_alpn_protocols(PySSLContext *self, PyObject *args)
2338{
2339#ifdef HAVE_ALPN
2340 Py_buffer protos;
2341
2342 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2343 return NULL;
2344
2345 PyMem_FREE(self->alpn_protocols);
2346 self->alpn_protocols = PyMem_Malloc(protos.len);
2347 if (!self->alpn_protocols)
2348 return PyErr_NoMemory();
2349 memcpy(self->alpn_protocols, protos.buf, protos.len);
2350 self->alpn_protocols_len = protos.len;
2351 PyBuffer_Release(&protos);
2352
2353 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2354 return PyErr_NoMemory();
2355 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2356
2357 PyBuffer_Release(&protos);
2358 Py_RETURN_NONE;
2359#else
2360 PyErr_SetString(PyExc_NotImplementedError,
2361 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2362 return NULL;
2363#endif
2364}
2365
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002366static PyObject *
2367get_verify_mode(PySSLContext *self, void *c)
2368{
2369 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2370 case SSL_VERIFY_NONE:
2371 return PyLong_FromLong(PY_SSL_CERT_NONE);
2372 case SSL_VERIFY_PEER:
2373 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2374 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2375 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2376 }
2377 PyErr_SetString(PySSLErrorObject,
2378 "invalid return value from SSL_CTX_get_verify_mode");
2379 return NULL;
2380}
2381
2382static int
2383set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2384{
2385 int n, mode;
2386 if (!PyArg_Parse(arg, "i", &n))
2387 return -1;
2388 if (n == PY_SSL_CERT_NONE)
2389 mode = SSL_VERIFY_NONE;
2390 else if (n == PY_SSL_CERT_OPTIONAL)
2391 mode = SSL_VERIFY_PEER;
2392 else if (n == PY_SSL_CERT_REQUIRED)
2393 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2394 else {
2395 PyErr_SetString(PyExc_ValueError,
2396 "invalid value for verify_mode");
2397 return -1;
2398 }
2399 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2400 PyErr_SetString(PyExc_ValueError,
2401 "Cannot set verify_mode to CERT_NONE when "
2402 "check_hostname is enabled.");
2403 return -1;
2404 }
2405 SSL_CTX_set_verify(self->ctx, mode, NULL);
2406 return 0;
2407}
2408
2409#ifdef HAVE_OPENSSL_VERIFY_PARAM
2410static PyObject *
2411get_verify_flags(PySSLContext *self, void *c)
2412{
2413 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002414 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002415 unsigned long flags;
2416
2417 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002418 param = X509_STORE_get0_param(store);
2419 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002420 return PyLong_FromUnsignedLong(flags);
2421}
2422
2423static int
2424set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2425{
2426 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002427 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002428 unsigned long new_flags, flags, set, clear;
2429
2430 if (!PyArg_Parse(arg, "k", &new_flags))
2431 return -1;
2432 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002433 param = X509_STORE_get0_param(store);
2434 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002435 clear = flags & ~new_flags;
2436 set = ~flags & new_flags;
2437 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002438 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002439 _setSSLError(NULL, 0, __FILE__, __LINE__);
2440 return -1;
2441 }
2442 }
2443 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002444 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002445 _setSSLError(NULL, 0, __FILE__, __LINE__);
2446 return -1;
2447 }
2448 }
2449 return 0;
2450}
2451#endif
2452
2453static PyObject *
2454get_options(PySSLContext *self, void *c)
2455{
2456 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2457}
2458
2459static int
2460set_options(PySSLContext *self, PyObject *arg, void *c)
2461{
2462 long new_opts, opts, set, clear;
2463 if (!PyArg_Parse(arg, "l", &new_opts))
2464 return -1;
2465 opts = SSL_CTX_get_options(self->ctx);
2466 clear = opts & ~new_opts;
2467 set = ~opts & new_opts;
2468 if (clear) {
2469#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2470 SSL_CTX_clear_options(self->ctx, clear);
2471#else
2472 PyErr_SetString(PyExc_ValueError,
2473 "can't clear options before OpenSSL 0.9.8m");
2474 return -1;
2475#endif
2476 }
2477 if (set)
2478 SSL_CTX_set_options(self->ctx, set);
2479 return 0;
2480}
2481
2482static PyObject *
2483get_check_hostname(PySSLContext *self, void *c)
2484{
2485 return PyBool_FromLong(self->check_hostname);
2486}
2487
2488static int
2489set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2490{
2491 PyObject *py_check_hostname;
2492 int check_hostname;
2493 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2494 return -1;
2495
2496 check_hostname = PyObject_IsTrue(py_check_hostname);
2497 if (check_hostname < 0)
2498 return -1;
2499 if (check_hostname &&
2500 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2501 PyErr_SetString(PyExc_ValueError,
2502 "check_hostname needs a SSL context with either "
2503 "CERT_OPTIONAL or CERT_REQUIRED");
2504 return -1;
2505 }
2506 self->check_hostname = check_hostname;
2507 return 0;
2508}
2509
2510
2511typedef struct {
2512 PyThreadState *thread_state;
2513 PyObject *callable;
2514 char *password;
2515 int size;
2516 int error;
2517} _PySSLPasswordInfo;
2518
2519static int
2520_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2521 const char *bad_type_error)
2522{
2523 /* Set the password and size fields of a _PySSLPasswordInfo struct
2524 from a unicode, bytes, or byte array object.
2525 The password field will be dynamically allocated and must be freed
2526 by the caller */
2527 PyObject *password_bytes = NULL;
2528 const char *data = NULL;
2529 Py_ssize_t size;
2530
2531 if (PyUnicode_Check(password)) {
2532 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2533 if (!password_bytes) {
2534 goto error;
2535 }
2536 data = PyBytes_AS_STRING(password_bytes);
2537 size = PyBytes_GET_SIZE(password_bytes);
2538 } else if (PyBytes_Check(password)) {
2539 data = PyBytes_AS_STRING(password);
2540 size = PyBytes_GET_SIZE(password);
2541 } else if (PyByteArray_Check(password)) {
2542 data = PyByteArray_AS_STRING(password);
2543 size = PyByteArray_GET_SIZE(password);
2544 } else {
2545 PyErr_SetString(PyExc_TypeError, bad_type_error);
2546 goto error;
2547 }
2548
2549 if (size > (Py_ssize_t)INT_MAX) {
2550 PyErr_Format(PyExc_ValueError,
2551 "password cannot be longer than %d bytes", INT_MAX);
2552 goto error;
2553 }
2554
2555 PyMem_Free(pw_info->password);
2556 pw_info->password = PyMem_Malloc(size);
2557 if (!pw_info->password) {
2558 PyErr_SetString(PyExc_MemoryError,
2559 "unable to allocate password buffer");
2560 goto error;
2561 }
2562 memcpy(pw_info->password, data, size);
2563 pw_info->size = (int)size;
2564
2565 Py_XDECREF(password_bytes);
2566 return 1;
2567
2568error:
2569 Py_XDECREF(password_bytes);
2570 return 0;
2571}
2572
2573static int
2574_password_callback(char *buf, int size, int rwflag, void *userdata)
2575{
2576 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2577 PyObject *fn_ret = NULL;
2578
2579 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2580
2581 if (pw_info->callable) {
2582 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2583 if (!fn_ret) {
2584 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2585 core python API, so we could use it to add a frame here */
2586 goto error;
2587 }
2588
2589 if (!_pwinfo_set(pw_info, fn_ret,
2590 "password callback must return a string")) {
2591 goto error;
2592 }
2593 Py_CLEAR(fn_ret);
2594 }
2595
2596 if (pw_info->size > size) {
2597 PyErr_Format(PyExc_ValueError,
2598 "password cannot be longer than %d bytes", size);
2599 goto error;
2600 }
2601
2602 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2603 memcpy(buf, pw_info->password, pw_info->size);
2604 return pw_info->size;
2605
2606error:
2607 Py_XDECREF(fn_ret);
2608 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2609 pw_info->error = 1;
2610 return -1;
2611}
2612
2613static PyObject *
2614load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2615{
2616 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002617 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2618 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002619 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2620 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002621 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2622 int r;
2623
2624 errno = 0;
2625 ERR_clear_error();
2626 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002627 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002628 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002629 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002630 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002631
2632 if (keyfile && keyfile != Py_None) {
2633 if (PyString_Check(keyfile)) {
2634 Py_INCREF(keyfile);
2635 keyfile_bytes = keyfile;
2636 } else {
2637 PyObject *u = PyUnicode_FromObject(keyfile);
2638 if (!u)
2639 goto error;
2640 keyfile_bytes = PyUnicode_AsEncodedString(
2641 u, Py_FileSystemDefaultEncoding, NULL);
2642 Py_DECREF(u);
2643 if (!keyfile_bytes)
2644 goto error;
2645 }
2646 }
2647
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002648 if (password && password != Py_None) {
2649 if (PyCallable_Check(password)) {
2650 pw_info.callable = password;
2651 } else if (!_pwinfo_set(&pw_info, password,
2652 "password should be a string or callable")) {
2653 goto error;
2654 }
2655 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2656 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2657 }
2658 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2659 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2660 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2661 if (r != 1) {
2662 if (pw_info.error) {
2663 ERR_clear_error();
2664 /* the password callback has already set the error information */
2665 }
2666 else if (errno != 0) {
2667 ERR_clear_error();
2668 PyErr_SetFromErrno(PyExc_IOError);
2669 }
2670 else {
2671 _setSSLError(NULL, 0, __FILE__, __LINE__);
2672 }
2673 goto error;
2674 }
2675 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2676 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002677 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002678 SSL_FILETYPE_PEM);
2679 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2680 if (r != 1) {
2681 if (pw_info.error) {
2682 ERR_clear_error();
2683 /* the password callback has already set the error information */
2684 }
2685 else if (errno != 0) {
2686 ERR_clear_error();
2687 PyErr_SetFromErrno(PyExc_IOError);
2688 }
2689 else {
2690 _setSSLError(NULL, 0, __FILE__, __LINE__);
2691 }
2692 goto error;
2693 }
2694 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2695 r = SSL_CTX_check_private_key(self->ctx);
2696 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2697 if (r != 1) {
2698 _setSSLError(NULL, 0, __FILE__, __LINE__);
2699 goto error;
2700 }
2701 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2702 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002703 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002704 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002705 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002706 Py_RETURN_NONE;
2707
2708error:
2709 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2710 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002711 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002712 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002713 PyMem_Free(certfile_bytes);
2714 return NULL;
2715}
2716
2717/* internal helper function, returns -1 on error
2718 */
2719static int
2720_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2721 int filetype)
2722{
2723 BIO *biobuf = NULL;
2724 X509_STORE *store;
2725 int retval = 0, err, loaded = 0;
2726
2727 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2728
2729 if (len <= 0) {
2730 PyErr_SetString(PyExc_ValueError,
2731 "Empty certificate data");
2732 return -1;
2733 } else if (len > INT_MAX) {
2734 PyErr_SetString(PyExc_OverflowError,
2735 "Certificate data is too long.");
2736 return -1;
2737 }
2738
2739 biobuf = BIO_new_mem_buf(data, (int)len);
2740 if (biobuf == NULL) {
2741 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2742 return -1;
2743 }
2744
2745 store = SSL_CTX_get_cert_store(self->ctx);
2746 assert(store != NULL);
2747
2748 while (1) {
2749 X509 *cert = NULL;
2750 int r;
2751
2752 if (filetype == SSL_FILETYPE_ASN1) {
2753 cert = d2i_X509_bio(biobuf, NULL);
2754 } else {
2755 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002756 SSL_CTX_get_default_passwd_cb(self->ctx),
2757 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2758 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002759 }
2760 if (cert == NULL) {
2761 break;
2762 }
2763 r = X509_STORE_add_cert(store, cert);
2764 X509_free(cert);
2765 if (!r) {
2766 err = ERR_peek_last_error();
2767 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2768 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2769 /* cert already in hash table, not an error */
2770 ERR_clear_error();
2771 } else {
2772 break;
2773 }
2774 }
2775 loaded++;
2776 }
2777
2778 err = ERR_peek_last_error();
2779 if ((filetype == SSL_FILETYPE_ASN1) &&
2780 (loaded > 0) &&
2781 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2782 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2783 /* EOF ASN1 file, not an error */
2784 ERR_clear_error();
2785 retval = 0;
2786 } else if ((filetype == SSL_FILETYPE_PEM) &&
2787 (loaded > 0) &&
2788 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2789 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2790 /* EOF PEM file, not an error */
2791 ERR_clear_error();
2792 retval = 0;
2793 } else {
2794 _setSSLError(NULL, 0, __FILE__, __LINE__);
2795 retval = -1;
2796 }
2797
2798 BIO_free(biobuf);
2799 return retval;
2800}
2801
2802
2803static PyObject *
2804load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2805{
2806 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2807 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2808 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2809 const char *cafile_buf = NULL, *capath_buf = NULL;
2810 int r = 0, ok = 1;
2811
2812 errno = 0;
2813 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2814 "|OOO:load_verify_locations", kwlist,
2815 &cafile, &capath, &cadata))
2816 return NULL;
2817
2818 if (cafile == Py_None)
2819 cafile = NULL;
2820 if (capath == Py_None)
2821 capath = NULL;
2822 if (cadata == Py_None)
2823 cadata = NULL;
2824
2825 if (cafile == NULL && capath == NULL && cadata == NULL) {
2826 PyErr_SetString(PyExc_TypeError,
2827 "cafile, capath and cadata cannot be all omitted");
2828 goto error;
2829 }
2830
2831 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002832 if (PyString_Check(cafile)) {
2833 Py_INCREF(cafile);
2834 cafile_bytes = cafile;
2835 } else {
2836 PyObject *u = PyUnicode_FromObject(cafile);
2837 if (!u)
2838 goto error;
2839 cafile_bytes = PyUnicode_AsEncodedString(
2840 u, Py_FileSystemDefaultEncoding, NULL);
2841 Py_DECREF(u);
2842 if (!cafile_bytes)
2843 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002844 }
2845 }
2846 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002847 if (PyString_Check(capath)) {
2848 Py_INCREF(capath);
2849 capath_bytes = capath;
2850 } else {
2851 PyObject *u = PyUnicode_FromObject(capath);
2852 if (!u)
2853 goto error;
2854 capath_bytes = PyUnicode_AsEncodedString(
2855 u, Py_FileSystemDefaultEncoding, NULL);
2856 Py_DECREF(u);
2857 if (!capath_bytes)
2858 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002859 }
2860 }
2861
2862 /* validata cadata type and load cadata */
2863 if (cadata) {
2864 Py_buffer buf;
2865 PyObject *cadata_ascii = NULL;
2866
2867 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2868 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2869 PyBuffer_Release(&buf);
2870 PyErr_SetString(PyExc_TypeError,
2871 "cadata should be a contiguous buffer with "
2872 "a single dimension");
2873 goto error;
2874 }
2875 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2876 PyBuffer_Release(&buf);
2877 if (r == -1) {
2878 goto error;
2879 }
2880 } else {
2881 PyErr_Clear();
2882 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2883 if (cadata_ascii == NULL) {
2884 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002885 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002886 "bytes-like object");
2887 goto error;
2888 }
2889 r = _add_ca_certs(self,
2890 PyBytes_AS_STRING(cadata_ascii),
2891 PyBytes_GET_SIZE(cadata_ascii),
2892 SSL_FILETYPE_PEM);
2893 Py_DECREF(cadata_ascii);
2894 if (r == -1) {
2895 goto error;
2896 }
2897 }
2898 }
2899
2900 /* load cafile or capath */
2901 if (cafile_bytes || capath_bytes) {
2902 if (cafile)
2903 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2904 if (capath)
2905 capath_buf = PyBytes_AS_STRING(capath_bytes);
2906 PySSL_BEGIN_ALLOW_THREADS
2907 r = SSL_CTX_load_verify_locations(
2908 self->ctx,
2909 cafile_buf,
2910 capath_buf);
2911 PySSL_END_ALLOW_THREADS
2912 if (r != 1) {
2913 ok = 0;
2914 if (errno != 0) {
2915 ERR_clear_error();
2916 PyErr_SetFromErrno(PyExc_IOError);
2917 }
2918 else {
2919 _setSSLError(NULL, 0, __FILE__, __LINE__);
2920 }
2921 goto error;
2922 }
2923 }
2924 goto end;
2925
2926 error:
2927 ok = 0;
2928 end:
2929 Py_XDECREF(cafile_bytes);
2930 Py_XDECREF(capath_bytes);
2931 if (ok) {
2932 Py_RETURN_NONE;
2933 } else {
2934 return NULL;
2935 }
2936}
2937
2938static PyObject *
2939load_dh_params(PySSLContext *self, PyObject *filepath)
2940{
2941 BIO *bio;
2942 DH *dh;
2943 char *path = PyBytes_AsString(filepath);
2944 if (!path) {
2945 return NULL;
2946 }
2947
2948 bio = BIO_new_file(path, "r");
2949 if (bio == NULL) {
2950 ERR_clear_error();
2951 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2952 return NULL;
2953 }
2954 errno = 0;
2955 PySSL_BEGIN_ALLOW_THREADS
2956 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2957 BIO_free(bio);
2958 PySSL_END_ALLOW_THREADS
2959 if (dh == NULL) {
2960 if (errno != 0) {
2961 ERR_clear_error();
2962 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2963 }
2964 else {
2965 _setSSLError(NULL, 0, __FILE__, __LINE__);
2966 }
2967 return NULL;
2968 }
2969 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2970 _setSSLError(NULL, 0, __FILE__, __LINE__);
2971 DH_free(dh);
2972 Py_RETURN_NONE;
2973}
2974
2975static PyObject *
2976context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2977{
2978 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2979 PySocketSockObject *sock;
2980 int server_side = 0;
2981 char *hostname = NULL;
2982 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2983
2984 /* server_hostname is either None (or absent), or to be encoded
2985 using the idna encoding. */
2986 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2987 PySocketModule.Sock_Type,
2988 &sock, &server_side,
2989 Py_TYPE(Py_None), &hostname_obj,
2990 &ssl_sock)) {
2991 PyErr_Clear();
2992 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2993 PySocketModule.Sock_Type,
2994 &sock, &server_side,
2995 "idna", &hostname, &ssl_sock))
2996 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002997 }
2998
2999 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3000 hostname, ssl_sock);
3001 if (hostname != NULL)
3002 PyMem_Free(hostname);
3003 return res;
3004}
3005
3006static PyObject *
3007session_stats(PySSLContext *self, PyObject *unused)
3008{
3009 int r;
3010 PyObject *value, *stats = PyDict_New();
3011 if (!stats)
3012 return NULL;
3013
3014#define ADD_STATS(SSL_NAME, KEY_NAME) \
3015 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3016 if (value == NULL) \
3017 goto error; \
3018 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3019 Py_DECREF(value); \
3020 if (r < 0) \
3021 goto error;
3022
3023 ADD_STATS(number, "number");
3024 ADD_STATS(connect, "connect");
3025 ADD_STATS(connect_good, "connect_good");
3026 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3027 ADD_STATS(accept, "accept");
3028 ADD_STATS(accept_good, "accept_good");
3029 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3030 ADD_STATS(accept, "accept");
3031 ADD_STATS(hits, "hits");
3032 ADD_STATS(misses, "misses");
3033 ADD_STATS(timeouts, "timeouts");
3034 ADD_STATS(cache_full, "cache_full");
3035
3036#undef ADD_STATS
3037
3038 return stats;
3039
3040error:
3041 Py_DECREF(stats);
3042 return NULL;
3043}
3044
3045static PyObject *
3046set_default_verify_paths(PySSLContext *self, PyObject *unused)
3047{
3048 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3049 _setSSLError(NULL, 0, __FILE__, __LINE__);
3050 return NULL;
3051 }
3052 Py_RETURN_NONE;
3053}
3054
3055#ifndef OPENSSL_NO_ECDH
3056static PyObject *
3057set_ecdh_curve(PySSLContext *self, PyObject *name)
3058{
3059 char *name_bytes;
3060 int nid;
3061 EC_KEY *key;
3062
3063 name_bytes = PyBytes_AsString(name);
3064 if (!name_bytes) {
3065 return NULL;
3066 }
3067 nid = OBJ_sn2nid(name_bytes);
3068 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003069 PyObject *r = PyObject_Repr(name);
3070 if (!r)
3071 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003072 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003073 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3074 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003075 return NULL;
3076 }
3077 key = EC_KEY_new_by_curve_name(nid);
3078 if (key == NULL) {
3079 _setSSLError(NULL, 0, __FILE__, __LINE__);
3080 return NULL;
3081 }
3082 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3083 EC_KEY_free(key);
3084 Py_RETURN_NONE;
3085}
3086#endif
3087
3088#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3089static int
3090_servername_callback(SSL *s, int *al, void *args)
3091{
3092 int ret;
3093 PySSLContext *ssl_ctx = (PySSLContext *) args;
3094 PySSLSocket *ssl;
3095 PyObject *servername_o;
3096 PyObject *servername_idna;
3097 PyObject *result;
3098 /* The high-level ssl.SSLSocket object */
3099 PyObject *ssl_socket;
3100 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3101#ifdef WITH_THREAD
3102 PyGILState_STATE gstate = PyGILState_Ensure();
3103#endif
3104
3105 if (ssl_ctx->set_hostname == NULL) {
3106 /* remove race condition in this the call back while if removing the
3107 * callback is in progress */
3108#ifdef WITH_THREAD
3109 PyGILState_Release(gstate);
3110#endif
3111 return SSL_TLSEXT_ERR_OK;
3112 }
3113
3114 ssl = SSL_get_app_data(s);
3115 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003116 if (ssl->ssl_sock == NULL) {
3117 ssl_socket = Py_None;
3118 } else {
3119 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3120 Py_INCREF(ssl_socket);
3121 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003122 if (ssl_socket == Py_None) {
3123 goto error;
3124 }
3125
3126 if (servername == NULL) {
3127 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3128 Py_None, ssl_ctx, NULL);
3129 }
3130 else {
3131 servername_o = PyBytes_FromString(servername);
3132 if (servername_o == NULL) {
3133 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3134 goto error;
3135 }
3136 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3137 if (servername_idna == NULL) {
3138 PyErr_WriteUnraisable(servername_o);
3139 Py_DECREF(servername_o);
3140 goto error;
3141 }
3142 Py_DECREF(servername_o);
3143 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3144 servername_idna, ssl_ctx, NULL);
3145 Py_DECREF(servername_idna);
3146 }
3147 Py_DECREF(ssl_socket);
3148
3149 if (result == NULL) {
3150 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3151 *al = SSL_AD_HANDSHAKE_FAILURE;
3152 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3153 }
3154 else {
3155 if (result != Py_None) {
3156 *al = (int) PyLong_AsLong(result);
3157 if (PyErr_Occurred()) {
3158 PyErr_WriteUnraisable(result);
3159 *al = SSL_AD_INTERNAL_ERROR;
3160 }
3161 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3162 }
3163 else {
3164 ret = SSL_TLSEXT_ERR_OK;
3165 }
3166 Py_DECREF(result);
3167 }
3168
3169#ifdef WITH_THREAD
3170 PyGILState_Release(gstate);
3171#endif
3172 return ret;
3173
3174error:
3175 Py_DECREF(ssl_socket);
3176 *al = SSL_AD_INTERNAL_ERROR;
3177 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3178#ifdef WITH_THREAD
3179 PyGILState_Release(gstate);
3180#endif
3181 return ret;
3182}
3183#endif
3184
3185PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3186"set_servername_callback(method)\n\
3187\n\
3188This sets a callback that will be called when a server name is provided by\n\
3189the SSL/TLS client in the SNI extension.\n\
3190\n\
3191If the argument is None then the callback is disabled. The method is called\n\
3192with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3193See RFC 6066 for details of the SNI extension.");
3194
3195static PyObject *
3196set_servername_callback(PySSLContext *self, PyObject *args)
3197{
3198#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3199 PyObject *cb;
3200
3201 if (!PyArg_ParseTuple(args, "O", &cb))
3202 return NULL;
3203
3204 Py_CLEAR(self->set_hostname);
3205 if (cb == Py_None) {
3206 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3207 }
3208 else {
3209 if (!PyCallable_Check(cb)) {
3210 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3211 PyErr_SetString(PyExc_TypeError,
3212 "not a callable object");
3213 return NULL;
3214 }
3215 Py_INCREF(cb);
3216 self->set_hostname = cb;
3217 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3218 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3219 }
3220 Py_RETURN_NONE;
3221#else
3222 PyErr_SetString(PyExc_NotImplementedError,
3223 "The TLS extension servername callback, "
3224 "SSL_CTX_set_tlsext_servername_callback, "
3225 "is not in the current OpenSSL library.");
3226 return NULL;
3227#endif
3228}
3229
3230PyDoc_STRVAR(PySSL_get_stats_doc,
3231"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3232\n\
3233Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3234CA extension and certificate revocation lists inside the context's cert\n\
3235store.\n\
3236NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3237been used at least once.");
3238
3239static PyObject *
3240cert_store_stats(PySSLContext *self)
3241{
3242 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003243 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003244 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003245 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003246
3247 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003248 objs = X509_STORE_get0_objects(store);
3249 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3250 obj = sk_X509_OBJECT_value(objs, i);
3251 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003252 case X509_LU_X509:
3253 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003254 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003255 ca++;
3256 }
3257 break;
3258 case X509_LU_CRL:
3259 crl++;
3260 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003261 default:
3262 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3263 * As far as I can tell they are internal states and never
3264 * stored in a cert store */
3265 break;
3266 }
3267 }
3268 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3269 "x509_ca", ca);
3270}
3271
3272PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3273"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3274\n\
3275Returns a list of dicts with information of loaded CA certs. If the\n\
3276optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3277NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3278been used at least once.");
3279
3280static PyObject *
3281get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3282{
3283 char *kwlist[] = {"binary_form", NULL};
3284 X509_STORE *store;
3285 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003286 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003287 int i;
3288 int binary_mode = 0;
3289
3290 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3291 kwlist, &py_binary_mode)) {
3292 return NULL;
3293 }
3294 binary_mode = PyObject_IsTrue(py_binary_mode);
3295 if (binary_mode < 0) {
3296 return NULL;
3297 }
3298
3299 if ((rlist = PyList_New(0)) == NULL) {
3300 return NULL;
3301 }
3302
3303 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003304 objs = X509_STORE_get0_objects(store);
3305 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003306 X509_OBJECT *obj;
3307 X509 *cert;
3308
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003309 obj = sk_X509_OBJECT_value(objs, i);
3310 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003311 /* not a x509 cert */
3312 continue;
3313 }
3314 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003315 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003316 if (!X509_check_ca(cert)) {
3317 continue;
3318 }
3319 if (binary_mode) {
3320 ci = _certificate_to_der(cert);
3321 } else {
3322 ci = _decode_certificate(cert);
3323 }
3324 if (ci == NULL) {
3325 goto error;
3326 }
3327 if (PyList_Append(rlist, ci) == -1) {
3328 goto error;
3329 }
3330 Py_CLEAR(ci);
3331 }
3332 return rlist;
3333
3334 error:
3335 Py_XDECREF(ci);
3336 Py_XDECREF(rlist);
3337 return NULL;
3338}
3339
3340
3341static PyGetSetDef context_getsetlist[] = {
3342 {"check_hostname", (getter) get_check_hostname,
3343 (setter) set_check_hostname, NULL},
3344 {"options", (getter) get_options,
3345 (setter) set_options, NULL},
3346#ifdef HAVE_OPENSSL_VERIFY_PARAM
3347 {"verify_flags", (getter) get_verify_flags,
3348 (setter) set_verify_flags, NULL},
3349#endif
3350 {"verify_mode", (getter) get_verify_mode,
3351 (setter) set_verify_mode, NULL},
3352 {NULL}, /* sentinel */
3353};
3354
3355static struct PyMethodDef context_methods[] = {
3356 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3357 METH_VARARGS | METH_KEYWORDS, NULL},
3358 {"set_ciphers", (PyCFunction) set_ciphers,
3359 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003360 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3361 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003362 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3363 METH_VARARGS, NULL},
3364 {"load_cert_chain", (PyCFunction) load_cert_chain,
3365 METH_VARARGS | METH_KEYWORDS, NULL},
3366 {"load_dh_params", (PyCFunction) load_dh_params,
3367 METH_O, NULL},
3368 {"load_verify_locations", (PyCFunction) load_verify_locations,
3369 METH_VARARGS | METH_KEYWORDS, NULL},
3370 {"session_stats", (PyCFunction) session_stats,
3371 METH_NOARGS, NULL},
3372 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3373 METH_NOARGS, NULL},
3374#ifndef OPENSSL_NO_ECDH
3375 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3376 METH_O, NULL},
3377#endif
3378 {"set_servername_callback", (PyCFunction) set_servername_callback,
3379 METH_VARARGS, PySSL_set_servername_callback_doc},
3380 {"cert_store_stats", (PyCFunction) cert_store_stats,
3381 METH_NOARGS, PySSL_get_stats_doc},
3382 {"get_ca_certs", (PyCFunction) get_ca_certs,
3383 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3384 {NULL, NULL} /* sentinel */
3385};
3386
3387static PyTypeObject PySSLContext_Type = {
3388 PyVarObject_HEAD_INIT(NULL, 0)
3389 "_ssl._SSLContext", /*tp_name*/
3390 sizeof(PySSLContext), /*tp_basicsize*/
3391 0, /*tp_itemsize*/
3392 (destructor)context_dealloc, /*tp_dealloc*/
3393 0, /*tp_print*/
3394 0, /*tp_getattr*/
3395 0, /*tp_setattr*/
3396 0, /*tp_reserved*/
3397 0, /*tp_repr*/
3398 0, /*tp_as_number*/
3399 0, /*tp_as_sequence*/
3400 0, /*tp_as_mapping*/
3401 0, /*tp_hash*/
3402 0, /*tp_call*/
3403 0, /*tp_str*/
3404 0, /*tp_getattro*/
3405 0, /*tp_setattro*/
3406 0, /*tp_as_buffer*/
3407 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3408 0, /*tp_doc*/
3409 (traverseproc) context_traverse, /*tp_traverse*/
3410 (inquiry) context_clear, /*tp_clear*/
3411 0, /*tp_richcompare*/
3412 0, /*tp_weaklistoffset*/
3413 0, /*tp_iter*/
3414 0, /*tp_iternext*/
3415 context_methods, /*tp_methods*/
3416 0, /*tp_members*/
3417 context_getsetlist, /*tp_getset*/
3418 0, /*tp_base*/
3419 0, /*tp_dict*/
3420 0, /*tp_descr_get*/
3421 0, /*tp_descr_set*/
3422 0, /*tp_dictoffset*/
3423 0, /*tp_init*/
3424 0, /*tp_alloc*/
3425 context_new, /*tp_new*/
3426};
3427
3428
3429
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003430#ifdef HAVE_OPENSSL_RAND
3431
3432/* helper routines for seeding the SSL PRNG */
3433static PyObject *
3434PySSL_RAND_add(PyObject *self, PyObject *args)
3435{
3436 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003437 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003438 double entropy;
3439
3440 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003441 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003442 do {
3443 if (len >= INT_MAX) {
3444 written = INT_MAX;
3445 } else {
3446 written = len;
3447 }
3448 RAND_add(buf, (int)written, entropy);
3449 buf += written;
3450 len -= written;
3451 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003452 Py_INCREF(Py_None);
3453 return Py_None;
3454}
3455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003456PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003457"RAND_add(string, entropy)\n\
3458\n\
3459Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003460bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003461
3462static PyObject *
3463PySSL_RAND_status(PyObject *self)
3464{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003465 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003466}
3467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003468PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003469"RAND_status() -> 0 or 1\n\
3470\n\
3471Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3472It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003473using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003474
Victor Stinner7c906672015-01-06 13:53:37 +01003475#endif /* HAVE_OPENSSL_RAND */
3476
3477
Benjamin Peterson42e10292016-07-07 00:02:31 -07003478#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003479
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003480static PyObject *
3481PySSL_RAND_egd(PyObject *self, PyObject *arg)
3482{
3483 int bytes;
3484
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003485 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003486 return PyErr_Format(PyExc_TypeError,
3487 "RAND_egd() expected string, found %s",
3488 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003489 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003490 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003491 PyErr_SetString(PySSLErrorObject,
3492 "EGD connection failed or EGD did not return "
3493 "enough data to seed the PRNG");
3494 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003495 }
3496 return PyInt_FromLong(bytes);
3497}
3498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003499PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003500"RAND_egd(path) -> bytes\n\
3501\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003502Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3503Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003504fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003505
Benjamin Peterson42e10292016-07-07 00:02:31 -07003506#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003507
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003508
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003509PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3510"get_default_verify_paths() -> tuple\n\
3511\n\
3512Return search paths and environment vars that are used by SSLContext's\n\
3513set_default_verify_paths() to load default CAs. The values are\n\
3514'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3515
3516static PyObject *
3517PySSL_get_default_verify_paths(PyObject *self)
3518{
3519 PyObject *ofile_env = NULL;
3520 PyObject *ofile = NULL;
3521 PyObject *odir_env = NULL;
3522 PyObject *odir = NULL;
3523
Benjamin Peterson65192c12015-07-18 10:59:13 -07003524#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003525 const char *tmp = (info); \
3526 target = NULL; \
3527 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3528 else { target = PyBytes_FromString(tmp); } \
3529 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003530 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003531
Benjamin Peterson65192c12015-07-18 10:59:13 -07003532 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3533 CONVERT(X509_get_default_cert_file(), ofile);
3534 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3535 CONVERT(X509_get_default_cert_dir(), odir);
3536#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003537
3538 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3539
3540 error:
3541 Py_XDECREF(ofile_env);
3542 Py_XDECREF(ofile);
3543 Py_XDECREF(odir_env);
3544 Py_XDECREF(odir);
3545 return NULL;
3546}
3547
3548static PyObject*
3549asn1obj2py(ASN1_OBJECT *obj)
3550{
3551 int nid;
3552 const char *ln, *sn;
3553 char buf[100];
3554 Py_ssize_t buflen;
3555
3556 nid = OBJ_obj2nid(obj);
3557 if (nid == NID_undef) {
3558 PyErr_Format(PyExc_ValueError, "Unknown object");
3559 return NULL;
3560 }
3561 sn = OBJ_nid2sn(nid);
3562 ln = OBJ_nid2ln(nid);
3563 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3564 if (buflen < 0) {
3565 _setSSLError(NULL, 0, __FILE__, __LINE__);
3566 return NULL;
3567 }
3568 if (buflen) {
3569 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3570 } else {
3571 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3572 }
3573}
3574
3575PyDoc_STRVAR(PySSL_txt2obj_doc,
3576"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3577\n\
3578Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3579objects are looked up by OID. With name=True short and long name are also\n\
3580matched.");
3581
3582static PyObject*
3583PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3584{
3585 char *kwlist[] = {"txt", "name", NULL};
3586 PyObject *result = NULL;
3587 char *txt;
3588 PyObject *pyname = Py_None;
3589 int name = 0;
3590 ASN1_OBJECT *obj;
3591
3592 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3593 kwlist, &txt, &pyname)) {
3594 return NULL;
3595 }
3596 name = PyObject_IsTrue(pyname);
3597 if (name < 0)
3598 return NULL;
3599 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3600 if (obj == NULL) {
3601 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3602 return NULL;
3603 }
3604 result = asn1obj2py(obj);
3605 ASN1_OBJECT_free(obj);
3606 return result;
3607}
3608
3609PyDoc_STRVAR(PySSL_nid2obj_doc,
3610"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3611\n\
3612Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3613
3614static PyObject*
3615PySSL_nid2obj(PyObject *self, PyObject *args)
3616{
3617 PyObject *result = NULL;
3618 int nid;
3619 ASN1_OBJECT *obj;
3620
3621 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3622 return NULL;
3623 }
3624 if (nid < NID_undef) {
3625 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3626 return NULL;
3627 }
3628 obj = OBJ_nid2obj(nid);
3629 if (obj == NULL) {
3630 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3631 return NULL;
3632 }
3633 result = asn1obj2py(obj);
3634 ASN1_OBJECT_free(obj);
3635 return result;
3636}
3637
3638#ifdef _MSC_VER
3639
3640static PyObject*
3641certEncodingType(DWORD encodingType)
3642{
3643 static PyObject *x509_asn = NULL;
3644 static PyObject *pkcs_7_asn = NULL;
3645
3646 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003647 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003648 if (x509_asn == NULL)
3649 return NULL;
3650 }
3651 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003652 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003653 if (pkcs_7_asn == NULL)
3654 return NULL;
3655 }
3656 switch(encodingType) {
3657 case X509_ASN_ENCODING:
3658 Py_INCREF(x509_asn);
3659 return x509_asn;
3660 case PKCS_7_ASN_ENCODING:
3661 Py_INCREF(pkcs_7_asn);
3662 return pkcs_7_asn;
3663 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003664 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003665 }
3666}
3667
3668static PyObject*
3669parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3670{
3671 CERT_ENHKEY_USAGE *usage;
3672 DWORD size, error, i;
3673 PyObject *retval;
3674
3675 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3676 error = GetLastError();
3677 if (error == CRYPT_E_NOT_FOUND) {
3678 Py_RETURN_TRUE;
3679 }
3680 return PyErr_SetFromWindowsErr(error);
3681 }
3682
3683 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3684 if (usage == NULL) {
3685 return PyErr_NoMemory();
3686 }
3687
3688 /* Now get the actual enhanced usage property */
3689 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3690 PyMem_Free(usage);
3691 error = GetLastError();
3692 if (error == CRYPT_E_NOT_FOUND) {
3693 Py_RETURN_TRUE;
3694 }
3695 return PyErr_SetFromWindowsErr(error);
3696 }
3697 retval = PySet_New(NULL);
3698 if (retval == NULL) {
3699 goto error;
3700 }
3701 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3702 if (usage->rgpszUsageIdentifier[i]) {
3703 PyObject *oid;
3704 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003705 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003706 if (oid == NULL) {
3707 Py_CLEAR(retval);
3708 goto error;
3709 }
3710 err = PySet_Add(retval, oid);
3711 Py_DECREF(oid);
3712 if (err == -1) {
3713 Py_CLEAR(retval);
3714 goto error;
3715 }
3716 }
3717 }
3718 error:
3719 PyMem_Free(usage);
3720 return retval;
3721}
3722
3723PyDoc_STRVAR(PySSL_enum_certificates_doc,
3724"enum_certificates(store_name) -> []\n\
3725\n\
3726Retrieve certificates from Windows' cert store. store_name may be one of\n\
3727'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3728The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3729encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3730PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3731boolean True.");
3732
3733static PyObject *
3734PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3735{
3736 char *kwlist[] = {"store_name", NULL};
3737 char *store_name;
3738 HCERTSTORE hStore = NULL;
3739 PCCERT_CONTEXT pCertCtx = NULL;
3740 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3741 PyObject *result = NULL;
3742
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003743 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003744 kwlist, &store_name)) {
3745 return NULL;
3746 }
3747 result = PyList_New(0);
3748 if (result == NULL) {
3749 return NULL;
3750 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003751 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3752 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3753 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003754 if (hStore == NULL) {
3755 Py_DECREF(result);
3756 return PyErr_SetFromWindowsErr(GetLastError());
3757 }
3758
3759 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3760 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3761 pCertCtx->cbCertEncoded);
3762 if (!cert) {
3763 Py_CLEAR(result);
3764 break;
3765 }
3766 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3767 Py_CLEAR(result);
3768 break;
3769 }
3770 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3771 if (keyusage == Py_True) {
3772 Py_DECREF(keyusage);
3773 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3774 }
3775 if (keyusage == NULL) {
3776 Py_CLEAR(result);
3777 break;
3778 }
3779 if ((tup = PyTuple_New(3)) == NULL) {
3780 Py_CLEAR(result);
3781 break;
3782 }
3783 PyTuple_SET_ITEM(tup, 0, cert);
3784 cert = NULL;
3785 PyTuple_SET_ITEM(tup, 1, enc);
3786 enc = NULL;
3787 PyTuple_SET_ITEM(tup, 2, keyusage);
3788 keyusage = NULL;
3789 if (PyList_Append(result, tup) < 0) {
3790 Py_CLEAR(result);
3791 break;
3792 }
3793 Py_CLEAR(tup);
3794 }
3795 if (pCertCtx) {
3796 /* loop ended with an error, need to clean up context manually */
3797 CertFreeCertificateContext(pCertCtx);
3798 }
3799
3800 /* In error cases cert, enc and tup may not be NULL */
3801 Py_XDECREF(cert);
3802 Py_XDECREF(enc);
3803 Py_XDECREF(keyusage);
3804 Py_XDECREF(tup);
3805
3806 if (!CertCloseStore(hStore, 0)) {
3807 /* This error case might shadow another exception.*/
3808 Py_XDECREF(result);
3809 return PyErr_SetFromWindowsErr(GetLastError());
3810 }
3811 return result;
3812}
3813
3814PyDoc_STRVAR(PySSL_enum_crls_doc,
3815"enum_crls(store_name) -> []\n\
3816\n\
3817Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3818'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3819The function returns a list of (bytes, encoding_type) tuples. The\n\
3820encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3821PKCS_7_ASN_ENCODING.");
3822
3823static PyObject *
3824PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3825{
3826 char *kwlist[] = {"store_name", NULL};
3827 char *store_name;
3828 HCERTSTORE hStore = NULL;
3829 PCCRL_CONTEXT pCrlCtx = NULL;
3830 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3831 PyObject *result = NULL;
3832
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003833 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003834 kwlist, &store_name)) {
3835 return NULL;
3836 }
3837 result = PyList_New(0);
3838 if (result == NULL) {
3839 return NULL;
3840 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003841 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3842 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3843 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003844 if (hStore == NULL) {
3845 Py_DECREF(result);
3846 return PyErr_SetFromWindowsErr(GetLastError());
3847 }
3848
3849 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3850 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3851 pCrlCtx->cbCrlEncoded);
3852 if (!crl) {
3853 Py_CLEAR(result);
3854 break;
3855 }
3856 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3857 Py_CLEAR(result);
3858 break;
3859 }
3860 if ((tup = PyTuple_New(2)) == NULL) {
3861 Py_CLEAR(result);
3862 break;
3863 }
3864 PyTuple_SET_ITEM(tup, 0, crl);
3865 crl = NULL;
3866 PyTuple_SET_ITEM(tup, 1, enc);
3867 enc = NULL;
3868
3869 if (PyList_Append(result, tup) < 0) {
3870 Py_CLEAR(result);
3871 break;
3872 }
3873 Py_CLEAR(tup);
3874 }
3875 if (pCrlCtx) {
3876 /* loop ended with an error, need to clean up context manually */
3877 CertFreeCRLContext(pCrlCtx);
3878 }
3879
3880 /* In error cases cert, enc and tup may not be NULL */
3881 Py_XDECREF(crl);
3882 Py_XDECREF(enc);
3883 Py_XDECREF(tup);
3884
3885 if (!CertCloseStore(hStore, 0)) {
3886 /* This error case might shadow another exception.*/
3887 Py_XDECREF(result);
3888 return PyErr_SetFromWindowsErr(GetLastError());
3889 }
3890 return result;
3891}
3892
3893#endif /* _MSC_VER */
3894
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003895/* List of functions exported by this module. */
3896
3897static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003898 {"_test_decode_cert", PySSL_test_decode_certificate,
3899 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003900#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003901 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3902 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003903 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3904 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003905#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003906#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003907 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3908 PySSL_RAND_egd_doc},
3909#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003910 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3911 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3912#ifdef _MSC_VER
3913 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3914 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3915 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3916 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3917#endif
3918 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3919 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3920 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3921 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003922 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003923};
3924
3925
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003926#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00003927
3928/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003929 * of the Python C thread library
3930 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3931 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003932
3933static PyThread_type_lock *_ssl_locks = NULL;
3934
Christian Heimes10107812013-08-19 17:36:29 +02003935#if OPENSSL_VERSION_NUMBER >= 0x10000000
3936/* use new CRYPTO_THREADID API. */
3937static void
3938_ssl_threadid_callback(CRYPTO_THREADID *id)
3939{
3940 CRYPTO_THREADID_set_numeric(id,
3941 (unsigned long)PyThread_get_thread_ident());
3942}
3943#else
3944/* deprecated CRYPTO_set_id_callback() API. */
3945static unsigned long
3946_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003947 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003948}
Christian Heimes10107812013-08-19 17:36:29 +02003949#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003950
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003951static void _ssl_thread_locking_function
3952 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003953 /* this function is needed to perform locking on shared data
3954 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003955 structures that will be implicitly shared whenever multiple
3956 threads use OpenSSL.) Multi-threaded applications will
3957 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003958
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003959 locking_function() must be able to handle up to
3960 CRYPTO_num_locks() different mutex locks. It sets the n-th
3961 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003962
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003963 file and line are the file number of the function setting the
3964 lock. They can be useful for debugging.
3965 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003966
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003967 if ((_ssl_locks == NULL) ||
3968 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3969 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003970
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003971 if (mode & CRYPTO_LOCK) {
3972 PyThread_acquire_lock(_ssl_locks[n], 1);
3973 } else {
3974 PyThread_release_lock(_ssl_locks[n]);
3975 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003976}
3977
3978static int _setup_ssl_threads(void) {
3979
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003980 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003981
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003982 if (_ssl_locks == NULL) {
3983 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003984 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3985 if (_ssl_locks == NULL) {
3986 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003987 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003988 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003989 memset(_ssl_locks, 0,
3990 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003991 for (i = 0; i < _ssl_locks_count; i++) {
3992 _ssl_locks[i] = PyThread_allocate_lock();
3993 if (_ssl_locks[i] == NULL) {
3994 unsigned int j;
3995 for (j = 0; j < i; j++) {
3996 PyThread_free_lock(_ssl_locks[j]);
3997 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003998 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003999 return 0;
4000 }
4001 }
4002 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004003#if OPENSSL_VERSION_NUMBER >= 0x10000000
4004 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4005#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004006 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004007#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004008 }
4009 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004010}
4011
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004012#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004014PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004015"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004016for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004017
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004018
4019
4020
4021static void
4022parse_openssl_version(unsigned long libver,
4023 unsigned int *major, unsigned int *minor,
4024 unsigned int *fix, unsigned int *patch,
4025 unsigned int *status)
4026{
4027 *status = libver & 0xF;
4028 libver >>= 4;
4029 *patch = libver & 0xFF;
4030 libver >>= 8;
4031 *fix = libver & 0xFF;
4032 libver >>= 8;
4033 *minor = libver & 0xFF;
4034 libver >>= 8;
4035 *major = libver & 0xFF;
4036}
4037
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004038PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004039init_ssl(void)
4040{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004041 PyObject *m, *d, *r;
4042 unsigned long libver;
4043 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004044 struct py_ssl_error_code *errcode;
4045 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004046
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004047 if (PyType_Ready(&PySSLContext_Type) < 0)
4048 return;
4049 if (PyType_Ready(&PySSLSocket_Type) < 0)
4050 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004051
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004052 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4053 if (m == NULL)
4054 return;
4055 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004056
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004057 /* Load _socket module and its C API */
4058 if (PySocketModule_ImportModuleAndAPI())
4059 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004060
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004061 /* Init OpenSSL */
4062 SSL_load_error_strings();
4063 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00004064#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004065#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004066 /* note that this will start threading if not already started */
4067 if (!_setup_ssl_threads()) {
4068 return;
4069 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004070#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4071 /* OpenSSL 1.1.0 builtin thread support is enabled */
4072 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004073#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004074#endif /* WITH_THREAD */
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004075 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004076
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004077 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004078 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4079 "ssl.SSLError", SSLError_doc,
4080 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004081 if (PySSLErrorObject == NULL)
4082 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004083 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4084
4085 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4086 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4087 PySSLErrorObject, NULL);
4088 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4089 "ssl.SSLWantReadError", SSLWantReadError_doc,
4090 PySSLErrorObject, NULL);
4091 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4092 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4093 PySSLErrorObject, NULL);
4094 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4095 "ssl.SSLSyscallError", SSLSyscallError_doc,
4096 PySSLErrorObject, NULL);
4097 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4098 "ssl.SSLEOFError", SSLEOFError_doc,
4099 PySSLErrorObject, NULL);
4100 if (PySSLZeroReturnErrorObject == NULL
4101 || PySSLWantReadErrorObject == NULL
4102 || PySSLWantWriteErrorObject == NULL
4103 || PySSLSyscallErrorObject == NULL
4104 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004105 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004106
4107 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4108 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4109 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4110 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4111 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4112
4113 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4114 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4115 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4116 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4117 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4118 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4119 return;
4120 if (PyDict_SetItemString(d, "_SSLContext",
4121 (PyObject *)&PySSLContext_Type) != 0)
4122 return;
4123 if (PyDict_SetItemString(d, "_SSLSocket",
4124 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004125 return;
4126 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4127 PY_SSL_ERROR_ZERO_RETURN);
4128 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4129 PY_SSL_ERROR_WANT_READ);
4130 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4131 PY_SSL_ERROR_WANT_WRITE);
4132 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4133 PY_SSL_ERROR_WANT_X509_LOOKUP);
4134 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4135 PY_SSL_ERROR_SYSCALL);
4136 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4137 PY_SSL_ERROR_SSL);
4138 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4139 PY_SSL_ERROR_WANT_CONNECT);
4140 /* non ssl.h errorcodes */
4141 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4142 PY_SSL_ERROR_EOF);
4143 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4144 PY_SSL_ERROR_INVALID_ERROR_CODE);
4145 /* cert requirements */
4146 PyModule_AddIntConstant(m, "CERT_NONE",
4147 PY_SSL_CERT_NONE);
4148 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4149 PY_SSL_CERT_OPTIONAL);
4150 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4151 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004152 /* CRL verification for verification_flags */
4153 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4154 0);
4155 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4156 X509_V_FLAG_CRL_CHECK);
4157 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4158 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4159 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4160 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004161#ifdef X509_V_FLAG_TRUSTED_FIRST
4162 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4163 X509_V_FLAG_TRUSTED_FIRST);
4164#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004165
4166 /* Alert Descriptions from ssl.h */
4167 /* note RESERVED constants no longer intended for use have been removed */
4168 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4169
4170#define ADD_AD_CONSTANT(s) \
4171 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4172 SSL_AD_##s)
4173
4174 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4175 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4176 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4177 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4178 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4179 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4180 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4181 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4182 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4183 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4184 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4185 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4186 ADD_AD_CONSTANT(UNKNOWN_CA);
4187 ADD_AD_CONSTANT(ACCESS_DENIED);
4188 ADD_AD_CONSTANT(DECODE_ERROR);
4189 ADD_AD_CONSTANT(DECRYPT_ERROR);
4190 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4191 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4192 ADD_AD_CONSTANT(INTERNAL_ERROR);
4193 ADD_AD_CONSTANT(USER_CANCELLED);
4194 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4195 /* Not all constants are in old OpenSSL versions */
4196#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4197 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4198#endif
4199#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4200 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4201#endif
4202#ifdef SSL_AD_UNRECOGNIZED_NAME
4203 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4204#endif
4205#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4206 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4207#endif
4208#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4209 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4210#endif
4211#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4212 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4213#endif
4214
4215#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004216
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004217 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004218#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004219 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4220 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004221#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004222#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004223 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4224 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004225#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004226 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004227 PY_SSL_VERSION_TLS);
4228 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4229 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004230 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4231 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004232#if HAVE_TLSv1_2
4233 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4234 PY_SSL_VERSION_TLS1_1);
4235 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4236 PY_SSL_VERSION_TLS1_2);
4237#endif
4238
4239 /* protocol options */
4240 PyModule_AddIntConstant(m, "OP_ALL",
4241 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4242 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4243 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4244 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4245#if HAVE_TLSv1_2
4246 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4247 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4248#endif
4249 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4250 SSL_OP_CIPHER_SERVER_PREFERENCE);
4251 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4252#ifdef SSL_OP_SINGLE_ECDH_USE
4253 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4254#endif
4255#ifdef SSL_OP_NO_COMPRESSION
4256 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4257 SSL_OP_NO_COMPRESSION);
4258#endif
4259
4260#if HAVE_SNI
4261 r = Py_True;
4262#else
4263 r = Py_False;
4264#endif
4265 Py_INCREF(r);
4266 PyModule_AddObject(m, "HAS_SNI", r);
4267
4268#if HAVE_OPENSSL_FINISHED
4269 r = Py_True;
4270#else
4271 r = Py_False;
4272#endif
4273 Py_INCREF(r);
4274 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4275
4276#ifdef OPENSSL_NO_ECDH
4277 r = Py_False;
4278#else
4279 r = Py_True;
4280#endif
4281 Py_INCREF(r);
4282 PyModule_AddObject(m, "HAS_ECDH", r);
4283
4284#ifdef OPENSSL_NPN_NEGOTIATED
4285 r = Py_True;
4286#else
4287 r = Py_False;
4288#endif
4289 Py_INCREF(r);
4290 PyModule_AddObject(m, "HAS_NPN", r);
4291
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004292#ifdef HAVE_ALPN
4293 r = Py_True;
4294#else
4295 r = Py_False;
4296#endif
4297 Py_INCREF(r);
4298 PyModule_AddObject(m, "HAS_ALPN", r);
4299
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004300 /* Mappings for error codes */
4301 err_codes_to_names = PyDict_New();
4302 err_names_to_codes = PyDict_New();
4303 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4304 return;
4305 errcode = error_codes;
4306 while (errcode->mnemonic != NULL) {
4307 PyObject *mnemo, *key;
4308 mnemo = PyUnicode_FromString(errcode->mnemonic);
4309 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4310 if (mnemo == NULL || key == NULL)
4311 return;
4312 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4313 return;
4314 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4315 return;
4316 Py_DECREF(key);
4317 Py_DECREF(mnemo);
4318 errcode++;
4319 }
4320 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4321 return;
4322 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4323 return;
4324
4325 lib_codes_to_names = PyDict_New();
4326 if (lib_codes_to_names == NULL)
4327 return;
4328 libcode = library_codes;
4329 while (libcode->library != NULL) {
4330 PyObject *mnemo, *key;
4331 key = PyLong_FromLong(libcode->code);
4332 mnemo = PyUnicode_FromString(libcode->library);
4333 if (key == NULL || mnemo == NULL)
4334 return;
4335 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4336 return;
4337 Py_DECREF(key);
4338 Py_DECREF(mnemo);
4339 libcode++;
4340 }
4341 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4342 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004343
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004344 /* OpenSSL version */
4345 /* SSLeay() gives us the version of the library linked against,
4346 which could be different from the headers version.
4347 */
4348 libver = SSLeay();
4349 r = PyLong_FromUnsignedLong(libver);
4350 if (r == NULL)
4351 return;
4352 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4353 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004354 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004355 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4356 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4357 return;
4358 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4359 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4360 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004361
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004362 libver = OPENSSL_VERSION_NUMBER;
4363 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4364 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4365 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4366 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004367}