blob: f09f9c9ea2f2834e4355d2c62646783f62da50c0 [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
Miss Islington (bot)a5c91122018-02-25 01:16:37 -080055#ifndef MS_WINDOWS
56/* inet_pton */
57#include <arpa/inet.h>
58#endif
59
Christian Heimesc2fc7c42016-09-05 23:37:13 +020060/* Don't warn about deprecated functions */
61#ifdef __GNUC__
62#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
63#endif
64#ifdef __clang__
65#pragma clang diagnostic ignored "-Wdeprecated-declarations"
66#endif
67
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000068/* Include OpenSSL header files */
69#include "openssl/rsa.h"
70#include "openssl/crypto.h"
71#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000072#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000073#include "openssl/pem.h"
74#include "openssl/ssl.h"
75#include "openssl/err.h"
76#include "openssl/rand.h"
77
78/* SSL error object */
79static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
100/* Include generated data (error codes) */
101#include "_ssl_data.h"
102
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200103#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
104# define OPENSSL_VERSION_1_1 1
105#endif
106
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500107/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
108 http://www.openssl.org/news/changelog.html
109 */
110#if OPENSSL_VERSION_NUMBER >= 0x10001000L
111# define HAVE_TLSv1_2 1
112#else
113# define HAVE_TLSv1_2 0
114#endif
115
116/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
117 * This includes the SSL_set_SSL_CTX() function.
118 */
119#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
120# define HAVE_SNI 1
121#else
122# define HAVE_SNI 0
123#endif
124
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500125/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500126#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500127# define HAVE_ALPN
128#endif
129
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200130#ifndef INVALID_SOCKET /* MS defines this */
131#define INVALID_SOCKET (-1)
132#endif
133
134#ifdef OPENSSL_VERSION_1_1
135/* OpenSSL 1.1.0+ */
136#ifndef OPENSSL_NO_SSL2
137#define OPENSSL_NO_SSL2
138#endif
139#else /* OpenSSL < 1.1.0 */
140#if defined(WITH_THREAD)
141#define HAVE_OPENSSL_CRYPTO_LOCK
142#endif
143
144#define TLS_method SSLv23_method
145
146static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147{
148 return ne->set;
149}
150
151#ifndef OPENSSL_NO_COMP
152static int COMP_get_type(const COMP_METHOD *meth)
153{
154 return meth->type;
155}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200156#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;
Christian Heimes72ed2332017-09-05 01:11:40 +0200288#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
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
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800583 if (server_hostname != NULL) {
584/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
585 * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
586 * available on all platforms. Use OpenSSL's IP address parser. It's
587 * available since 1.0.2 and LibreSSL since at least 2.3.0. */
588 int send_sni = 1;
589#if OPENSSL_VERSION_NUMBER >= 0x10200000L
590 ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
591 if (ip == NULL) {
592 send_sni = 1;
593 ERR_clear_error();
594 } else {
595 send_sni = 0;
596 ASN1_OCTET_STRING_free(ip);
597 }
598#elif defined(HAVE_INET_PTON)
599#ifdef ENABLE_IPV6
600 char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
601#else
602 char packed[sizeof(struct in_addr)];
603#endif /* ENABLE_IPV6 */
604 if (inet_pton(AF_INET, server_hostname, packed)) {
605 send_sni = 0;
606#ifdef ENABLE_IPV6
607 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
608 send_sni = 0;
609#endif /* ENABLE_IPV6 */
610 } else {
611 send_sni = 1;
612 }
613#endif /* HAVE_INET_PTON */
614 if (send_sni) {
615 SSL_set_tlsext_host_name(self->ssl, server_hostname);
616 }
617 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000618#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000619
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000620 /* If the socket is in non-blocking mode or timeout mode, set the BIO
621 * to non-blocking mode (blocking is the default)
622 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500623 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000624 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
625 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
626 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000627
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000628 PySSL_BEGIN_ALLOW_THREADS
629 if (socket_type == PY_SSL_CLIENT)
630 SSL_set_connect_state(self->ssl);
631 else
632 SSL_set_accept_state(self->ssl);
633 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000634
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500635 self->socket_type = socket_type;
636 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000637 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400638 if (ssl_sock != Py_None) {
639 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
640 if (self->ssl_sock == NULL) {
641 Py_DECREF(self);
642 return NULL;
643 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500644 }
645 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000646}
647
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000648
649/* SSL object methods */
650
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500651static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000652{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000653 int ret;
654 int err;
655 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500656 PySocketSockObject *sock = self->Socket;
657
658 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000659
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000660 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500661 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000662 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
663 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000664
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000665 /* Actually negotiate SSL connection */
666 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
667 do {
668 PySSL_BEGIN_ALLOW_THREADS
669 ret = SSL_do_handshake(self->ssl);
670 err = SSL_get_error(self->ssl, ret);
671 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500672 if (PyErr_CheckSignals())
673 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000674 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500675 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000676 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500677 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000678 } else {
679 sockstate = SOCKET_OPERATION_OK;
680 }
681 if (sockstate == SOCKET_HAS_TIMED_OUT) {
682 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000683 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500684 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000685 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
686 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000687 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500688 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000689 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
690 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000691 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500692 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000693 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
694 break;
695 }
696 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500697 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000698 if (ret < 1)
699 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000700
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000701 if (self->peer_cert)
702 X509_free (self->peer_cert);
703 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500704 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500706 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000707
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000708 Py_INCREF(Py_None);
709 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000710
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500711error:
712 Py_DECREF(sock);
713 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000714}
715
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000716static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200717_asn1obj2py(const ASN1_OBJECT *name, int no_name)
718{
719 char buf[X509_NAME_MAXLEN];
720 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000721 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200722 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000723
Christian Heimesc9d668c2017-09-05 19:13:07 +0200724 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000725 if (buflen < 0) {
726 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200727 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000728 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200729 /* initial buffer is too small for oid + terminating null byte */
730 if (buflen > X509_NAME_MAXLEN - 1) {
731 /* make OBJ_obj2txt() calculate the required buflen */
732 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
733 /* allocate len + 1 for terminating NULL byte */
734 namebuf = PyMem_Malloc(buflen + 1);
735 if (namebuf == NULL) {
736 PyErr_NoMemory();
737 return NULL;
738 }
739 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
740 if (buflen < 0) {
741 _setSSLError(NULL, 0, __FILE__, __LINE__);
742 goto done;
743 }
744 }
745 if (!buflen && no_name) {
746 Py_INCREF(Py_None);
747 name_obj = Py_None;
748 }
749 else {
750 name_obj = PyString_FromStringAndSize(namebuf, buflen);
751 }
752
753 done:
754 if (buf != namebuf) {
755 PyMem_Free(namebuf);
756 }
757 return name_obj;
758}
759
760static PyObject *
761_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
762{
763 Py_ssize_t buflen;
764 unsigned char *valuebuf = NULL;
765 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000766
767 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
768 if (buflen < 0) {
769 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200770 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000771 }
772 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000773 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000774
Christian Heimesc9d668c2017-09-05 19:13:07 +0200775 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
776 OPENSSL_free(valuebuf);
777 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000778}
779
780static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000781_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000782{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000783 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
784 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
785 PyObject *rdnt;
786 PyObject *attr = NULL; /* tuple to hold an attribute */
787 int entry_count = X509_NAME_entry_count(xname);
788 X509_NAME_ENTRY *entry;
789 ASN1_OBJECT *name;
790 ASN1_STRING *value;
791 int index_counter;
792 int rdn_level = -1;
793 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000794
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000795 dn = PyList_New(0);
796 if (dn == NULL)
797 return NULL;
798 /* now create another tuple to hold the top-level RDN */
799 rdn = PyList_New(0);
800 if (rdn == NULL)
801 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000802
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000803 for (index_counter = 0;
804 index_counter < entry_count;
805 index_counter++)
806 {
807 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000808
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000809 /* check to see if we've gotten to a new RDN */
810 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200811 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000812 /* yes, new RDN */
813 /* add old RDN to DN */
814 rdnt = PyList_AsTuple(rdn);
815 Py_DECREF(rdn);
816 if (rdnt == NULL)
817 goto fail0;
818 retcode = PyList_Append(dn, rdnt);
819 Py_DECREF(rdnt);
820 if (retcode < 0)
821 goto fail0;
822 /* create new RDN */
823 rdn = PyList_New(0);
824 if (rdn == NULL)
825 goto fail0;
826 }
827 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200828 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000829
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000830 /* now add this attribute to the current RDN */
831 name = X509_NAME_ENTRY_get_object(entry);
832 value = X509_NAME_ENTRY_get_data(entry);
833 attr = _create_tuple_for_attribute(name, value);
834 /*
835 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
836 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500837 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
838 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000839 */
840 if (attr == NULL)
841 goto fail1;
842 retcode = PyList_Append(rdn, attr);
843 Py_DECREF(attr);
844 if (retcode < 0)
845 goto fail1;
846 }
847 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100848 if (rdn != NULL) {
849 if (PyList_GET_SIZE(rdn) > 0) {
850 rdnt = PyList_AsTuple(rdn);
851 Py_DECREF(rdn);
852 if (rdnt == NULL)
853 goto fail0;
854 retcode = PyList_Append(dn, rdnt);
855 Py_DECREF(rdnt);
856 if (retcode < 0)
857 goto fail0;
858 }
859 else {
860 Py_DECREF(rdn);
861 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000862 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000863
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000864 /* convert list to tuple */
865 rdnt = PyList_AsTuple(dn);
866 Py_DECREF(dn);
867 if (rdnt == NULL)
868 return NULL;
869 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000870
871 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000872 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000873
874 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000875 Py_XDECREF(dn);
876 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000877}
878
879static PyObject *
880_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000881
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000882 /* this code follows the procedure outlined in
883 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
884 function to extract the STACK_OF(GENERAL_NAME),
885 then iterates through the stack to add the
886 names. */
887
888 int i, j;
889 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200890 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000891 X509_EXTENSION *ext = NULL;
892 GENERAL_NAMES *names = NULL;
893 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000894 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000895 BIO *biobuf = NULL;
896 char buf[2048];
897 char *vptr;
898 int len;
899 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000900#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000901 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000902#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000903 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000904#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000905
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000906 if (certificate == NULL)
907 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000908
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000909 /* get a memory buffer */
910 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000911
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200912 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000913 while ((i = X509_get_ext_by_NID(
914 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000915
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000916 if (peer_alt_names == Py_None) {
917 peer_alt_names = PyList_New(0);
918 if (peer_alt_names == NULL)
919 goto fail;
920 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000921
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000922 /* now decode the altName */
923 ext = X509_get_ext(certificate, i);
924 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500925 PyErr_SetString
926 (PySSLErrorObject,
927 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 goto fail;
929 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000930
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200931 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000932 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500933 names = (GENERAL_NAMES*)
934 (ASN1_item_d2i(NULL,
935 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200936 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500937 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000938 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500939 names = (GENERAL_NAMES*)
940 (method->d2i(NULL,
941 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200942 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000943
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000944 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000945 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200946 int gntype;
947 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000948
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000949 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200950 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200951 switch (gntype) {
952 case GEN_DIRNAME:
953 /* we special-case DirName as a tuple of
954 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000955
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000956 t = PyTuple_New(2);
957 if (t == NULL) {
958 goto fail;
959 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000960
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000961 v = PyString_FromString("DirName");
962 if (v == NULL) {
963 Py_DECREF(t);
964 goto fail;
965 }
966 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000967
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000968 v = _create_tuple_for_X509_NAME (name->d.dirn);
969 if (v == NULL) {
970 Py_DECREF(t);
971 goto fail;
972 }
973 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200974 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000975
Christian Heimes88b174c2013-08-17 00:54:47 +0200976 case GEN_EMAIL:
977 case GEN_DNS:
978 case GEN_URI:
979 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
980 correctly, CVE-2013-4238 */
981 t = PyTuple_New(2);
982 if (t == NULL)
983 goto fail;
984 switch (gntype) {
985 case GEN_EMAIL:
986 v = PyString_FromString("email");
987 as = name->d.rfc822Name;
988 break;
989 case GEN_DNS:
990 v = PyString_FromString("DNS");
991 as = name->d.dNSName;
992 break;
993 case GEN_URI:
994 v = PyString_FromString("URI");
995 as = name->d.uniformResourceIdentifier;
996 break;
997 }
998 if (v == NULL) {
999 Py_DECREF(t);
1000 goto fail;
1001 }
1002 PyTuple_SET_ITEM(t, 0, v);
1003 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1004 ASN1_STRING_length(as));
1005 if (v == NULL) {
1006 Py_DECREF(t);
1007 goto fail;
1008 }
1009 PyTuple_SET_ITEM(t, 1, v);
1010 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001011
Christian Heimes6663eb62016-09-06 23:25:35 +02001012 case GEN_RID:
1013 t = PyTuple_New(2);
1014 if (t == NULL)
1015 goto fail;
1016
1017 v = PyUnicode_FromString("Registered ID");
1018 if (v == NULL) {
1019 Py_DECREF(t);
1020 goto fail;
1021 }
1022 PyTuple_SET_ITEM(t, 0, v);
1023
1024 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1025 if (len < 0) {
1026 Py_DECREF(t);
1027 _setSSLError(NULL, 0, __FILE__, __LINE__);
1028 goto fail;
1029 } else if (len >= (int)sizeof(buf)) {
1030 v = PyUnicode_FromString("<INVALID>");
1031 } else {
1032 v = PyUnicode_FromStringAndSize(buf, len);
1033 }
1034 if (v == NULL) {
1035 Py_DECREF(t);
1036 goto fail;
1037 }
1038 PyTuple_SET_ITEM(t, 1, v);
1039 break;
1040
Christian Heimes88b174c2013-08-17 00:54:47 +02001041 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001042 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001043 switch (gntype) {
1044 /* check for new general name type */
1045 case GEN_OTHERNAME:
1046 case GEN_X400:
1047 case GEN_EDIPARTY:
1048 case GEN_IPADD:
1049 case GEN_RID:
1050 break;
1051 default:
1052 if (PyErr_Warn(PyExc_RuntimeWarning,
1053 "Unknown general name type") == -1) {
1054 goto fail;
1055 }
1056 break;
1057 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001058 (void) BIO_reset(biobuf);
1059 GENERAL_NAME_print(biobuf, name);
1060 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1061 if (len < 0) {
1062 _setSSLError(NULL, 0, __FILE__, __LINE__);
1063 goto fail;
1064 }
1065 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001066 if (vptr == NULL) {
1067 PyErr_Format(PyExc_ValueError,
1068 "Invalid value %.200s",
1069 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001070 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001071 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001072 t = PyTuple_New(2);
1073 if (t == NULL)
1074 goto fail;
1075 v = PyString_FromStringAndSize(buf, (vptr - buf));
1076 if (v == NULL) {
1077 Py_DECREF(t);
1078 goto fail;
1079 }
1080 PyTuple_SET_ITEM(t, 0, v);
1081 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1082 if (v == NULL) {
1083 Py_DECREF(t);
1084 goto fail;
1085 }
1086 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001087 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001088 }
1089
1090 /* and add that rendering to the list */
1091
1092 if (PyList_Append(peer_alt_names, t) < 0) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 Py_DECREF(t);
1097 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001098 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001099 }
1100 BIO_free(biobuf);
1101 if (peer_alt_names != Py_None) {
1102 v = PyList_AsTuple(peer_alt_names);
1103 Py_DECREF(peer_alt_names);
1104 return v;
1105 } else {
1106 return peer_alt_names;
1107 }
1108
Bill Janssen98d19da2007-09-10 21:51:02 +00001109
1110 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001111 if (biobuf != NULL)
1112 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001113
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001114 if (peer_alt_names != Py_None) {
1115 Py_XDECREF(peer_alt_names);
1116 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001117
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001118 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001119}
1120
1121static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001122_get_aia_uri(X509 *certificate, int nid) {
1123 PyObject *lst = NULL, *ostr = NULL;
1124 int i, result;
1125 AUTHORITY_INFO_ACCESS *info;
1126
1127 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001128 if (info == NULL)
1129 return Py_None;
1130 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1131 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001132 return Py_None;
1133 }
1134
1135 if ((lst = PyList_New(0)) == NULL) {
1136 goto fail;
1137 }
1138
1139 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1140 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1141 ASN1_IA5STRING *uri;
1142
1143 if ((OBJ_obj2nid(ad->method) != nid) ||
1144 (ad->location->type != GEN_URI)) {
1145 continue;
1146 }
1147 uri = ad->location->d.uniformResourceIdentifier;
1148 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1149 uri->length);
1150 if (ostr == NULL) {
1151 goto fail;
1152 }
1153 result = PyList_Append(lst, ostr);
1154 Py_DECREF(ostr);
1155 if (result < 0) {
1156 goto fail;
1157 }
1158 }
1159 AUTHORITY_INFO_ACCESS_free(info);
1160
1161 /* convert to tuple or None */
1162 if (PyList_Size(lst) == 0) {
1163 Py_DECREF(lst);
1164 return Py_None;
1165 } else {
1166 PyObject *tup;
1167 tup = PyList_AsTuple(lst);
1168 Py_DECREF(lst);
1169 return tup;
1170 }
1171
1172 fail:
1173 AUTHORITY_INFO_ACCESS_free(info);
1174 Py_XDECREF(lst);
1175 return NULL;
1176}
1177
1178static PyObject *
1179_get_crl_dp(X509 *certificate) {
1180 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001181 int i, j;
1182 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001183
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001184 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001185
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001186 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001187 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001188
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001189 lst = PyList_New(0);
1190 if (lst == NULL)
1191 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001192
1193 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1194 DIST_POINT *dp;
1195 STACK_OF(GENERAL_NAME) *gns;
1196
1197 dp = sk_DIST_POINT_value(dps, i);
1198 gns = dp->distpoint->name.fullname;
1199
1200 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1201 GENERAL_NAME *gn;
1202 ASN1_IA5STRING *uri;
1203 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001204 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001205
1206 gn = sk_GENERAL_NAME_value(gns, j);
1207 if (gn->type != GEN_URI) {
1208 continue;
1209 }
1210 uri = gn->d.uniformResourceIdentifier;
1211 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1212 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001213 if (ouri == NULL)
1214 goto done;
1215
1216 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001217 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001218 if (err < 0)
1219 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001220 }
1221 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001222
1223 /* Convert to tuple. */
1224 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1225
1226 done:
1227 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001228 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001229 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001230}
1231
1232static PyObject *
1233_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001234
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001235 PyObject *retval = NULL;
1236 BIO *biobuf = NULL;
1237 PyObject *peer;
1238 PyObject *peer_alt_names = NULL;
1239 PyObject *issuer;
1240 PyObject *version;
1241 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001242 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001243 ASN1_INTEGER *serialNumber;
1244 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001245 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001246 ASN1_TIME *notBefore, *notAfter;
1247 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001248
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001249 retval = PyDict_New();
1250 if (retval == NULL)
1251 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001252
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001253 peer = _create_tuple_for_X509_NAME(
1254 X509_get_subject_name(certificate));
1255 if (peer == NULL)
1256 goto fail0;
1257 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1258 Py_DECREF(peer);
1259 goto fail0;
1260 }
1261 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001262
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001263 issuer = _create_tuple_for_X509_NAME(
1264 X509_get_issuer_name(certificate));
1265 if (issuer == NULL)
1266 goto fail0;
1267 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001268 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001269 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001270 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001271 Py_DECREF(issuer);
1272
1273 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1274 if (version == NULL)
1275 goto fail0;
1276 if (PyDict_SetItemString(retval, "version", version) < 0) {
1277 Py_DECREF(version);
1278 goto fail0;
1279 }
1280 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001281
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001282 /* get a memory buffer */
1283 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001284
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001285 (void) BIO_reset(biobuf);
1286 serialNumber = X509_get_serialNumber(certificate);
1287 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1288 i2a_ASN1_INTEGER(biobuf, serialNumber);
1289 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1290 if (len < 0) {
1291 _setSSLError(NULL, 0, __FILE__, __LINE__);
1292 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001293 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001294 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1295 if (sn_obj == NULL)
1296 goto fail1;
1297 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1298 Py_DECREF(sn_obj);
1299 goto fail1;
1300 }
1301 Py_DECREF(sn_obj);
1302
1303 (void) BIO_reset(biobuf);
1304 notBefore = X509_get_notBefore(certificate);
1305 ASN1_TIME_print(biobuf, notBefore);
1306 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1307 if (len < 0) {
1308 _setSSLError(NULL, 0, __FILE__, __LINE__);
1309 goto fail1;
1310 }
1311 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1312 if (pnotBefore == NULL)
1313 goto fail1;
1314 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1315 Py_DECREF(pnotBefore);
1316 goto fail1;
1317 }
1318 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001319
1320 (void) BIO_reset(biobuf);
1321 notAfter = X509_get_notAfter(certificate);
1322 ASN1_TIME_print(biobuf, notAfter);
1323 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1324 if (len < 0) {
1325 _setSSLError(NULL, 0, __FILE__, __LINE__);
1326 goto fail1;
1327 }
1328 pnotAfter = PyString_FromStringAndSize(buf, len);
1329 if (pnotAfter == NULL)
1330 goto fail1;
1331 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1332 Py_DECREF(pnotAfter);
1333 goto fail1;
1334 }
1335 Py_DECREF(pnotAfter);
1336
1337 /* Now look for subjectAltName */
1338
1339 peer_alt_names = _get_peer_alt_names(certificate);
1340 if (peer_alt_names == NULL)
1341 goto fail1;
1342 else if (peer_alt_names != Py_None) {
1343 if (PyDict_SetItemString(retval, "subjectAltName",
1344 peer_alt_names) < 0) {
1345 Py_DECREF(peer_alt_names);
1346 goto fail1;
1347 }
1348 Py_DECREF(peer_alt_names);
1349 }
1350
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001351 /* Authority Information Access: OCSP URIs */
1352 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1353 if (obj == NULL) {
1354 goto fail1;
1355 } else if (obj != Py_None) {
1356 result = PyDict_SetItemString(retval, "OCSP", obj);
1357 Py_DECREF(obj);
1358 if (result < 0) {
1359 goto fail1;
1360 }
1361 }
1362
1363 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1364 if (obj == NULL) {
1365 goto fail1;
1366 } else if (obj != Py_None) {
1367 result = PyDict_SetItemString(retval, "caIssuers", obj);
1368 Py_DECREF(obj);
1369 if (result < 0) {
1370 goto fail1;
1371 }
1372 }
1373
1374 /* CDP (CRL distribution points) */
1375 obj = _get_crl_dp(certificate);
1376 if (obj == NULL) {
1377 goto fail1;
1378 } else if (obj != Py_None) {
1379 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1380 Py_DECREF(obj);
1381 if (result < 0) {
1382 goto fail1;
1383 }
1384 }
1385
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001386 BIO_free(biobuf);
1387 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001388
1389 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001390 if (biobuf != NULL)
1391 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001392 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001393 Py_XDECREF(retval);
1394 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001395}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001396
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001397static PyObject *
1398_certificate_to_der(X509 *certificate)
1399{
1400 unsigned char *bytes_buf = NULL;
1401 int len;
1402 PyObject *retval;
1403
1404 bytes_buf = NULL;
1405 len = i2d_X509(certificate, &bytes_buf);
1406 if (len < 0) {
1407 _setSSLError(NULL, 0, __FILE__, __LINE__);
1408 return NULL;
1409 }
1410 /* this is actually an immutable bytes sequence */
1411 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1412 OPENSSL_free(bytes_buf);
1413 return retval;
1414}
Bill Janssen98d19da2007-09-10 21:51:02 +00001415
1416static PyObject *
1417PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1418
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001419 PyObject *retval = NULL;
1420 char *filename = NULL;
1421 X509 *x=NULL;
1422 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001423
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001424 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001425 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001426
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001427 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001428 PyErr_SetString(PySSLErrorObject,
1429 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001430 goto fail0;
1431 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001432
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001433 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001434 PyErr_SetString(PySSLErrorObject,
1435 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001436 goto fail0;
1437 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001438
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001439 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1440 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001441 PyErr_SetString(PySSLErrorObject,
1442 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001443 goto fail0;
1444 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001445
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001446 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001447 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001448
1449 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001450
1451 if (cert != NULL) BIO_free(cert);
1452 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001453}
1454
1455
1456static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001457PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001458{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001459 int verification;
1460 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001461 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001462
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001463 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1464 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001465
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001466 if (!self->handshake_done) {
1467 PyErr_SetString(PyExc_ValueError,
1468 "handshake not done yet");
1469 return NULL;
1470 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001471 if (!self->peer_cert)
1472 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001473
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001474 b = PyObject_IsTrue(binary_mode);
1475 if (b < 0)
1476 return NULL;
1477 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001478 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001479 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001480 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001481 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001482 if ((verification & SSL_VERIFY_PEER) == 0)
1483 return PyDict_New();
1484 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001485 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001486 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001487}
1488
1489PyDoc_STRVAR(PySSL_peercert_doc,
1490"peer_certificate([der=False]) -> certificate\n\
1491\n\
1492Returns the certificate for the peer. If no certificate was provided,\n\
1493returns None. If a certificate was provided, but not validated, returns\n\
1494an empty dictionary. Otherwise returns a dict containing information\n\
1495about the peer certificate.\n\
1496\n\
1497If the optional argument is True, returns a DER-encoded copy of the\n\
1498peer certificate, or None if no certificate was provided. This will\n\
1499return the certificate even if it wasn't validated.");
1500
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001501static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001502
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001503 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001504 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001505 char *cipher_name;
1506 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001507
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001508 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001509 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001510 current = SSL_get_current_cipher(self->ssl);
1511 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001512 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001513
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001514 retval = PyTuple_New(3);
1515 if (retval == NULL)
1516 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001517
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001518 cipher_name = (char *) SSL_CIPHER_get_name(current);
1519 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001520 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001521 PyTuple_SET_ITEM(retval, 0, Py_None);
1522 } else {
1523 v = PyString_FromString(cipher_name);
1524 if (v == NULL)
1525 goto fail0;
1526 PyTuple_SET_ITEM(retval, 0, v);
1527 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001528 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001529 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001530 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001531 PyTuple_SET_ITEM(retval, 1, Py_None);
1532 } else {
1533 v = PyString_FromString(cipher_protocol);
1534 if (v == NULL)
1535 goto fail0;
1536 PyTuple_SET_ITEM(retval, 1, v);
1537 }
1538 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1539 if (v == NULL)
1540 goto fail0;
1541 PyTuple_SET_ITEM(retval, 2, v);
1542 return retval;
1543
Bill Janssen98d19da2007-09-10 21:51:02 +00001544 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001545 Py_DECREF(retval);
1546 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001547}
1548
Alex Gaynore98205d2014-09-04 13:33:22 -07001549static PyObject *PySSL_version(PySSLSocket *self)
1550{
1551 const char *version;
1552
1553 if (self->ssl == NULL)
1554 Py_RETURN_NONE;
1555 version = SSL_get_version(self->ssl);
1556 if (!strcmp(version, "unknown"))
1557 Py_RETURN_NONE;
1558 return PyUnicode_FromString(version);
1559}
1560
Christian Heimes72ed2332017-09-05 01:11:40 +02001561#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001562static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1563 const unsigned char *out;
1564 unsigned int outlen;
1565
1566 SSL_get0_next_proto_negotiated(self->ssl,
1567 &out, &outlen);
1568
1569 if (out == NULL)
1570 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001571 return PyString_FromStringAndSize((char *)out, outlen);
1572}
1573#endif
1574
1575#ifdef HAVE_ALPN
1576static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1577 const unsigned char *out;
1578 unsigned int outlen;
1579
1580 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1581
1582 if (out == NULL)
1583 Py_RETURN_NONE;
1584 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001585}
1586#endif
1587
1588static PyObject *PySSL_compression(PySSLSocket *self) {
1589#ifdef OPENSSL_NO_COMP
1590 Py_RETURN_NONE;
1591#else
1592 const COMP_METHOD *comp_method;
1593 const char *short_name;
1594
1595 if (self->ssl == NULL)
1596 Py_RETURN_NONE;
1597 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001598 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001599 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001600 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001601 if (short_name == NULL)
1602 Py_RETURN_NONE;
1603 return PyBytes_FromString(short_name);
1604#endif
1605}
1606
1607static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1608 Py_INCREF(self->ctx);
1609 return self->ctx;
1610}
1611
1612static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1613 void *closure) {
1614
1615 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1616#if !HAVE_SNI
1617 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1618 "context is not supported by your OpenSSL library");
1619 return -1;
1620#else
1621 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001622 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001623 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1624#endif
1625 } else {
1626 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1627 return -1;
1628 }
1629
1630 return 0;
1631}
1632
1633PyDoc_STRVAR(PySSL_set_context_doc,
1634"_setter_context(ctx)\n\
1635\
1636This changes the context associated with the SSLSocket. This is typically\n\
1637used from within a callback function set by the set_servername_callback\n\
1638on the SSLContext to change the certificate information associated with the\n\
1639SSLSocket before the cryptographic exchange handshake messages\n");
1640
1641
1642
1643static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001644{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001645 if (self->peer_cert) /* Possible not to have one? */
1646 X509_free (self->peer_cert);
1647 if (self->ssl)
1648 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001649 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001650 Py_XDECREF(self->ssl_sock);
1651 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001652 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001653}
1654
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001655/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001656 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001657 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001658 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001659
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001660static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001661check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001662{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001663 fd_set fds;
1664 struct timeval tv;
1665 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001666
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001667 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1668 if (s->sock_timeout < 0.0)
1669 return SOCKET_IS_BLOCKING;
1670 else if (s->sock_timeout == 0.0)
1671 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001672
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001673 /* Guard against closed socket */
1674 if (s->sock_fd < 0)
1675 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001677 /* Prefer poll, if available, since you can poll() any fd
1678 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001679#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001680 {
1681 struct pollfd pollfd;
1682 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001683
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001684 pollfd.fd = s->sock_fd;
1685 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001686
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001687 /* s->sock_timeout is in seconds, timeout in ms */
1688 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1689 PySSL_BEGIN_ALLOW_THREADS
1690 rc = poll(&pollfd, 1, timeout);
1691 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001692
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001693 goto normal_return;
1694 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001695#endif
1696
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001697 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001698 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001699 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001700
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001701 /* Construct the arguments to select */
1702 tv.tv_sec = (int)s->sock_timeout;
1703 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1704 FD_ZERO(&fds);
1705 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001706
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001707 /* See if the socket is ready */
1708 PySSL_BEGIN_ALLOW_THREADS
1709 if (writing)
1710 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1711 else
1712 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1713 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001714
Bill Janssen934b16d2008-06-28 22:19:33 +00001715#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001716normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001717#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1719 (when we are able to write or when there's something to read) */
1720 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001721}
1722
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001723static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001724{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001725 Py_buffer buf;
1726 int len;
1727 int sockstate;
1728 int err;
1729 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001730 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001731
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001732 Py_INCREF(sock);
1733
1734 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1735 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001736 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001737 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001738
Victor Stinnerc1a44262013-06-25 00:48:02 +02001739 if (buf.len > INT_MAX) {
1740 PyErr_Format(PyExc_OverflowError,
1741 "string longer than %d bytes", INT_MAX);
1742 goto error;
1743 }
1744
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001745 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001746 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001747 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1748 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001749
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001750 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001751 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1752 PyErr_SetString(PySSLErrorObject,
1753 "The write operation timed out");
1754 goto error;
1755 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1756 PyErr_SetString(PySSLErrorObject,
1757 "Underlying socket has been closed.");
1758 goto error;
1759 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1760 PyErr_SetString(PySSLErrorObject,
1761 "Underlying socket too large for select().");
1762 goto error;
1763 }
1764 do {
1765 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001766 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001767 err = SSL_get_error(self->ssl, len);
1768 PySSL_END_ALLOW_THREADS
1769 if (PyErr_CheckSignals()) {
1770 goto error;
1771 }
1772 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001773 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001774 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001775 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001776 } else {
1777 sockstate = SOCKET_OPERATION_OK;
1778 }
1779 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1780 PyErr_SetString(PySSLErrorObject,
1781 "The write operation timed out");
1782 goto error;
1783 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1784 PyErr_SetString(PySSLErrorObject,
1785 "Underlying socket has been closed.");
1786 goto error;
1787 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1788 break;
1789 }
1790 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001791
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001792 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001793 PyBuffer_Release(&buf);
1794 if (len > 0)
1795 return PyInt_FromLong(len);
1796 else
1797 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001798
1799error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001800 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001801 PyBuffer_Release(&buf);
1802 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001803}
1804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001805PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001806"write(s) -> len\n\
1807\n\
1808Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001809of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001810
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001811static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001812{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001813 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001814
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001815 PySSL_BEGIN_ALLOW_THREADS
1816 count = SSL_pending(self->ssl);
1817 PySSL_END_ALLOW_THREADS
1818 if (count < 0)
1819 return PySSL_SetError(self, count, __FILE__, __LINE__);
1820 else
1821 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001822}
1823
1824PyDoc_STRVAR(PySSL_SSLpending_doc,
1825"pending() -> count\n\
1826\n\
1827Returns the number of already decrypted bytes available for read,\n\
1828pending on the connection.\n");
1829
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001830static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001831{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001832 PyObject *dest = NULL;
1833 Py_buffer buf;
1834 char *mem;
1835 int len, count;
1836 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001837 int sockstate;
1838 int err;
1839 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001840 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001841
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001842 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001843
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844 buf.obj = NULL;
1845 buf.buf = NULL;
1846 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1847 goto error;
1848
1849 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001850 if (len < 0) {
1851 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1852 goto error;
1853 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001854 dest = PyBytes_FromStringAndSize(NULL, len);
1855 if (dest == NULL)
1856 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001857 if (len == 0) {
1858 Py_XDECREF(sock);
1859 return dest;
1860 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001861 mem = PyBytes_AS_STRING(dest);
1862 }
1863 else {
1864 buf_passed = 1;
1865 mem = buf.buf;
1866 if (len <= 0 || len > buf.len) {
1867 len = (int) buf.len;
1868 if (buf.len != len) {
1869 PyErr_SetString(PyExc_OverflowError,
1870 "maximum length can't fit in a C 'int'");
1871 goto error;
1872 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001873 if (len == 0) {
1874 count = 0;
1875 goto done;
1876 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001877 }
1878 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001879
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001880 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001881 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001882 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1883 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001884
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001885 do {
1886 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001887 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001888 err = SSL_get_error(self->ssl, count);
1889 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001890 if (PyErr_CheckSignals())
1891 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001892 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001893 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001894 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001895 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001896 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1897 (SSL_get_shutdown(self->ssl) ==
1898 SSL_RECEIVED_SHUTDOWN))
1899 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001900 count = 0;
1901 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001902 } else {
1903 sockstate = SOCKET_OPERATION_OK;
1904 }
1905 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1906 PyErr_SetString(PySSLErrorObject,
1907 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001908 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001909 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1910 break;
1911 }
1912 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1913 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001914 PySSL_SetError(self, count, __FILE__, __LINE__);
1915 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001916 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001917
1918done:
1919 Py_DECREF(sock);
1920 if (!buf_passed) {
1921 _PyBytes_Resize(&dest, count);
1922 return dest;
1923 }
1924 else {
1925 PyBuffer_Release(&buf);
1926 return PyLong_FromLong(count);
1927 }
1928
1929error:
1930 Py_DECREF(sock);
1931 if (!buf_passed)
1932 Py_XDECREF(dest);
1933 else
1934 PyBuffer_Release(&buf);
1935 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001936}
1937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001939"read([len]) -> string\n\
1940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001941Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001943static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001944{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001945 int err, ssl_err, sockstate, nonblocking;
1946 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001947 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001948
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001949 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001950 if (sock->sock_fd < 0) {
1951 _setSSLError("Underlying socket connection gone",
1952 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001953 return NULL;
1954 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001955 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001956
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001957 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001958 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001959 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1960 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001961
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001962 while (1) {
1963 PySSL_BEGIN_ALLOW_THREADS
1964 /* Disable read-ahead so that unwrap can work correctly.
1965 * Otherwise OpenSSL might read in too much data,
1966 * eating clear text data that happens to be
1967 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001968 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001969 * function is used and the shutdown_seen_zero != 0
1970 * condition is met.
1971 */
1972 if (self->shutdown_seen_zero)
1973 SSL_set_read_ahead(self->ssl, 0);
1974 err = SSL_shutdown(self->ssl);
1975 PySSL_END_ALLOW_THREADS
1976 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1977 if (err > 0)
1978 break;
1979 if (err == 0) {
1980 /* Don't loop endlessly; instead preserve legacy
1981 behaviour of trying SSL_shutdown() only twice.
1982 This looks necessary for OpenSSL < 0.9.8m */
1983 if (++zeros > 1)
1984 break;
1985 /* Shutdown was sent, now try receiving */
1986 self->shutdown_seen_zero = 1;
1987 continue;
1988 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001989
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001990 /* Possibly retry shutdown until timeout or failure */
1991 ssl_err = SSL_get_error(self->ssl, err);
1992 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001993 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001994 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001995 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001996 else
1997 break;
1998 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1999 if (ssl_err == SSL_ERROR_WANT_READ)
2000 PyErr_SetString(PySSLErrorObject,
2001 "The read operation timed out");
2002 else
2003 PyErr_SetString(PySSLErrorObject,
2004 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002005 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002006 }
2007 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2008 PyErr_SetString(PySSLErrorObject,
2009 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002010 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002011 }
2012 else if (sockstate != SOCKET_OPERATION_OK)
2013 /* Retain the SSL error code */
2014 break;
2015 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002016
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002017 if (err < 0) {
2018 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002019 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002020 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002021 else
2022 /* It's already INCREF'ed */
2023 return (PyObject *) sock;
2024
2025error:
2026 Py_DECREF(sock);
2027 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002028}
2029
2030PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2031"shutdown(s) -> socket\n\
2032\n\
2033Does the SSL shutdown handshake with the remote end, and returns\n\
2034the underlying socket object.");
2035
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002036#if HAVE_OPENSSL_FINISHED
2037static PyObject *
2038PySSL_tls_unique_cb(PySSLSocket *self)
2039{
2040 PyObject *retval = NULL;
2041 char buf[PySSL_CB_MAXLEN];
2042 size_t len;
2043
2044 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2045 /* if session is resumed XOR we are the client */
2046 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2047 }
2048 else {
2049 /* if a new session XOR we are the server */
2050 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2051 }
2052
2053 /* It cannot be negative in current OpenSSL version as of July 2011 */
2054 if (len == 0)
2055 Py_RETURN_NONE;
2056
2057 retval = PyBytes_FromStringAndSize(buf, len);
2058
2059 return retval;
2060}
2061
2062PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2063"tls_unique_cb() -> bytes\n\
2064\n\
2065Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2066\n\
2067If the TLS handshake is not yet complete, None is returned");
2068
2069#endif /* HAVE_OPENSSL_FINISHED */
2070
2071static PyGetSetDef ssl_getsetlist[] = {
2072 {"context", (getter) PySSL_get_context,
2073 (setter) PySSL_set_context, PySSL_set_context_doc},
2074 {NULL}, /* sentinel */
2075};
2076
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002077static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002078 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2079 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2080 PySSL_SSLwrite_doc},
2081 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2082 PySSL_SSLread_doc},
2083 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2084 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002085 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2086 PySSL_peercert_doc},
2087 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002088 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002089#ifdef OPENSSL_NPN_NEGOTIATED
2090 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2091#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002092#ifdef HAVE_ALPN
2093 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2094#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002095 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002096 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2097 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002098#if HAVE_OPENSSL_FINISHED
2099 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2100 PySSL_tls_unique_cb_doc},
2101#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002102 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002103};
2104
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002105static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002106 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002107 "_ssl._SSLSocket", /*tp_name*/
2108 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002109 0, /*tp_itemsize*/
2110 /* methods */
2111 (destructor)PySSL_dealloc, /*tp_dealloc*/
2112 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002113 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002114 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002115 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002116 0, /*tp_repr*/
2117 0, /*tp_as_number*/
2118 0, /*tp_as_sequence*/
2119 0, /*tp_as_mapping*/
2120 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002121 0, /*tp_call*/
2122 0, /*tp_str*/
2123 0, /*tp_getattro*/
2124 0, /*tp_setattro*/
2125 0, /*tp_as_buffer*/
2126 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2127 0, /*tp_doc*/
2128 0, /*tp_traverse*/
2129 0, /*tp_clear*/
2130 0, /*tp_richcompare*/
2131 0, /*tp_weaklistoffset*/
2132 0, /*tp_iter*/
2133 0, /*tp_iternext*/
2134 PySSLMethods, /*tp_methods*/
2135 0, /*tp_members*/
2136 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002137};
2138
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002139
2140/*
2141 * _SSLContext objects
2142 */
2143
2144static PyObject *
2145context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2146{
2147 char *kwlist[] = {"protocol", NULL};
2148 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002149 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002150 long options;
2151 SSL_CTX *ctx = NULL;
2152
2153 if (!PyArg_ParseTupleAndKeywords(
2154 args, kwds, "i:_SSLContext", kwlist,
2155 &proto_version))
2156 return NULL;
2157
2158 PySSL_BEGIN_ALLOW_THREADS
2159 if (proto_version == PY_SSL_VERSION_TLS1)
2160 ctx = SSL_CTX_new(TLSv1_method());
2161#if HAVE_TLSv1_2
2162 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2163 ctx = SSL_CTX_new(TLSv1_1_method());
2164 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2165 ctx = SSL_CTX_new(TLSv1_2_method());
2166#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002167#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002168 else if (proto_version == PY_SSL_VERSION_SSL3)
2169 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002170#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002171#ifndef OPENSSL_NO_SSL2
2172 else if (proto_version == PY_SSL_VERSION_SSL2)
2173 ctx = SSL_CTX_new(SSLv2_method());
2174#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002175 else if (proto_version == PY_SSL_VERSION_TLS)
2176 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002177 else
2178 proto_version = -1;
2179 PySSL_END_ALLOW_THREADS
2180
2181 if (proto_version == -1) {
2182 PyErr_SetString(PyExc_ValueError,
2183 "invalid protocol version");
2184 return NULL;
2185 }
2186 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002187 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002188 return NULL;
2189 }
2190
2191 assert(type != NULL && type->tp_alloc != NULL);
2192 self = (PySSLContext *) type->tp_alloc(type, 0);
2193 if (self == NULL) {
2194 SSL_CTX_free(ctx);
2195 return NULL;
2196 }
2197 self->ctx = ctx;
Christian Heimes72ed2332017-09-05 01:11:40 +02002198#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002199 self->npn_protocols = NULL;
2200#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002201#ifdef HAVE_ALPN
2202 self->alpn_protocols = NULL;
2203#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002204#ifndef OPENSSL_NO_TLSEXT
2205 self->set_hostname = NULL;
2206#endif
2207 /* Don't check host name by default */
2208 self->check_hostname = 0;
2209 /* Defaults */
2210 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2211 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2212 if (proto_version != PY_SSL_VERSION_SSL2)
2213 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002214 if (proto_version != PY_SSL_VERSION_SSL3)
2215 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002216 SSL_CTX_set_options(self->ctx, options);
2217
Donald Stufftf1a696e2017-03-02 12:37:07 -05002218#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002219 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2220 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002221 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2222 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002223#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002224 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2225#else
2226 {
2227 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2228 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2229 EC_KEY_free(key);
2230 }
2231#endif
2232#endif
2233
2234#define SID_CTX "Python"
2235 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2236 sizeof(SID_CTX));
2237#undef SID_CTX
2238
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002239#ifdef X509_V_FLAG_TRUSTED_FIRST
2240 {
2241 /* Improve trust chain building when cross-signed intermediate
2242 certificates are present. See https://bugs.python.org/issue23476. */
2243 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2244 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2245 }
2246#endif
2247
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002248 return (PyObject *)self;
2249}
2250
2251static int
2252context_traverse(PySSLContext *self, visitproc visit, void *arg)
2253{
2254#ifndef OPENSSL_NO_TLSEXT
2255 Py_VISIT(self->set_hostname);
2256#endif
2257 return 0;
2258}
2259
2260static int
2261context_clear(PySSLContext *self)
2262{
2263#ifndef OPENSSL_NO_TLSEXT
2264 Py_CLEAR(self->set_hostname);
2265#endif
2266 return 0;
2267}
2268
2269static void
2270context_dealloc(PySSLContext *self)
2271{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002272 /* bpo-31095: UnTrack is needed before calling any callbacks */
2273 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002274 context_clear(self);
2275 SSL_CTX_free(self->ctx);
Christian Heimes72ed2332017-09-05 01:11:40 +02002276#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002277 PyMem_FREE(self->npn_protocols);
2278#endif
2279#ifdef HAVE_ALPN
2280 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002281#endif
2282 Py_TYPE(self)->tp_free(self);
2283}
2284
2285static PyObject *
2286set_ciphers(PySSLContext *self, PyObject *args)
2287{
2288 int ret;
2289 const char *cipherlist;
2290
2291 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2292 return NULL;
2293 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2294 if (ret == 0) {
2295 /* Clearing the error queue is necessary on some OpenSSL versions,
2296 otherwise the error will be reported again when another SSL call
2297 is done. */
2298 ERR_clear_error();
2299 PyErr_SetString(PySSLErrorObject,
2300 "No cipher can be selected.");
2301 return NULL;
2302 }
2303 Py_RETURN_NONE;
2304}
2305
Christian Heimes72ed2332017-09-05 01:11:40 +02002306#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002307static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002308do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2309 const unsigned char *server_protocols, unsigned int server_protocols_len,
2310 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002311{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002312 int ret;
2313 if (client_protocols == NULL) {
2314 client_protocols = (unsigned char *)"";
2315 client_protocols_len = 0;
2316 }
2317 if (server_protocols == NULL) {
2318 server_protocols = (unsigned char *)"";
2319 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002320 }
2321
Benjamin Petersonaa707582015-01-23 17:30:26 -05002322 ret = SSL_select_next_proto(out, outlen,
2323 server_protocols, server_protocols_len,
2324 client_protocols, client_protocols_len);
2325 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2326 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002327
2328 return SSL_TLSEXT_ERR_OK;
2329}
Christian Heimes72ed2332017-09-05 01:11:40 +02002330#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002331
Christian Heimes72ed2332017-09-05 01:11:40 +02002332#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002333/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2334static int
2335_advertiseNPN_cb(SSL *s,
2336 const unsigned char **data, unsigned int *len,
2337 void *args)
2338{
2339 PySSLContext *ssl_ctx = (PySSLContext *) args;
2340
2341 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002342 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002343 *len = 0;
2344 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002345 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002346 *len = ssl_ctx->npn_protocols_len;
2347 }
2348
2349 return SSL_TLSEXT_ERR_OK;
2350}
2351/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2352static int
2353_selectNPN_cb(SSL *s,
2354 unsigned char **out, unsigned char *outlen,
2355 const unsigned char *server, unsigned int server_len,
2356 void *args)
2357{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002358 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002359 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002360 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002361}
2362#endif
2363
2364static PyObject *
2365_set_npn_protocols(PySSLContext *self, PyObject *args)
2366{
Christian Heimes72ed2332017-09-05 01:11:40 +02002367#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002368 Py_buffer protos;
2369
2370 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2371 return NULL;
2372
2373 if (self->npn_protocols != NULL) {
2374 PyMem_Free(self->npn_protocols);
2375 }
2376
2377 self->npn_protocols = PyMem_Malloc(protos.len);
2378 if (self->npn_protocols == NULL) {
2379 PyBuffer_Release(&protos);
2380 return PyErr_NoMemory();
2381 }
2382 memcpy(self->npn_protocols, protos.buf, protos.len);
2383 self->npn_protocols_len = (int) protos.len;
2384
2385 /* set both server and client callbacks, because the context can
2386 * be used to create both types of sockets */
2387 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2388 _advertiseNPN_cb,
2389 self);
2390 SSL_CTX_set_next_proto_select_cb(self->ctx,
2391 _selectNPN_cb,
2392 self);
2393
2394 PyBuffer_Release(&protos);
2395 Py_RETURN_NONE;
2396#else
2397 PyErr_SetString(PyExc_NotImplementedError,
2398 "The NPN extension requires OpenSSL 1.0.1 or later.");
2399 return NULL;
2400#endif
2401}
2402
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002403#ifdef HAVE_ALPN
2404static int
2405_selectALPN_cb(SSL *s,
2406 const unsigned char **out, unsigned char *outlen,
2407 const unsigned char *client_protocols, unsigned int client_protocols_len,
2408 void *args)
2409{
2410 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002411 return do_protocol_selection(1, (unsigned char **)out, outlen,
2412 ctx->alpn_protocols, ctx->alpn_protocols_len,
2413 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002414}
2415#endif
2416
2417static PyObject *
2418_set_alpn_protocols(PySSLContext *self, PyObject *args)
2419{
2420#ifdef HAVE_ALPN
2421 Py_buffer protos;
2422
2423 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2424 return NULL;
2425
2426 PyMem_FREE(self->alpn_protocols);
2427 self->alpn_protocols = PyMem_Malloc(protos.len);
2428 if (!self->alpn_protocols)
2429 return PyErr_NoMemory();
2430 memcpy(self->alpn_protocols, protos.buf, protos.len);
2431 self->alpn_protocols_len = protos.len;
2432 PyBuffer_Release(&protos);
2433
2434 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2435 return PyErr_NoMemory();
2436 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2437
2438 PyBuffer_Release(&protos);
2439 Py_RETURN_NONE;
2440#else
2441 PyErr_SetString(PyExc_NotImplementedError,
2442 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2443 return NULL;
2444#endif
2445}
2446
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002447static PyObject *
2448get_verify_mode(PySSLContext *self, void *c)
2449{
2450 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2451 case SSL_VERIFY_NONE:
2452 return PyLong_FromLong(PY_SSL_CERT_NONE);
2453 case SSL_VERIFY_PEER:
2454 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2455 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2456 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2457 }
2458 PyErr_SetString(PySSLErrorObject,
2459 "invalid return value from SSL_CTX_get_verify_mode");
2460 return NULL;
2461}
2462
2463static int
2464set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2465{
2466 int n, mode;
2467 if (!PyArg_Parse(arg, "i", &n))
2468 return -1;
2469 if (n == PY_SSL_CERT_NONE)
2470 mode = SSL_VERIFY_NONE;
2471 else if (n == PY_SSL_CERT_OPTIONAL)
2472 mode = SSL_VERIFY_PEER;
2473 else if (n == PY_SSL_CERT_REQUIRED)
2474 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2475 else {
2476 PyErr_SetString(PyExc_ValueError,
2477 "invalid value for verify_mode");
2478 return -1;
2479 }
2480 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2481 PyErr_SetString(PyExc_ValueError,
2482 "Cannot set verify_mode to CERT_NONE when "
2483 "check_hostname is enabled.");
2484 return -1;
2485 }
2486 SSL_CTX_set_verify(self->ctx, mode, NULL);
2487 return 0;
2488}
2489
2490#ifdef HAVE_OPENSSL_VERIFY_PARAM
2491static PyObject *
2492get_verify_flags(PySSLContext *self, void *c)
2493{
2494 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002495 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002496 unsigned long flags;
2497
2498 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002499 param = X509_STORE_get0_param(store);
2500 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002501 return PyLong_FromUnsignedLong(flags);
2502}
2503
2504static int
2505set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2506{
2507 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002508 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002509 unsigned long new_flags, flags, set, clear;
2510
2511 if (!PyArg_Parse(arg, "k", &new_flags))
2512 return -1;
2513 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002514 param = X509_STORE_get0_param(store);
2515 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002516 clear = flags & ~new_flags;
2517 set = ~flags & new_flags;
2518 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002519 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002520 _setSSLError(NULL, 0, __FILE__, __LINE__);
2521 return -1;
2522 }
2523 }
2524 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002525 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002526 _setSSLError(NULL, 0, __FILE__, __LINE__);
2527 return -1;
2528 }
2529 }
2530 return 0;
2531}
2532#endif
2533
2534static PyObject *
2535get_options(PySSLContext *self, void *c)
2536{
2537 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2538}
2539
2540static int
2541set_options(PySSLContext *self, PyObject *arg, void *c)
2542{
2543 long new_opts, opts, set, clear;
2544 if (!PyArg_Parse(arg, "l", &new_opts))
2545 return -1;
2546 opts = SSL_CTX_get_options(self->ctx);
2547 clear = opts & ~new_opts;
2548 set = ~opts & new_opts;
2549 if (clear) {
2550#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2551 SSL_CTX_clear_options(self->ctx, clear);
2552#else
2553 PyErr_SetString(PyExc_ValueError,
2554 "can't clear options before OpenSSL 0.9.8m");
2555 return -1;
2556#endif
2557 }
2558 if (set)
2559 SSL_CTX_set_options(self->ctx, set);
2560 return 0;
2561}
2562
2563static PyObject *
2564get_check_hostname(PySSLContext *self, void *c)
2565{
2566 return PyBool_FromLong(self->check_hostname);
2567}
2568
2569static int
2570set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2571{
2572 PyObject *py_check_hostname;
2573 int check_hostname;
2574 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2575 return -1;
2576
2577 check_hostname = PyObject_IsTrue(py_check_hostname);
2578 if (check_hostname < 0)
2579 return -1;
2580 if (check_hostname &&
2581 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2582 PyErr_SetString(PyExc_ValueError,
2583 "check_hostname needs a SSL context with either "
2584 "CERT_OPTIONAL or CERT_REQUIRED");
2585 return -1;
2586 }
2587 self->check_hostname = check_hostname;
2588 return 0;
2589}
2590
2591
2592typedef struct {
2593 PyThreadState *thread_state;
2594 PyObject *callable;
2595 char *password;
2596 int size;
2597 int error;
2598} _PySSLPasswordInfo;
2599
2600static int
2601_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2602 const char *bad_type_error)
2603{
2604 /* Set the password and size fields of a _PySSLPasswordInfo struct
2605 from a unicode, bytes, or byte array object.
2606 The password field will be dynamically allocated and must be freed
2607 by the caller */
2608 PyObject *password_bytes = NULL;
2609 const char *data = NULL;
2610 Py_ssize_t size;
2611
2612 if (PyUnicode_Check(password)) {
2613 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2614 if (!password_bytes) {
2615 goto error;
2616 }
2617 data = PyBytes_AS_STRING(password_bytes);
2618 size = PyBytes_GET_SIZE(password_bytes);
2619 } else if (PyBytes_Check(password)) {
2620 data = PyBytes_AS_STRING(password);
2621 size = PyBytes_GET_SIZE(password);
2622 } else if (PyByteArray_Check(password)) {
2623 data = PyByteArray_AS_STRING(password);
2624 size = PyByteArray_GET_SIZE(password);
2625 } else {
2626 PyErr_SetString(PyExc_TypeError, bad_type_error);
2627 goto error;
2628 }
2629
2630 if (size > (Py_ssize_t)INT_MAX) {
2631 PyErr_Format(PyExc_ValueError,
2632 "password cannot be longer than %d bytes", INT_MAX);
2633 goto error;
2634 }
2635
2636 PyMem_Free(pw_info->password);
2637 pw_info->password = PyMem_Malloc(size);
2638 if (!pw_info->password) {
2639 PyErr_SetString(PyExc_MemoryError,
2640 "unable to allocate password buffer");
2641 goto error;
2642 }
2643 memcpy(pw_info->password, data, size);
2644 pw_info->size = (int)size;
2645
2646 Py_XDECREF(password_bytes);
2647 return 1;
2648
2649error:
2650 Py_XDECREF(password_bytes);
2651 return 0;
2652}
2653
2654static int
2655_password_callback(char *buf, int size, int rwflag, void *userdata)
2656{
2657 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2658 PyObject *fn_ret = NULL;
2659
2660 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2661
2662 if (pw_info->callable) {
2663 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2664 if (!fn_ret) {
2665 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2666 core python API, so we could use it to add a frame here */
2667 goto error;
2668 }
2669
2670 if (!_pwinfo_set(pw_info, fn_ret,
2671 "password callback must return a string")) {
2672 goto error;
2673 }
2674 Py_CLEAR(fn_ret);
2675 }
2676
2677 if (pw_info->size > size) {
2678 PyErr_Format(PyExc_ValueError,
2679 "password cannot be longer than %d bytes", size);
2680 goto error;
2681 }
2682
2683 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2684 memcpy(buf, pw_info->password, pw_info->size);
2685 return pw_info->size;
2686
2687error:
2688 Py_XDECREF(fn_ret);
2689 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2690 pw_info->error = 1;
2691 return -1;
2692}
2693
2694static PyObject *
2695load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2696{
2697 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002698 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2699 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002700 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2701 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002702 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2703 int r;
2704
2705 errno = 0;
2706 ERR_clear_error();
2707 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002708 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002709 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002710 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002711 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002712
2713 if (keyfile && keyfile != Py_None) {
2714 if (PyString_Check(keyfile)) {
2715 Py_INCREF(keyfile);
2716 keyfile_bytes = keyfile;
2717 } else {
2718 PyObject *u = PyUnicode_FromObject(keyfile);
2719 if (!u)
2720 goto error;
2721 keyfile_bytes = PyUnicode_AsEncodedString(
2722 u, Py_FileSystemDefaultEncoding, NULL);
2723 Py_DECREF(u);
2724 if (!keyfile_bytes)
2725 goto error;
2726 }
2727 }
2728
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002729 if (password && password != Py_None) {
2730 if (PyCallable_Check(password)) {
2731 pw_info.callable = password;
2732 } else if (!_pwinfo_set(&pw_info, password,
2733 "password should be a string or callable")) {
2734 goto error;
2735 }
2736 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2737 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2738 }
2739 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2740 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2741 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2742 if (r != 1) {
2743 if (pw_info.error) {
2744 ERR_clear_error();
2745 /* the password callback has already set the error information */
2746 }
2747 else if (errno != 0) {
2748 ERR_clear_error();
2749 PyErr_SetFromErrno(PyExc_IOError);
2750 }
2751 else {
2752 _setSSLError(NULL, 0, __FILE__, __LINE__);
2753 }
2754 goto error;
2755 }
2756 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2757 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002758 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002759 SSL_FILETYPE_PEM);
2760 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2761 if (r != 1) {
2762 if (pw_info.error) {
2763 ERR_clear_error();
2764 /* the password callback has already set the error information */
2765 }
2766 else if (errno != 0) {
2767 ERR_clear_error();
2768 PyErr_SetFromErrno(PyExc_IOError);
2769 }
2770 else {
2771 _setSSLError(NULL, 0, __FILE__, __LINE__);
2772 }
2773 goto error;
2774 }
2775 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2776 r = SSL_CTX_check_private_key(self->ctx);
2777 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2778 if (r != 1) {
2779 _setSSLError(NULL, 0, __FILE__, __LINE__);
2780 goto error;
2781 }
2782 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2783 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002784 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002785 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002786 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002787 Py_RETURN_NONE;
2788
2789error:
2790 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2791 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002792 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002793 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002794 PyMem_Free(certfile_bytes);
2795 return NULL;
2796}
2797
2798/* internal helper function, returns -1 on error
2799 */
2800static int
2801_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2802 int filetype)
2803{
2804 BIO *biobuf = NULL;
2805 X509_STORE *store;
2806 int retval = 0, err, loaded = 0;
2807
2808 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2809
2810 if (len <= 0) {
2811 PyErr_SetString(PyExc_ValueError,
2812 "Empty certificate data");
2813 return -1;
2814 } else if (len > INT_MAX) {
2815 PyErr_SetString(PyExc_OverflowError,
2816 "Certificate data is too long.");
2817 return -1;
2818 }
2819
2820 biobuf = BIO_new_mem_buf(data, (int)len);
2821 if (biobuf == NULL) {
2822 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2823 return -1;
2824 }
2825
2826 store = SSL_CTX_get_cert_store(self->ctx);
2827 assert(store != NULL);
2828
2829 while (1) {
2830 X509 *cert = NULL;
2831 int r;
2832
2833 if (filetype == SSL_FILETYPE_ASN1) {
2834 cert = d2i_X509_bio(biobuf, NULL);
2835 } else {
2836 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002837 SSL_CTX_get_default_passwd_cb(self->ctx),
2838 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2839 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002840 }
2841 if (cert == NULL) {
2842 break;
2843 }
2844 r = X509_STORE_add_cert(store, cert);
2845 X509_free(cert);
2846 if (!r) {
2847 err = ERR_peek_last_error();
2848 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2849 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2850 /* cert already in hash table, not an error */
2851 ERR_clear_error();
2852 } else {
2853 break;
2854 }
2855 }
2856 loaded++;
2857 }
2858
2859 err = ERR_peek_last_error();
2860 if ((filetype == SSL_FILETYPE_ASN1) &&
2861 (loaded > 0) &&
2862 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2863 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2864 /* EOF ASN1 file, not an error */
2865 ERR_clear_error();
2866 retval = 0;
2867 } else if ((filetype == SSL_FILETYPE_PEM) &&
2868 (loaded > 0) &&
2869 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2870 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2871 /* EOF PEM file, not an error */
2872 ERR_clear_error();
2873 retval = 0;
2874 } else {
2875 _setSSLError(NULL, 0, __FILE__, __LINE__);
2876 retval = -1;
2877 }
2878
2879 BIO_free(biobuf);
2880 return retval;
2881}
2882
2883
2884static PyObject *
2885load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2886{
2887 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2888 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2889 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2890 const char *cafile_buf = NULL, *capath_buf = NULL;
2891 int r = 0, ok = 1;
2892
2893 errno = 0;
2894 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2895 "|OOO:load_verify_locations", kwlist,
2896 &cafile, &capath, &cadata))
2897 return NULL;
2898
2899 if (cafile == Py_None)
2900 cafile = NULL;
2901 if (capath == Py_None)
2902 capath = NULL;
2903 if (cadata == Py_None)
2904 cadata = NULL;
2905
2906 if (cafile == NULL && capath == NULL && cadata == NULL) {
2907 PyErr_SetString(PyExc_TypeError,
2908 "cafile, capath and cadata cannot be all omitted");
2909 goto error;
2910 }
2911
2912 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002913 if (PyString_Check(cafile)) {
2914 Py_INCREF(cafile);
2915 cafile_bytes = cafile;
2916 } else {
2917 PyObject *u = PyUnicode_FromObject(cafile);
2918 if (!u)
2919 goto error;
2920 cafile_bytes = PyUnicode_AsEncodedString(
2921 u, Py_FileSystemDefaultEncoding, NULL);
2922 Py_DECREF(u);
2923 if (!cafile_bytes)
2924 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002925 }
2926 }
2927 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002928 if (PyString_Check(capath)) {
2929 Py_INCREF(capath);
2930 capath_bytes = capath;
2931 } else {
2932 PyObject *u = PyUnicode_FromObject(capath);
2933 if (!u)
2934 goto error;
2935 capath_bytes = PyUnicode_AsEncodedString(
2936 u, Py_FileSystemDefaultEncoding, NULL);
2937 Py_DECREF(u);
2938 if (!capath_bytes)
2939 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002940 }
2941 }
2942
2943 /* validata cadata type and load cadata */
2944 if (cadata) {
2945 Py_buffer buf;
2946 PyObject *cadata_ascii = NULL;
2947
2948 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2949 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2950 PyBuffer_Release(&buf);
2951 PyErr_SetString(PyExc_TypeError,
2952 "cadata should be a contiguous buffer with "
2953 "a single dimension");
2954 goto error;
2955 }
2956 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2957 PyBuffer_Release(&buf);
2958 if (r == -1) {
2959 goto error;
2960 }
2961 } else {
2962 PyErr_Clear();
2963 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2964 if (cadata_ascii == NULL) {
2965 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002966 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002967 "bytes-like object");
2968 goto error;
2969 }
2970 r = _add_ca_certs(self,
2971 PyBytes_AS_STRING(cadata_ascii),
2972 PyBytes_GET_SIZE(cadata_ascii),
2973 SSL_FILETYPE_PEM);
2974 Py_DECREF(cadata_ascii);
2975 if (r == -1) {
2976 goto error;
2977 }
2978 }
2979 }
2980
2981 /* load cafile or capath */
2982 if (cafile_bytes || capath_bytes) {
2983 if (cafile)
2984 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2985 if (capath)
2986 capath_buf = PyBytes_AS_STRING(capath_bytes);
2987 PySSL_BEGIN_ALLOW_THREADS
2988 r = SSL_CTX_load_verify_locations(
2989 self->ctx,
2990 cafile_buf,
2991 capath_buf);
2992 PySSL_END_ALLOW_THREADS
2993 if (r != 1) {
2994 ok = 0;
2995 if (errno != 0) {
2996 ERR_clear_error();
2997 PyErr_SetFromErrno(PyExc_IOError);
2998 }
2999 else {
3000 _setSSLError(NULL, 0, __FILE__, __LINE__);
3001 }
3002 goto error;
3003 }
3004 }
3005 goto end;
3006
3007 error:
3008 ok = 0;
3009 end:
3010 Py_XDECREF(cafile_bytes);
3011 Py_XDECREF(capath_bytes);
3012 if (ok) {
3013 Py_RETURN_NONE;
3014 } else {
3015 return NULL;
3016 }
3017}
3018
3019static PyObject *
3020load_dh_params(PySSLContext *self, PyObject *filepath)
3021{
3022 BIO *bio;
3023 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003024 PyObject *filepath_bytes = NULL;
3025
3026 if (PyString_Check(filepath)) {
3027 Py_INCREF(filepath);
3028 filepath_bytes = filepath;
3029 } else {
3030 PyObject *u = PyUnicode_FromObject(filepath);
3031 if (!u)
3032 return NULL;
3033 filepath_bytes = PyUnicode_AsEncodedString(
3034 u, Py_FileSystemDefaultEncoding, NULL);
3035 Py_DECREF(u);
3036 if (!filepath_bytes)
3037 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003038 }
3039
Christian Heimes6e8f3952018-02-25 09:48:02 +01003040 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003041 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003042 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003043 ERR_clear_error();
3044 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3045 return NULL;
3046 }
3047 errno = 0;
3048 PySSL_BEGIN_ALLOW_THREADS
3049 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3050 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003051 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003052 PySSL_END_ALLOW_THREADS
3053 if (dh == NULL) {
3054 if (errno != 0) {
3055 ERR_clear_error();
3056 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3057 }
3058 else {
3059 _setSSLError(NULL, 0, __FILE__, __LINE__);
3060 }
3061 return NULL;
3062 }
3063 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3064 _setSSLError(NULL, 0, __FILE__, __LINE__);
3065 DH_free(dh);
3066 Py_RETURN_NONE;
3067}
3068
3069static PyObject *
3070context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3071{
3072 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3073 PySocketSockObject *sock;
3074 int server_side = 0;
3075 char *hostname = NULL;
3076 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3077
3078 /* server_hostname is either None (or absent), or to be encoded
3079 using the idna encoding. */
3080 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3081 PySocketModule.Sock_Type,
3082 &sock, &server_side,
3083 Py_TYPE(Py_None), &hostname_obj,
3084 &ssl_sock)) {
3085 PyErr_Clear();
3086 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3087 PySocketModule.Sock_Type,
3088 &sock, &server_side,
3089 "idna", &hostname, &ssl_sock))
3090 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003091 }
3092
3093 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3094 hostname, ssl_sock);
3095 if (hostname != NULL)
3096 PyMem_Free(hostname);
3097 return res;
3098}
3099
3100static PyObject *
3101session_stats(PySSLContext *self, PyObject *unused)
3102{
3103 int r;
3104 PyObject *value, *stats = PyDict_New();
3105 if (!stats)
3106 return NULL;
3107
3108#define ADD_STATS(SSL_NAME, KEY_NAME) \
3109 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3110 if (value == NULL) \
3111 goto error; \
3112 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3113 Py_DECREF(value); \
3114 if (r < 0) \
3115 goto error;
3116
3117 ADD_STATS(number, "number");
3118 ADD_STATS(connect, "connect");
3119 ADD_STATS(connect_good, "connect_good");
3120 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3121 ADD_STATS(accept, "accept");
3122 ADD_STATS(accept_good, "accept_good");
3123 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3124 ADD_STATS(accept, "accept");
3125 ADD_STATS(hits, "hits");
3126 ADD_STATS(misses, "misses");
3127 ADD_STATS(timeouts, "timeouts");
3128 ADD_STATS(cache_full, "cache_full");
3129
3130#undef ADD_STATS
3131
3132 return stats;
3133
3134error:
3135 Py_DECREF(stats);
3136 return NULL;
3137}
3138
3139static PyObject *
3140set_default_verify_paths(PySSLContext *self, PyObject *unused)
3141{
3142 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3143 _setSSLError(NULL, 0, __FILE__, __LINE__);
3144 return NULL;
3145 }
3146 Py_RETURN_NONE;
3147}
3148
3149#ifndef OPENSSL_NO_ECDH
3150static PyObject *
3151set_ecdh_curve(PySSLContext *self, PyObject *name)
3152{
3153 char *name_bytes;
3154 int nid;
3155 EC_KEY *key;
3156
3157 name_bytes = PyBytes_AsString(name);
3158 if (!name_bytes) {
3159 return NULL;
3160 }
3161 nid = OBJ_sn2nid(name_bytes);
3162 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003163 PyObject *r = PyObject_Repr(name);
3164 if (!r)
3165 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003166 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003167 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3168 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003169 return NULL;
3170 }
3171 key = EC_KEY_new_by_curve_name(nid);
3172 if (key == NULL) {
3173 _setSSLError(NULL, 0, __FILE__, __LINE__);
3174 return NULL;
3175 }
3176 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3177 EC_KEY_free(key);
3178 Py_RETURN_NONE;
3179}
3180#endif
3181
3182#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3183static int
3184_servername_callback(SSL *s, int *al, void *args)
3185{
3186 int ret;
3187 PySSLContext *ssl_ctx = (PySSLContext *) args;
3188 PySSLSocket *ssl;
3189 PyObject *servername_o;
3190 PyObject *servername_idna;
3191 PyObject *result;
3192 /* The high-level ssl.SSLSocket object */
3193 PyObject *ssl_socket;
3194 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3195#ifdef WITH_THREAD
3196 PyGILState_STATE gstate = PyGILState_Ensure();
3197#endif
3198
3199 if (ssl_ctx->set_hostname == NULL) {
3200 /* remove race condition in this the call back while if removing the
3201 * callback is in progress */
3202#ifdef WITH_THREAD
3203 PyGILState_Release(gstate);
3204#endif
3205 return SSL_TLSEXT_ERR_OK;
3206 }
3207
3208 ssl = SSL_get_app_data(s);
3209 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003210 if (ssl->ssl_sock == NULL) {
3211 ssl_socket = Py_None;
3212 } else {
3213 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3214 Py_INCREF(ssl_socket);
3215 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003216 if (ssl_socket == Py_None) {
3217 goto error;
3218 }
3219
3220 if (servername == NULL) {
3221 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3222 Py_None, ssl_ctx, NULL);
3223 }
3224 else {
3225 servername_o = PyBytes_FromString(servername);
3226 if (servername_o == NULL) {
3227 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3228 goto error;
3229 }
3230 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3231 if (servername_idna == NULL) {
3232 PyErr_WriteUnraisable(servername_o);
3233 Py_DECREF(servername_o);
3234 goto error;
3235 }
3236 Py_DECREF(servername_o);
3237 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3238 servername_idna, ssl_ctx, NULL);
3239 Py_DECREF(servername_idna);
3240 }
3241 Py_DECREF(ssl_socket);
3242
3243 if (result == NULL) {
3244 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3245 *al = SSL_AD_HANDSHAKE_FAILURE;
3246 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3247 }
3248 else {
3249 if (result != Py_None) {
3250 *al = (int) PyLong_AsLong(result);
3251 if (PyErr_Occurred()) {
3252 PyErr_WriteUnraisable(result);
3253 *al = SSL_AD_INTERNAL_ERROR;
3254 }
3255 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3256 }
3257 else {
3258 ret = SSL_TLSEXT_ERR_OK;
3259 }
3260 Py_DECREF(result);
3261 }
3262
3263#ifdef WITH_THREAD
3264 PyGILState_Release(gstate);
3265#endif
3266 return ret;
3267
3268error:
3269 Py_DECREF(ssl_socket);
3270 *al = SSL_AD_INTERNAL_ERROR;
3271 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3272#ifdef WITH_THREAD
3273 PyGILState_Release(gstate);
3274#endif
3275 return ret;
3276}
3277#endif
3278
3279PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3280"set_servername_callback(method)\n\
3281\n\
3282This sets a callback that will be called when a server name is provided by\n\
3283the SSL/TLS client in the SNI extension.\n\
3284\n\
3285If the argument is None then the callback is disabled. The method is called\n\
3286with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3287See RFC 6066 for details of the SNI extension.");
3288
3289static PyObject *
3290set_servername_callback(PySSLContext *self, PyObject *args)
3291{
3292#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3293 PyObject *cb;
3294
3295 if (!PyArg_ParseTuple(args, "O", &cb))
3296 return NULL;
3297
3298 Py_CLEAR(self->set_hostname);
3299 if (cb == Py_None) {
3300 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3301 }
3302 else {
3303 if (!PyCallable_Check(cb)) {
3304 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3305 PyErr_SetString(PyExc_TypeError,
3306 "not a callable object");
3307 return NULL;
3308 }
3309 Py_INCREF(cb);
3310 self->set_hostname = cb;
3311 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3312 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3313 }
3314 Py_RETURN_NONE;
3315#else
3316 PyErr_SetString(PyExc_NotImplementedError,
3317 "The TLS extension servername callback, "
3318 "SSL_CTX_set_tlsext_servername_callback, "
3319 "is not in the current OpenSSL library.");
3320 return NULL;
3321#endif
3322}
3323
3324PyDoc_STRVAR(PySSL_get_stats_doc,
3325"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3326\n\
3327Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3328CA extension and certificate revocation lists inside the context's cert\n\
3329store.\n\
3330NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3331been used at least once.");
3332
3333static PyObject *
3334cert_store_stats(PySSLContext *self)
3335{
3336 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003337 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003338 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003339 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003340
3341 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003342 objs = X509_STORE_get0_objects(store);
3343 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3344 obj = sk_X509_OBJECT_value(objs, i);
3345 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003346 case X509_LU_X509:
3347 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003348 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003349 ca++;
3350 }
3351 break;
3352 case X509_LU_CRL:
3353 crl++;
3354 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003355 default:
3356 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3357 * As far as I can tell they are internal states and never
3358 * stored in a cert store */
3359 break;
3360 }
3361 }
3362 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3363 "x509_ca", ca);
3364}
3365
3366PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3367"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3368\n\
3369Returns a list of dicts with information of loaded CA certs. If the\n\
3370optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3371NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3372been used at least once.");
3373
3374static PyObject *
3375get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3376{
3377 char *kwlist[] = {"binary_form", NULL};
3378 X509_STORE *store;
3379 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003380 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003381 int i;
3382 int binary_mode = 0;
3383
3384 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3385 kwlist, &py_binary_mode)) {
3386 return NULL;
3387 }
3388 binary_mode = PyObject_IsTrue(py_binary_mode);
3389 if (binary_mode < 0) {
3390 return NULL;
3391 }
3392
3393 if ((rlist = PyList_New(0)) == NULL) {
3394 return NULL;
3395 }
3396
3397 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003398 objs = X509_STORE_get0_objects(store);
3399 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003400 X509_OBJECT *obj;
3401 X509 *cert;
3402
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003403 obj = sk_X509_OBJECT_value(objs, i);
3404 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003405 /* not a x509 cert */
3406 continue;
3407 }
3408 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003409 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003410 if (!X509_check_ca(cert)) {
3411 continue;
3412 }
3413 if (binary_mode) {
3414 ci = _certificate_to_der(cert);
3415 } else {
3416 ci = _decode_certificate(cert);
3417 }
3418 if (ci == NULL) {
3419 goto error;
3420 }
3421 if (PyList_Append(rlist, ci) == -1) {
3422 goto error;
3423 }
3424 Py_CLEAR(ci);
3425 }
3426 return rlist;
3427
3428 error:
3429 Py_XDECREF(ci);
3430 Py_XDECREF(rlist);
3431 return NULL;
3432}
3433
3434
3435static PyGetSetDef context_getsetlist[] = {
3436 {"check_hostname", (getter) get_check_hostname,
3437 (setter) set_check_hostname, NULL},
3438 {"options", (getter) get_options,
3439 (setter) set_options, NULL},
3440#ifdef HAVE_OPENSSL_VERIFY_PARAM
3441 {"verify_flags", (getter) get_verify_flags,
3442 (setter) set_verify_flags, NULL},
3443#endif
3444 {"verify_mode", (getter) get_verify_mode,
3445 (setter) set_verify_mode, NULL},
3446 {NULL}, /* sentinel */
3447};
3448
3449static struct PyMethodDef context_methods[] = {
3450 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3451 METH_VARARGS | METH_KEYWORDS, NULL},
3452 {"set_ciphers", (PyCFunction) set_ciphers,
3453 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003454 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3455 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003456 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3457 METH_VARARGS, NULL},
3458 {"load_cert_chain", (PyCFunction) load_cert_chain,
3459 METH_VARARGS | METH_KEYWORDS, NULL},
3460 {"load_dh_params", (PyCFunction) load_dh_params,
3461 METH_O, NULL},
3462 {"load_verify_locations", (PyCFunction) load_verify_locations,
3463 METH_VARARGS | METH_KEYWORDS, NULL},
3464 {"session_stats", (PyCFunction) session_stats,
3465 METH_NOARGS, NULL},
3466 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3467 METH_NOARGS, NULL},
3468#ifndef OPENSSL_NO_ECDH
3469 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3470 METH_O, NULL},
3471#endif
3472 {"set_servername_callback", (PyCFunction) set_servername_callback,
3473 METH_VARARGS, PySSL_set_servername_callback_doc},
3474 {"cert_store_stats", (PyCFunction) cert_store_stats,
3475 METH_NOARGS, PySSL_get_stats_doc},
3476 {"get_ca_certs", (PyCFunction) get_ca_certs,
3477 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3478 {NULL, NULL} /* sentinel */
3479};
3480
3481static PyTypeObject PySSLContext_Type = {
3482 PyVarObject_HEAD_INIT(NULL, 0)
3483 "_ssl._SSLContext", /*tp_name*/
3484 sizeof(PySSLContext), /*tp_basicsize*/
3485 0, /*tp_itemsize*/
3486 (destructor)context_dealloc, /*tp_dealloc*/
3487 0, /*tp_print*/
3488 0, /*tp_getattr*/
3489 0, /*tp_setattr*/
3490 0, /*tp_reserved*/
3491 0, /*tp_repr*/
3492 0, /*tp_as_number*/
3493 0, /*tp_as_sequence*/
3494 0, /*tp_as_mapping*/
3495 0, /*tp_hash*/
3496 0, /*tp_call*/
3497 0, /*tp_str*/
3498 0, /*tp_getattro*/
3499 0, /*tp_setattro*/
3500 0, /*tp_as_buffer*/
3501 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3502 0, /*tp_doc*/
3503 (traverseproc) context_traverse, /*tp_traverse*/
3504 (inquiry) context_clear, /*tp_clear*/
3505 0, /*tp_richcompare*/
3506 0, /*tp_weaklistoffset*/
3507 0, /*tp_iter*/
3508 0, /*tp_iternext*/
3509 context_methods, /*tp_methods*/
3510 0, /*tp_members*/
3511 context_getsetlist, /*tp_getset*/
3512 0, /*tp_base*/
3513 0, /*tp_dict*/
3514 0, /*tp_descr_get*/
3515 0, /*tp_descr_set*/
3516 0, /*tp_dictoffset*/
3517 0, /*tp_init*/
3518 0, /*tp_alloc*/
3519 context_new, /*tp_new*/
3520};
3521
3522
3523
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003524#ifdef HAVE_OPENSSL_RAND
3525
3526/* helper routines for seeding the SSL PRNG */
3527static PyObject *
3528PySSL_RAND_add(PyObject *self, PyObject *args)
3529{
3530 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003531 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003532 double entropy;
3533
3534 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003535 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003536 do {
3537 if (len >= INT_MAX) {
3538 written = INT_MAX;
3539 } else {
3540 written = len;
3541 }
3542 RAND_add(buf, (int)written, entropy);
3543 buf += written;
3544 len -= written;
3545 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003546 Py_INCREF(Py_None);
3547 return Py_None;
3548}
3549
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003550PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003551"RAND_add(string, entropy)\n\
3552\n\
3553Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003554bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003555
3556static PyObject *
3557PySSL_RAND_status(PyObject *self)
3558{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003559 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003560}
3561
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003562PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003563"RAND_status() -> 0 or 1\n\
3564\n\
3565Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3566It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003567using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003568
Victor Stinner7c906672015-01-06 13:53:37 +01003569#endif /* HAVE_OPENSSL_RAND */
3570
3571
Benjamin Peterson42e10292016-07-07 00:02:31 -07003572#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003573
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003574static PyObject *
3575PySSL_RAND_egd(PyObject *self, PyObject *arg)
3576{
3577 int bytes;
3578
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003579 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003580 return PyErr_Format(PyExc_TypeError,
3581 "RAND_egd() expected string, found %s",
3582 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003583 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003584 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003585 PyErr_SetString(PySSLErrorObject,
3586 "EGD connection failed or EGD did not return "
3587 "enough data to seed the PRNG");
3588 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003589 }
3590 return PyInt_FromLong(bytes);
3591}
3592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003593PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003594"RAND_egd(path) -> bytes\n\
3595\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003596Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3597Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003598fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003599
Benjamin Peterson42e10292016-07-07 00:02:31 -07003600#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003601
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003602
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003603PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3604"get_default_verify_paths() -> tuple\n\
3605\n\
3606Return search paths and environment vars that are used by SSLContext's\n\
3607set_default_verify_paths() to load default CAs. The values are\n\
3608'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3609
3610static PyObject *
3611PySSL_get_default_verify_paths(PyObject *self)
3612{
3613 PyObject *ofile_env = NULL;
3614 PyObject *ofile = NULL;
3615 PyObject *odir_env = NULL;
3616 PyObject *odir = NULL;
3617
Benjamin Peterson65192c12015-07-18 10:59:13 -07003618#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003619 const char *tmp = (info); \
3620 target = NULL; \
3621 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3622 else { target = PyBytes_FromString(tmp); } \
3623 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003624 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003625
Benjamin Peterson65192c12015-07-18 10:59:13 -07003626 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3627 CONVERT(X509_get_default_cert_file(), ofile);
3628 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3629 CONVERT(X509_get_default_cert_dir(), odir);
3630#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003631
3632 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3633
3634 error:
3635 Py_XDECREF(ofile_env);
3636 Py_XDECREF(ofile);
3637 Py_XDECREF(odir_env);
3638 Py_XDECREF(odir);
3639 return NULL;
3640}
3641
3642static PyObject*
3643asn1obj2py(ASN1_OBJECT *obj)
3644{
3645 int nid;
3646 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003647
3648 nid = OBJ_obj2nid(obj);
3649 if (nid == NID_undef) {
3650 PyErr_Format(PyExc_ValueError, "Unknown object");
3651 return NULL;
3652 }
3653 sn = OBJ_nid2sn(nid);
3654 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003655 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003656}
3657
3658PyDoc_STRVAR(PySSL_txt2obj_doc,
3659"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3660\n\
3661Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3662objects are looked up by OID. With name=True short and long name are also\n\
3663matched.");
3664
3665static PyObject*
3666PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3667{
3668 char *kwlist[] = {"txt", "name", NULL};
3669 PyObject *result = NULL;
3670 char *txt;
3671 PyObject *pyname = Py_None;
3672 int name = 0;
3673 ASN1_OBJECT *obj;
3674
3675 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3676 kwlist, &txt, &pyname)) {
3677 return NULL;
3678 }
3679 name = PyObject_IsTrue(pyname);
3680 if (name < 0)
3681 return NULL;
3682 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3683 if (obj == NULL) {
3684 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3685 return NULL;
3686 }
3687 result = asn1obj2py(obj);
3688 ASN1_OBJECT_free(obj);
3689 return result;
3690}
3691
3692PyDoc_STRVAR(PySSL_nid2obj_doc,
3693"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3694\n\
3695Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3696
3697static PyObject*
3698PySSL_nid2obj(PyObject *self, PyObject *args)
3699{
3700 PyObject *result = NULL;
3701 int nid;
3702 ASN1_OBJECT *obj;
3703
3704 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3705 return NULL;
3706 }
3707 if (nid < NID_undef) {
3708 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3709 return NULL;
3710 }
3711 obj = OBJ_nid2obj(nid);
3712 if (obj == NULL) {
3713 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3714 return NULL;
3715 }
3716 result = asn1obj2py(obj);
3717 ASN1_OBJECT_free(obj);
3718 return result;
3719}
3720
3721#ifdef _MSC_VER
3722
3723static PyObject*
3724certEncodingType(DWORD encodingType)
3725{
3726 static PyObject *x509_asn = NULL;
3727 static PyObject *pkcs_7_asn = NULL;
3728
3729 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003730 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003731 if (x509_asn == NULL)
3732 return NULL;
3733 }
3734 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003735 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003736 if (pkcs_7_asn == NULL)
3737 return NULL;
3738 }
3739 switch(encodingType) {
3740 case X509_ASN_ENCODING:
3741 Py_INCREF(x509_asn);
3742 return x509_asn;
3743 case PKCS_7_ASN_ENCODING:
3744 Py_INCREF(pkcs_7_asn);
3745 return pkcs_7_asn;
3746 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003747 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003748 }
3749}
3750
3751static PyObject*
3752parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3753{
3754 CERT_ENHKEY_USAGE *usage;
3755 DWORD size, error, i;
3756 PyObject *retval;
3757
3758 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3759 error = GetLastError();
3760 if (error == CRYPT_E_NOT_FOUND) {
3761 Py_RETURN_TRUE;
3762 }
3763 return PyErr_SetFromWindowsErr(error);
3764 }
3765
3766 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3767 if (usage == NULL) {
3768 return PyErr_NoMemory();
3769 }
3770
3771 /* Now get the actual enhanced usage property */
3772 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3773 PyMem_Free(usage);
3774 error = GetLastError();
3775 if (error == CRYPT_E_NOT_FOUND) {
3776 Py_RETURN_TRUE;
3777 }
3778 return PyErr_SetFromWindowsErr(error);
3779 }
3780 retval = PySet_New(NULL);
3781 if (retval == NULL) {
3782 goto error;
3783 }
3784 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3785 if (usage->rgpszUsageIdentifier[i]) {
3786 PyObject *oid;
3787 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003788 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003789 if (oid == NULL) {
3790 Py_CLEAR(retval);
3791 goto error;
3792 }
3793 err = PySet_Add(retval, oid);
3794 Py_DECREF(oid);
3795 if (err == -1) {
3796 Py_CLEAR(retval);
3797 goto error;
3798 }
3799 }
3800 }
3801 error:
3802 PyMem_Free(usage);
3803 return retval;
3804}
3805
3806PyDoc_STRVAR(PySSL_enum_certificates_doc,
3807"enum_certificates(store_name) -> []\n\
3808\n\
3809Retrieve certificates from Windows' cert store. store_name may be one of\n\
3810'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3811The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3812encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3813PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3814boolean True.");
3815
3816static PyObject *
3817PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3818{
3819 char *kwlist[] = {"store_name", NULL};
3820 char *store_name;
3821 HCERTSTORE hStore = NULL;
3822 PCCERT_CONTEXT pCertCtx = NULL;
3823 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3824 PyObject *result = NULL;
3825
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003826 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003827 kwlist, &store_name)) {
3828 return NULL;
3829 }
3830 result = PyList_New(0);
3831 if (result == NULL) {
3832 return NULL;
3833 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003834 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3835 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3836 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003837 if (hStore == NULL) {
3838 Py_DECREF(result);
3839 return PyErr_SetFromWindowsErr(GetLastError());
3840 }
3841
3842 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3843 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3844 pCertCtx->cbCertEncoded);
3845 if (!cert) {
3846 Py_CLEAR(result);
3847 break;
3848 }
3849 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3850 Py_CLEAR(result);
3851 break;
3852 }
3853 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3854 if (keyusage == Py_True) {
3855 Py_DECREF(keyusage);
3856 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3857 }
3858 if (keyusage == NULL) {
3859 Py_CLEAR(result);
3860 break;
3861 }
3862 if ((tup = PyTuple_New(3)) == NULL) {
3863 Py_CLEAR(result);
3864 break;
3865 }
3866 PyTuple_SET_ITEM(tup, 0, cert);
3867 cert = NULL;
3868 PyTuple_SET_ITEM(tup, 1, enc);
3869 enc = NULL;
3870 PyTuple_SET_ITEM(tup, 2, keyusage);
3871 keyusage = NULL;
3872 if (PyList_Append(result, tup) < 0) {
3873 Py_CLEAR(result);
3874 break;
3875 }
3876 Py_CLEAR(tup);
3877 }
3878 if (pCertCtx) {
3879 /* loop ended with an error, need to clean up context manually */
3880 CertFreeCertificateContext(pCertCtx);
3881 }
3882
3883 /* In error cases cert, enc and tup may not be NULL */
3884 Py_XDECREF(cert);
3885 Py_XDECREF(enc);
3886 Py_XDECREF(keyusage);
3887 Py_XDECREF(tup);
3888
3889 if (!CertCloseStore(hStore, 0)) {
3890 /* This error case might shadow another exception.*/
3891 Py_XDECREF(result);
3892 return PyErr_SetFromWindowsErr(GetLastError());
3893 }
3894 return result;
3895}
3896
3897PyDoc_STRVAR(PySSL_enum_crls_doc,
3898"enum_crls(store_name) -> []\n\
3899\n\
3900Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3901'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3902The function returns a list of (bytes, encoding_type) tuples. The\n\
3903encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3904PKCS_7_ASN_ENCODING.");
3905
3906static PyObject *
3907PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3908{
3909 char *kwlist[] = {"store_name", NULL};
3910 char *store_name;
3911 HCERTSTORE hStore = NULL;
3912 PCCRL_CONTEXT pCrlCtx = NULL;
3913 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3914 PyObject *result = NULL;
3915
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003916 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003917 kwlist, &store_name)) {
3918 return NULL;
3919 }
3920 result = PyList_New(0);
3921 if (result == NULL) {
3922 return NULL;
3923 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003924 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3925 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3926 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003927 if (hStore == NULL) {
3928 Py_DECREF(result);
3929 return PyErr_SetFromWindowsErr(GetLastError());
3930 }
3931
3932 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3933 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3934 pCrlCtx->cbCrlEncoded);
3935 if (!crl) {
3936 Py_CLEAR(result);
3937 break;
3938 }
3939 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3940 Py_CLEAR(result);
3941 break;
3942 }
3943 if ((tup = PyTuple_New(2)) == NULL) {
3944 Py_CLEAR(result);
3945 break;
3946 }
3947 PyTuple_SET_ITEM(tup, 0, crl);
3948 crl = NULL;
3949 PyTuple_SET_ITEM(tup, 1, enc);
3950 enc = NULL;
3951
3952 if (PyList_Append(result, tup) < 0) {
3953 Py_CLEAR(result);
3954 break;
3955 }
3956 Py_CLEAR(tup);
3957 }
3958 if (pCrlCtx) {
3959 /* loop ended with an error, need to clean up context manually */
3960 CertFreeCRLContext(pCrlCtx);
3961 }
3962
3963 /* In error cases cert, enc and tup may not be NULL */
3964 Py_XDECREF(crl);
3965 Py_XDECREF(enc);
3966 Py_XDECREF(tup);
3967
3968 if (!CertCloseStore(hStore, 0)) {
3969 /* This error case might shadow another exception.*/
3970 Py_XDECREF(result);
3971 return PyErr_SetFromWindowsErr(GetLastError());
3972 }
3973 return result;
3974}
3975
3976#endif /* _MSC_VER */
3977
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003978/* List of functions exported by this module. */
3979
3980static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003981 {"_test_decode_cert", PySSL_test_decode_certificate,
3982 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003983#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003984 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3985 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003986 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3987 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003988#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003989#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003990 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3991 PySSL_RAND_egd_doc},
3992#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003993 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3994 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3995#ifdef _MSC_VER
3996 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3997 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3998 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3999 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4000#endif
4001 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4002 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4003 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4004 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004005 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004006};
4007
4008
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004009#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004010
4011/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004012 * of the Python C thread library
4013 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4014 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004015
4016static PyThread_type_lock *_ssl_locks = NULL;
4017
Christian Heimes10107812013-08-19 17:36:29 +02004018#if OPENSSL_VERSION_NUMBER >= 0x10000000
4019/* use new CRYPTO_THREADID API. */
4020static void
4021_ssl_threadid_callback(CRYPTO_THREADID *id)
4022{
4023 CRYPTO_THREADID_set_numeric(id,
4024 (unsigned long)PyThread_get_thread_ident());
4025}
4026#else
4027/* deprecated CRYPTO_set_id_callback() API. */
4028static unsigned long
4029_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004030 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004031}
Christian Heimes10107812013-08-19 17:36:29 +02004032#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004033
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004034static void _ssl_thread_locking_function
4035 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004036 /* this function is needed to perform locking on shared data
4037 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004038 structures that will be implicitly shared whenever multiple
4039 threads use OpenSSL.) Multi-threaded applications will
4040 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004041
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004042 locking_function() must be able to handle up to
4043 CRYPTO_num_locks() different mutex locks. It sets the n-th
4044 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004045
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004046 file and line are the file number of the function setting the
4047 lock. They can be useful for debugging.
4048 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004049
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004050 if ((_ssl_locks == NULL) ||
4051 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4052 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004053
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004054 if (mode & CRYPTO_LOCK) {
4055 PyThread_acquire_lock(_ssl_locks[n], 1);
4056 } else {
4057 PyThread_release_lock(_ssl_locks[n]);
4058 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004059}
4060
4061static int _setup_ssl_threads(void) {
4062
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004063 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004064
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004065 if (_ssl_locks == NULL) {
4066 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004067 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4068 if (_ssl_locks == NULL) {
4069 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004070 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004071 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004072 memset(_ssl_locks, 0,
4073 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004074 for (i = 0; i < _ssl_locks_count; i++) {
4075 _ssl_locks[i] = PyThread_allocate_lock();
4076 if (_ssl_locks[i] == NULL) {
4077 unsigned int j;
4078 for (j = 0; j < i; j++) {
4079 PyThread_free_lock(_ssl_locks[j]);
4080 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004081 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004082 return 0;
4083 }
4084 }
4085 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004086#if OPENSSL_VERSION_NUMBER >= 0x10000000
4087 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4088#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004089 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004090#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004091 }
4092 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004093}
4094
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004095#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004096
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004097PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004098"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004099for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004100
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004101
4102
4103
4104static void
4105parse_openssl_version(unsigned long libver,
4106 unsigned int *major, unsigned int *minor,
4107 unsigned int *fix, unsigned int *patch,
4108 unsigned int *status)
4109{
4110 *status = libver & 0xF;
4111 libver >>= 4;
4112 *patch = libver & 0xFF;
4113 libver >>= 8;
4114 *fix = libver & 0xFF;
4115 libver >>= 8;
4116 *minor = libver & 0xFF;
4117 libver >>= 8;
4118 *major = libver & 0xFF;
4119}
4120
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004121PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004122init_ssl(void)
4123{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004124 PyObject *m, *d, *r;
4125 unsigned long libver;
4126 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004127 struct py_ssl_error_code *errcode;
4128 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004129
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004130 if (PyType_Ready(&PySSLContext_Type) < 0)
4131 return;
4132 if (PyType_Ready(&PySSLSocket_Type) < 0)
4133 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004134
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004135 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4136 if (m == NULL)
4137 return;
4138 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004139
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004140 /* Load _socket module and its C API */
4141 if (PySocketModule_ImportModuleAndAPI())
4142 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004143
Christian Heimes7daa45d2017-09-05 17:12:12 +02004144#ifndef OPENSSL_VERSION_1_1
4145 /* Load all algorithms and initialize cpuid */
4146 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004147 /* Init OpenSSL */
4148 SSL_load_error_strings();
4149 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004150#endif
4151
Bill Janssen98d19da2007-09-10 21:51:02 +00004152#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004153#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004154 /* note that this will start threading if not already started */
4155 if (!_setup_ssl_threads()) {
4156 return;
4157 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004158#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4159 /* OpenSSL 1.1.0 builtin thread support is enabled */
4160 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004161#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004162#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004163
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004164 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004165 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4166 "ssl.SSLError", SSLError_doc,
4167 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004168 if (PySSLErrorObject == NULL)
4169 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004170 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4171
4172 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4173 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4174 PySSLErrorObject, NULL);
4175 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4176 "ssl.SSLWantReadError", SSLWantReadError_doc,
4177 PySSLErrorObject, NULL);
4178 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4179 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4180 PySSLErrorObject, NULL);
4181 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4182 "ssl.SSLSyscallError", SSLSyscallError_doc,
4183 PySSLErrorObject, NULL);
4184 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4185 "ssl.SSLEOFError", SSLEOFError_doc,
4186 PySSLErrorObject, NULL);
4187 if (PySSLZeroReturnErrorObject == NULL
4188 || PySSLWantReadErrorObject == NULL
4189 || PySSLWantWriteErrorObject == NULL
4190 || PySSLSyscallErrorObject == NULL
4191 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004192 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004193
4194 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4195 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4196 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4197 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4198 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4199
4200 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4201 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4202 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4203 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4204 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4205 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4206 return;
4207 if (PyDict_SetItemString(d, "_SSLContext",
4208 (PyObject *)&PySSLContext_Type) != 0)
4209 return;
4210 if (PyDict_SetItemString(d, "_SSLSocket",
4211 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004212 return;
4213 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4214 PY_SSL_ERROR_ZERO_RETURN);
4215 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4216 PY_SSL_ERROR_WANT_READ);
4217 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4218 PY_SSL_ERROR_WANT_WRITE);
4219 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4220 PY_SSL_ERROR_WANT_X509_LOOKUP);
4221 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4222 PY_SSL_ERROR_SYSCALL);
4223 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4224 PY_SSL_ERROR_SSL);
4225 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4226 PY_SSL_ERROR_WANT_CONNECT);
4227 /* non ssl.h errorcodes */
4228 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4229 PY_SSL_ERROR_EOF);
4230 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4231 PY_SSL_ERROR_INVALID_ERROR_CODE);
4232 /* cert requirements */
4233 PyModule_AddIntConstant(m, "CERT_NONE",
4234 PY_SSL_CERT_NONE);
4235 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4236 PY_SSL_CERT_OPTIONAL);
4237 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4238 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004239 /* CRL verification for verification_flags */
4240 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4241 0);
4242 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4243 X509_V_FLAG_CRL_CHECK);
4244 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4245 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4246 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4247 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004248#ifdef X509_V_FLAG_TRUSTED_FIRST
4249 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4250 X509_V_FLAG_TRUSTED_FIRST);
4251#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004252
4253 /* Alert Descriptions from ssl.h */
4254 /* note RESERVED constants no longer intended for use have been removed */
4255 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4256
4257#define ADD_AD_CONSTANT(s) \
4258 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4259 SSL_AD_##s)
4260
4261 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4262 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4263 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4264 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4265 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4266 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4267 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4268 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4269 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4270 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4271 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4272 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4273 ADD_AD_CONSTANT(UNKNOWN_CA);
4274 ADD_AD_CONSTANT(ACCESS_DENIED);
4275 ADD_AD_CONSTANT(DECODE_ERROR);
4276 ADD_AD_CONSTANT(DECRYPT_ERROR);
4277 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4278 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4279 ADD_AD_CONSTANT(INTERNAL_ERROR);
4280 ADD_AD_CONSTANT(USER_CANCELLED);
4281 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4282 /* Not all constants are in old OpenSSL versions */
4283#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4284 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4285#endif
4286#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4287 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4288#endif
4289#ifdef SSL_AD_UNRECOGNIZED_NAME
4290 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4291#endif
4292#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4293 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4294#endif
4295#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4296 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4297#endif
4298#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4299 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4300#endif
4301
4302#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004303
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004304 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004305#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004306 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4307 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004308#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004309#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004310 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4311 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004312#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004313 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004314 PY_SSL_VERSION_TLS);
4315 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4316 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004317 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4318 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004319#if HAVE_TLSv1_2
4320 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4321 PY_SSL_VERSION_TLS1_1);
4322 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4323 PY_SSL_VERSION_TLS1_2);
4324#endif
4325
4326 /* protocol options */
4327 PyModule_AddIntConstant(m, "OP_ALL",
4328 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4329 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4330 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4331 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4332#if HAVE_TLSv1_2
4333 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4334 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4335#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004336#ifdef SSL_OP_NO_TLSv1_3
4337 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4338#else
4339 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4340#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004341 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4342 SSL_OP_CIPHER_SERVER_PREFERENCE);
4343 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4344#ifdef SSL_OP_SINGLE_ECDH_USE
4345 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4346#endif
4347#ifdef SSL_OP_NO_COMPRESSION
4348 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4349 SSL_OP_NO_COMPRESSION);
4350#endif
4351
4352#if HAVE_SNI
4353 r = Py_True;
4354#else
4355 r = Py_False;
4356#endif
4357 Py_INCREF(r);
4358 PyModule_AddObject(m, "HAS_SNI", r);
4359
4360#if HAVE_OPENSSL_FINISHED
4361 r = Py_True;
4362#else
4363 r = Py_False;
4364#endif
4365 Py_INCREF(r);
4366 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4367
4368#ifdef OPENSSL_NO_ECDH
4369 r = Py_False;
4370#else
4371 r = Py_True;
4372#endif
4373 Py_INCREF(r);
4374 PyModule_AddObject(m, "HAS_ECDH", r);
4375
Christian Heimes72ed2332017-09-05 01:11:40 +02004376#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004377 r = Py_True;
4378#else
4379 r = Py_False;
4380#endif
4381 Py_INCREF(r);
4382 PyModule_AddObject(m, "HAS_NPN", r);
4383
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004384#ifdef HAVE_ALPN
4385 r = Py_True;
4386#else
4387 r = Py_False;
4388#endif
4389 Py_INCREF(r);
4390 PyModule_AddObject(m, "HAS_ALPN", r);
4391
Christian Heimesb9a860f2017-09-07 22:31:17 -07004392#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4393 r = Py_True;
4394#else
4395 r = Py_False;
4396#endif
4397 Py_INCREF(r);
4398 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4399
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004400 /* Mappings for error codes */
4401 err_codes_to_names = PyDict_New();
4402 err_names_to_codes = PyDict_New();
4403 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4404 return;
4405 errcode = error_codes;
4406 while (errcode->mnemonic != NULL) {
4407 PyObject *mnemo, *key;
4408 mnemo = PyUnicode_FromString(errcode->mnemonic);
4409 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4410 if (mnemo == NULL || key == NULL)
4411 return;
4412 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4413 return;
4414 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4415 return;
4416 Py_DECREF(key);
4417 Py_DECREF(mnemo);
4418 errcode++;
4419 }
4420 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4421 return;
4422 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4423 return;
4424
4425 lib_codes_to_names = PyDict_New();
4426 if (lib_codes_to_names == NULL)
4427 return;
4428 libcode = library_codes;
4429 while (libcode->library != NULL) {
4430 PyObject *mnemo, *key;
4431 key = PyLong_FromLong(libcode->code);
4432 mnemo = PyUnicode_FromString(libcode->library);
4433 if (key == NULL || mnemo == NULL)
4434 return;
4435 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4436 return;
4437 Py_DECREF(key);
4438 Py_DECREF(mnemo);
4439 libcode++;
4440 }
4441 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4442 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004443
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004444 /* OpenSSL version */
4445 /* SSLeay() gives us the version of the library linked against,
4446 which could be different from the headers version.
4447 */
4448 libver = SSLeay();
4449 r = PyLong_FromUnsignedLong(libver);
4450 if (r == NULL)
4451 return;
4452 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4453 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004454 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004455 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4456 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4457 return;
4458 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4459 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4460 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004461
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004462 libver = OPENSSL_VERSION_NUMBER;
4463 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4464 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4465 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4466 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004467}