blob: da8b20f54f3532fe6929de4321e474e682fc339b [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 */
Christian Heimesdf1732a2018-02-25 14:28:55 +0100126#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
127# define HAVE_ALPN 1
128#else
129# define HAVE_ALPN 0
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500130#endif
131
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100132/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
133 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
134 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
135 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimesdf1732a2018-02-25 14:28:55 +0100136 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100137 */
138#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimesdf1732a2018-02-25 14:28:55 +0100139# define HAVE_NPN 0
140#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
141# define HAVE_NPN 0
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100142#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimesdf1732a2018-02-25 14:28:55 +0100143# define HAVE_NPN 1
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100144#else
Christian Heimesdf1732a2018-02-25 14:28:55 +0100145# define HAVE_NPN 0
146#endif
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100147
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200148#ifndef INVALID_SOCKET /* MS defines this */
149#define INVALID_SOCKET (-1)
150#endif
151
152#ifdef OPENSSL_VERSION_1_1
153/* OpenSSL 1.1.0+ */
154#ifndef OPENSSL_NO_SSL2
155#define OPENSSL_NO_SSL2
156#endif
157#else /* OpenSSL < 1.1.0 */
158#if defined(WITH_THREAD)
159#define HAVE_OPENSSL_CRYPTO_LOCK
160#endif
161
162#define TLS_method SSLv23_method
163
164static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
165{
166 return ne->set;
167}
168
169#ifndef OPENSSL_NO_COMP
170static int COMP_get_type(const COMP_METHOD *meth)
171{
172 return meth->type;
173}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200174#endif
175
176static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
177{
178 return ctx->default_passwd_callback;
179}
180
181static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
182{
183 return ctx->default_passwd_callback_userdata;
184}
185
186static int X509_OBJECT_get_type(X509_OBJECT *x)
187{
188 return x->type;
189}
190
191static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
192{
193 return x->data.x509;
194}
195
196static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
197 return store->objs;
198}
199
200static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
201{
202 return store->param;
203}
204#endif /* OpenSSL < 1.1.0 or LibreSSL */
205
206
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500207enum py_ssl_error {
208 /* these mirror ssl.h */
209 PY_SSL_ERROR_NONE,
210 PY_SSL_ERROR_SSL,
211 PY_SSL_ERROR_WANT_READ,
212 PY_SSL_ERROR_WANT_WRITE,
213 PY_SSL_ERROR_WANT_X509_LOOKUP,
214 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
215 PY_SSL_ERROR_ZERO_RETURN,
216 PY_SSL_ERROR_WANT_CONNECT,
217 /* start of non ssl.h errorcodes */
218 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
219 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
220 PY_SSL_ERROR_INVALID_ERROR_CODE
221};
222
223enum py_ssl_server_or_client {
224 PY_SSL_CLIENT,
225 PY_SSL_SERVER
226};
227
228enum py_ssl_cert_requirements {
229 PY_SSL_CERT_NONE,
230 PY_SSL_CERT_OPTIONAL,
231 PY_SSL_CERT_REQUIRED
232};
233
234enum py_ssl_version {
235 PY_SSL_VERSION_SSL2,
236 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200237 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500238#if HAVE_TLSv1_2
239 PY_SSL_VERSION_TLS1,
240 PY_SSL_VERSION_TLS1_1,
241 PY_SSL_VERSION_TLS1_2
242#else
243 PY_SSL_VERSION_TLS1
244#endif
245};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000246
Bill Janssen98d19da2007-09-10 21:51:02 +0000247#ifdef WITH_THREAD
248
249/* serves as a flag to see whether we've initialized the SSL thread support. */
250/* 0 means no, greater than 0 means yes */
251
252static unsigned int _ssl_locks_count = 0;
253
254#endif /* def WITH_THREAD */
255
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000256/* SSL socket object */
257
258#define X509_NAME_MAXLEN 256
259
260/* RAND_* APIs got added to OpenSSL in 0.9.5 */
261#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
262# define HAVE_OPENSSL_RAND 1
263#else
264# undef HAVE_OPENSSL_RAND
265#endif
266
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500267/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
268 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
269 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
270#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
271# define HAVE_SSL_CTX_CLEAR_OPTIONS
272#else
273# undef HAVE_SSL_CTX_CLEAR_OPTIONS
274#endif
275
276/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
277 * older SSL, but let's be safe */
278#define PySSL_CB_MAXLEN 128
279
280/* SSL_get_finished got added to OpenSSL in 0.9.5 */
281#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
282# define HAVE_OPENSSL_FINISHED 1
283#else
284# define HAVE_OPENSSL_FINISHED 0
285#endif
286
287/* ECDH support got added to OpenSSL in 0.9.8 */
288#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
289# define OPENSSL_NO_ECDH
290#endif
291
292/* compression support got added to OpenSSL in 0.9.8 */
293#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
294# define OPENSSL_NO_COMP
295#endif
296
297/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
298#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
299# define HAVE_OPENSSL_VERIFY_PARAM
300#endif
301
302
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000303typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000304 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500305 SSL_CTX *ctx;
Christian Heimesdf1732a2018-02-25 14:28:55 +0100306#if HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500307 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500308 int npn_protocols_len;
309#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +0100310#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500311 unsigned char *alpn_protocols;
312 int alpn_protocols_len;
313#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500314#ifndef OPENSSL_NO_TLSEXT
315 PyObject *set_hostname;
316#endif
317 int check_hostname;
318} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000319
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500320typedef struct {
321 PyObject_HEAD
322 PySocketSockObject *Socket;
323 PyObject *ssl_sock;
324 SSL *ssl;
325 PySSLContext *ctx; /* weakref to SSL context */
326 X509 *peer_cert;
327 char shutdown_seen_zero;
328 char handshake_done;
329 enum py_ssl_server_or_client socket_type;
330} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000331
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500332static PyTypeObject PySSLContext_Type;
333static PyTypeObject PySSLSocket_Type;
334
335static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
336static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000337static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000338 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500339static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
340static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000341
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500342#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
343#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000344
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000345typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000346 SOCKET_IS_NONBLOCKING,
347 SOCKET_IS_BLOCKING,
348 SOCKET_HAS_TIMED_OUT,
349 SOCKET_HAS_BEEN_CLOSED,
350 SOCKET_TOO_LARGE_FOR_SELECT,
351 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000352} timeout_state;
353
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000354/* Wrap error strings with filename and line # */
355#define STRINGIFY1(x) #x
356#define STRINGIFY2(x) STRINGIFY1(x)
357#define ERRSTR1(x,y,z) (x ":" y ": " z)
358#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
359
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500360
361/*
362 * SSL errors.
363 */
364
365PyDoc_STRVAR(SSLError_doc,
366"An error occurred in the SSL implementation.");
367
368PyDoc_STRVAR(SSLZeroReturnError_doc,
369"SSL/TLS session closed cleanly.");
370
371PyDoc_STRVAR(SSLWantReadError_doc,
372"Non-blocking SSL socket needs to read more data\n"
373"before the requested operation can be completed.");
374
375PyDoc_STRVAR(SSLWantWriteError_doc,
376"Non-blocking SSL socket needs to write more data\n"
377"before the requested operation can be completed.");
378
379PyDoc_STRVAR(SSLSyscallError_doc,
380"System error when attempting SSL operation.");
381
382PyDoc_STRVAR(SSLEOFError_doc,
383"SSL/TLS connection terminated abruptly.");
384
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000385
386static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500387SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500389 if (self->strerror != NULL) {
390 Py_INCREF(self->strerror);
391 return self->strerror;
392 }
393 else
394 return PyObject_Str(self->args);
395}
396
397static void
398fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
399 int lineno, unsigned long errcode)
400{
401 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
402 PyObject *init_value, *msg, *key;
403
404 if (errcode != 0) {
405 int lib, reason;
406
407 lib = ERR_GET_LIB(errcode);
408 reason = ERR_GET_REASON(errcode);
409 key = Py_BuildValue("ii", lib, reason);
410 if (key == NULL)
411 goto fail;
412 reason_obj = PyDict_GetItem(err_codes_to_names, key);
413 Py_DECREF(key);
414 if (reason_obj == NULL) {
415 /* XXX if reason < 100, it might reflect a library number (!!) */
416 PyErr_Clear();
417 }
418 key = PyLong_FromLong(lib);
419 if (key == NULL)
420 goto fail;
421 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
422 Py_DECREF(key);
423 if (lib_obj == NULL) {
424 PyErr_Clear();
425 }
426 if (errstr == NULL)
427 errstr = ERR_reason_error_string(errcode);
428 }
429 if (errstr == NULL)
430 errstr = "unknown error";
431
432 if (reason_obj && lib_obj)
433 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
434 lib_obj, reason_obj, errstr, lineno);
435 else if (lib_obj)
436 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
437 lib_obj, errstr, lineno);
438 else
439 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
440 if (msg == NULL)
441 goto fail;
442
443 init_value = Py_BuildValue("iN", ssl_errno, msg);
444 if (init_value == NULL)
445 goto fail;
446
447 err_value = PyObject_CallObject(type, init_value);
448 Py_DECREF(init_value);
449 if (err_value == NULL)
450 goto fail;
451
452 if (reason_obj == NULL)
453 reason_obj = Py_None;
454 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
455 goto fail;
456 if (lib_obj == NULL)
457 lib_obj = Py_None;
458 if (PyObject_SetAttrString(err_value, "library", lib_obj))
459 goto fail;
460 PyErr_SetObject(type, err_value);
461fail:
462 Py_XDECREF(err_value);
463}
464
465static PyObject *
466PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
467{
468 PyObject *type = PySSLErrorObject;
469 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000470 int err;
471 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500472 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000473
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000474 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500475 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000476
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000477 if (obj->ssl != NULL) {
478 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000479
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000480 switch (err) {
481 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500482 errstr = "TLS/SSL connection has been closed (EOF)";
483 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000484 p = PY_SSL_ERROR_ZERO_RETURN;
485 break;
486 case SSL_ERROR_WANT_READ:
487 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500488 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000489 p = PY_SSL_ERROR_WANT_READ;
490 break;
491 case SSL_ERROR_WANT_WRITE:
492 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500493 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000494 errstr = "The operation did not complete (write)";
495 break;
496 case SSL_ERROR_WANT_X509_LOOKUP:
497 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000498 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000499 break;
500 case SSL_ERROR_WANT_CONNECT:
501 p = PY_SSL_ERROR_WANT_CONNECT;
502 errstr = "The operation did not complete (connect)";
503 break;
504 case SSL_ERROR_SYSCALL:
505 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000506 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500507 PySocketSockObject *s = obj->Socket;
508 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000509 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500510 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000511 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000512 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000513 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500514 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000515 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500516 s->errorhandler();
517 Py_DECREF(s);
518 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000519 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000520 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500521 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000522 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000523 }
524 } else {
525 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000526 }
527 break;
528 }
529 case SSL_ERROR_SSL:
530 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000531 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500532 if (e == 0)
533 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000534 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000535 break;
536 }
537 default:
538 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
539 errstr = "Invalid error code";
540 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000541 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500542 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000543 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000544 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000545}
546
Bill Janssen98d19da2007-09-10 21:51:02 +0000547static PyObject *
548_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
549
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500550 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000551 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552 else
553 errcode = 0;
554 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000555 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000556 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000557}
558
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500559/*
560 * SSL objects
561 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000562
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500563static PySSLSocket *
564newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
565 enum py_ssl_server_or_client socket_type,
566 char *server_hostname, PyObject *ssl_sock)
567{
568 PySSLSocket *self;
569 SSL_CTX *ctx = sslctx->ctx;
570 long mode;
571
572 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000573 if (self == NULL)
574 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500575
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000576 self->peer_cert = NULL;
577 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000578 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500579 self->ssl_sock = NULL;
580 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200581 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500582 self->handshake_done = 0;
583 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000584
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000585 /* Make sure the SSL error state is initialized */
586 (void) ERR_get_state();
587 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000588
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000589 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500590 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000591 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500592 SSL_set_app_data(self->ssl,self);
593 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
594 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000595#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500596 mode |= SSL_MODE_AUTO_RETRY;
597#endif
598 SSL_set_mode(self->ssl, mode);
599
600#if HAVE_SNI
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800601 if (server_hostname != NULL) {
602/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
603 * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
604 * available on all platforms. Use OpenSSL's IP address parser. It's
605 * available since 1.0.2 and LibreSSL since at least 2.3.0. */
606 int send_sni = 1;
607#if OPENSSL_VERSION_NUMBER >= 0x10200000L
608 ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
609 if (ip == NULL) {
610 send_sni = 1;
611 ERR_clear_error();
612 } else {
613 send_sni = 0;
614 ASN1_OCTET_STRING_free(ip);
615 }
616#elif defined(HAVE_INET_PTON)
617#ifdef ENABLE_IPV6
Christian Heimes439956a2018-02-25 13:08:05 +0100618 #define PySSL_MAX(x, y) (((x) > (y)) ? (x) : (y))
619 char packed[PySSL_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800620#else
621 char packed[sizeof(struct in_addr)];
622#endif /* ENABLE_IPV6 */
623 if (inet_pton(AF_INET, server_hostname, packed)) {
624 send_sni = 0;
625#ifdef ENABLE_IPV6
626 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
627 send_sni = 0;
628#endif /* ENABLE_IPV6 */
629 } else {
630 send_sni = 1;
631 }
632#endif /* HAVE_INET_PTON */
633 if (send_sni) {
634 SSL_set_tlsext_host_name(self->ssl, server_hostname);
635 }
636 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000637#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000638
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000639 /* If the socket is in non-blocking mode or timeout mode, set the BIO
640 * to non-blocking mode (blocking is the default)
641 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500642 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000643 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
644 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
645 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000646
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000647 PySSL_BEGIN_ALLOW_THREADS
648 if (socket_type == PY_SSL_CLIENT)
649 SSL_set_connect_state(self->ssl);
650 else
651 SSL_set_accept_state(self->ssl);
652 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000653
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500654 self->socket_type = socket_type;
655 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000656 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400657 if (ssl_sock != Py_None) {
658 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
659 if (self->ssl_sock == NULL) {
660 Py_DECREF(self);
661 return NULL;
662 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500663 }
664 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000665}
666
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000667
668/* SSL object methods */
669
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500670static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000671{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000672 int ret;
673 int err;
674 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500675 PySocketSockObject *sock = self->Socket;
676
677 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000678
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000679 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500680 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000681 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
682 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000683
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000684 /* Actually negotiate SSL connection */
685 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
686 do {
687 PySSL_BEGIN_ALLOW_THREADS
688 ret = SSL_do_handshake(self->ssl);
689 err = SSL_get_error(self->ssl, ret);
690 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500691 if (PyErr_CheckSignals())
692 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000693 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500694 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000695 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500696 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000697 } else {
698 sockstate = SOCKET_OPERATION_OK;
699 }
700 if (sockstate == SOCKET_HAS_TIMED_OUT) {
701 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000702 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500703 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000704 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
705 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000706 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500707 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000708 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
709 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000710 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500711 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000712 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
713 break;
714 }
715 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500716 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000717 if (ret < 1)
718 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000719
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000720 if (self->peer_cert)
721 X509_free (self->peer_cert);
722 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500723 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000724 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500725 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000726
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000727 Py_INCREF(Py_None);
728 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000729
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500730error:
731 Py_DECREF(sock);
732 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000733}
734
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000735static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200736_asn1obj2py(const ASN1_OBJECT *name, int no_name)
737{
738 char buf[X509_NAME_MAXLEN];
739 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000740 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200741 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000742
Christian Heimesc9d668c2017-09-05 19:13:07 +0200743 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000744 if (buflen < 0) {
745 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200746 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000747 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200748 /* initial buffer is too small for oid + terminating null byte */
749 if (buflen > X509_NAME_MAXLEN - 1) {
750 /* make OBJ_obj2txt() calculate the required buflen */
751 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
752 /* allocate len + 1 for terminating NULL byte */
753 namebuf = PyMem_Malloc(buflen + 1);
754 if (namebuf == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
758 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
759 if (buflen < 0) {
760 _setSSLError(NULL, 0, __FILE__, __LINE__);
761 goto done;
762 }
763 }
764 if (!buflen && no_name) {
765 Py_INCREF(Py_None);
766 name_obj = Py_None;
767 }
768 else {
769 name_obj = PyString_FromStringAndSize(namebuf, buflen);
770 }
771
772 done:
773 if (buf != namebuf) {
774 PyMem_Free(namebuf);
775 }
776 return name_obj;
777}
778
779static PyObject *
780_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
781{
782 Py_ssize_t buflen;
783 unsigned char *valuebuf = NULL;
784 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000785
786 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
787 if (buflen < 0) {
788 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200789 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000790 }
791 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000792 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000793
Christian Heimesc9d668c2017-09-05 19:13:07 +0200794 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
795 OPENSSL_free(valuebuf);
796 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000797}
798
799static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000800_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000801{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000802 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
803 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
804 PyObject *rdnt;
805 PyObject *attr = NULL; /* tuple to hold an attribute */
806 int entry_count = X509_NAME_entry_count(xname);
807 X509_NAME_ENTRY *entry;
808 ASN1_OBJECT *name;
809 ASN1_STRING *value;
810 int index_counter;
811 int rdn_level = -1;
812 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000813
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000814 dn = PyList_New(0);
815 if (dn == NULL)
816 return NULL;
817 /* now create another tuple to hold the top-level RDN */
818 rdn = PyList_New(0);
819 if (rdn == NULL)
820 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000822 for (index_counter = 0;
823 index_counter < entry_count;
824 index_counter++)
825 {
826 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000827
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000828 /* check to see if we've gotten to a new RDN */
829 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200830 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000831 /* yes, new RDN */
832 /* add old RDN to DN */
833 rdnt = PyList_AsTuple(rdn);
834 Py_DECREF(rdn);
835 if (rdnt == NULL)
836 goto fail0;
837 retcode = PyList_Append(dn, rdnt);
838 Py_DECREF(rdnt);
839 if (retcode < 0)
840 goto fail0;
841 /* create new RDN */
842 rdn = PyList_New(0);
843 if (rdn == NULL)
844 goto fail0;
845 }
846 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200847 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000848
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000849 /* now add this attribute to the current RDN */
850 name = X509_NAME_ENTRY_get_object(entry);
851 value = X509_NAME_ENTRY_get_data(entry);
852 attr = _create_tuple_for_attribute(name, value);
853 /*
854 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
855 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500856 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
857 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000858 */
859 if (attr == NULL)
860 goto fail1;
861 retcode = PyList_Append(rdn, attr);
862 Py_DECREF(attr);
863 if (retcode < 0)
864 goto fail1;
865 }
866 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100867 if (rdn != NULL) {
868 if (PyList_GET_SIZE(rdn) > 0) {
869 rdnt = PyList_AsTuple(rdn);
870 Py_DECREF(rdn);
871 if (rdnt == NULL)
872 goto fail0;
873 retcode = PyList_Append(dn, rdnt);
874 Py_DECREF(rdnt);
875 if (retcode < 0)
876 goto fail0;
877 }
878 else {
879 Py_DECREF(rdn);
880 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000881 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000882
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000883 /* convert list to tuple */
884 rdnt = PyList_AsTuple(dn);
885 Py_DECREF(dn);
886 if (rdnt == NULL)
887 return NULL;
888 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000889
890 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000891 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
893 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000894 Py_XDECREF(dn);
895 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000896}
897
898static PyObject *
899_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000900
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000901 /* this code follows the procedure outlined in
902 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
903 function to extract the STACK_OF(GENERAL_NAME),
904 then iterates through the stack to add the
905 names. */
906
907 int i, j;
908 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200909 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000910 X509_EXTENSION *ext = NULL;
911 GENERAL_NAMES *names = NULL;
912 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000913 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000914 BIO *biobuf = NULL;
915 char buf[2048];
916 char *vptr;
917 int len;
918 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000919#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000920 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000921#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000922 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000923#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000924
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000925 if (certificate == NULL)
926 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000927
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 /* get a memory buffer */
929 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000930
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200931 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000932 while ((i = X509_get_ext_by_NID(
933 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000934
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000935 if (peer_alt_names == Py_None) {
936 peer_alt_names = PyList_New(0);
937 if (peer_alt_names == NULL)
938 goto fail;
939 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000940
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000941 /* now decode the altName */
942 ext = X509_get_ext(certificate, i);
943 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500944 PyErr_SetString
945 (PySSLErrorObject,
946 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000947 goto fail;
948 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000949
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200950 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000951 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500952 names = (GENERAL_NAMES*)
953 (ASN1_item_d2i(NULL,
954 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200955 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500956 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000957 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500958 names = (GENERAL_NAMES*)
959 (method->d2i(NULL,
960 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200961 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000962
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000963 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000964 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200965 int gntype;
966 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000967
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000968 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200969 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200970 switch (gntype) {
971 case GEN_DIRNAME:
972 /* we special-case DirName as a tuple of
973 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000974
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000975 t = PyTuple_New(2);
976 if (t == NULL) {
977 goto fail;
978 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000979
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000980 v = PyString_FromString("DirName");
981 if (v == NULL) {
982 Py_DECREF(t);
983 goto fail;
984 }
985 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000986
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000987 v = _create_tuple_for_X509_NAME (name->d.dirn);
988 if (v == NULL) {
989 Py_DECREF(t);
990 goto fail;
991 }
992 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200993 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000994
Christian Heimes88b174c2013-08-17 00:54:47 +0200995 case GEN_EMAIL:
996 case GEN_DNS:
997 case GEN_URI:
998 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
999 correctly, CVE-2013-4238 */
1000 t = PyTuple_New(2);
1001 if (t == NULL)
1002 goto fail;
1003 switch (gntype) {
1004 case GEN_EMAIL:
1005 v = PyString_FromString("email");
1006 as = name->d.rfc822Name;
1007 break;
1008 case GEN_DNS:
1009 v = PyString_FromString("DNS");
1010 as = name->d.dNSName;
1011 break;
1012 case GEN_URI:
1013 v = PyString_FromString("URI");
1014 as = name->d.uniformResourceIdentifier;
1015 break;
1016 }
1017 if (v == NULL) {
1018 Py_DECREF(t);
1019 goto fail;
1020 }
1021 PyTuple_SET_ITEM(t, 0, v);
1022 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1023 ASN1_STRING_length(as));
1024 if (v == NULL) {
1025 Py_DECREF(t);
1026 goto fail;
1027 }
1028 PyTuple_SET_ITEM(t, 1, v);
1029 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001030
Christian Heimes6663eb62016-09-06 23:25:35 +02001031 case GEN_RID:
1032 t = PyTuple_New(2);
1033 if (t == NULL)
1034 goto fail;
1035
1036 v = PyUnicode_FromString("Registered ID");
1037 if (v == NULL) {
1038 Py_DECREF(t);
1039 goto fail;
1040 }
1041 PyTuple_SET_ITEM(t, 0, v);
1042
1043 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1044 if (len < 0) {
1045 Py_DECREF(t);
1046 _setSSLError(NULL, 0, __FILE__, __LINE__);
1047 goto fail;
1048 } else if (len >= (int)sizeof(buf)) {
1049 v = PyUnicode_FromString("<INVALID>");
1050 } else {
1051 v = PyUnicode_FromStringAndSize(buf, len);
1052 }
1053 if (v == NULL) {
1054 Py_DECREF(t);
1055 goto fail;
1056 }
1057 PyTuple_SET_ITEM(t, 1, v);
1058 break;
1059
Christian Heimes88b174c2013-08-17 00:54:47 +02001060 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001061 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001062 switch (gntype) {
1063 /* check for new general name type */
1064 case GEN_OTHERNAME:
1065 case GEN_X400:
1066 case GEN_EDIPARTY:
1067 case GEN_IPADD:
1068 case GEN_RID:
1069 break;
1070 default:
1071 if (PyErr_Warn(PyExc_RuntimeWarning,
1072 "Unknown general name type") == -1) {
1073 goto fail;
1074 }
1075 break;
1076 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001077 (void) BIO_reset(biobuf);
1078 GENERAL_NAME_print(biobuf, name);
1079 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1080 if (len < 0) {
1081 _setSSLError(NULL, 0, __FILE__, __LINE__);
1082 goto fail;
1083 }
1084 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001085 if (vptr == NULL) {
1086 PyErr_Format(PyExc_ValueError,
1087 "Invalid value %.200s",
1088 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001089 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001090 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001091 t = PyTuple_New(2);
1092 if (t == NULL)
1093 goto fail;
1094 v = PyString_FromStringAndSize(buf, (vptr - buf));
1095 if (v == NULL) {
1096 Py_DECREF(t);
1097 goto fail;
1098 }
1099 PyTuple_SET_ITEM(t, 0, v);
1100 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1101 if (v == NULL) {
1102 Py_DECREF(t);
1103 goto fail;
1104 }
1105 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001106 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001107 }
1108
1109 /* and add that rendering to the list */
1110
1111 if (PyList_Append(peer_alt_names, t) < 0) {
1112 Py_DECREF(t);
1113 goto fail;
1114 }
1115 Py_DECREF(t);
1116 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001117 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001118 }
1119 BIO_free(biobuf);
1120 if (peer_alt_names != Py_None) {
1121 v = PyList_AsTuple(peer_alt_names);
1122 Py_DECREF(peer_alt_names);
1123 return v;
1124 } else {
1125 return peer_alt_names;
1126 }
1127
Bill Janssen98d19da2007-09-10 21:51:02 +00001128
1129 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001130 if (biobuf != NULL)
1131 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001132
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001133 if (peer_alt_names != Py_None) {
1134 Py_XDECREF(peer_alt_names);
1135 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001136
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001137 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001138}
1139
1140static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001141_get_aia_uri(X509 *certificate, int nid) {
1142 PyObject *lst = NULL, *ostr = NULL;
1143 int i, result;
1144 AUTHORITY_INFO_ACCESS *info;
1145
1146 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001147 if (info == NULL)
1148 return Py_None;
1149 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1150 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001151 return Py_None;
1152 }
1153
1154 if ((lst = PyList_New(0)) == NULL) {
1155 goto fail;
1156 }
1157
1158 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1159 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1160 ASN1_IA5STRING *uri;
1161
1162 if ((OBJ_obj2nid(ad->method) != nid) ||
1163 (ad->location->type != GEN_URI)) {
1164 continue;
1165 }
1166 uri = ad->location->d.uniformResourceIdentifier;
1167 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1168 uri->length);
1169 if (ostr == NULL) {
1170 goto fail;
1171 }
1172 result = PyList_Append(lst, ostr);
1173 Py_DECREF(ostr);
1174 if (result < 0) {
1175 goto fail;
1176 }
1177 }
1178 AUTHORITY_INFO_ACCESS_free(info);
1179
1180 /* convert to tuple or None */
1181 if (PyList_Size(lst) == 0) {
1182 Py_DECREF(lst);
1183 return Py_None;
1184 } else {
1185 PyObject *tup;
1186 tup = PyList_AsTuple(lst);
1187 Py_DECREF(lst);
1188 return tup;
1189 }
1190
1191 fail:
1192 AUTHORITY_INFO_ACCESS_free(info);
1193 Py_XDECREF(lst);
1194 return NULL;
1195}
1196
1197static PyObject *
1198_get_crl_dp(X509 *certificate) {
1199 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001200 int i, j;
1201 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001202
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001203 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001204
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001205 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001206 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001207
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001208 lst = PyList_New(0);
1209 if (lst == NULL)
1210 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001211
1212 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1213 DIST_POINT *dp;
1214 STACK_OF(GENERAL_NAME) *gns;
1215
1216 dp = sk_DIST_POINT_value(dps, i);
1217 gns = dp->distpoint->name.fullname;
1218
1219 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1220 GENERAL_NAME *gn;
1221 ASN1_IA5STRING *uri;
1222 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001223 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001224
1225 gn = sk_GENERAL_NAME_value(gns, j);
1226 if (gn->type != GEN_URI) {
1227 continue;
1228 }
1229 uri = gn->d.uniformResourceIdentifier;
1230 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1231 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001232 if (ouri == NULL)
1233 goto done;
1234
1235 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001236 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001237 if (err < 0)
1238 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001239 }
1240 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001241
1242 /* Convert to tuple. */
1243 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1244
1245 done:
1246 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001247 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001248 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001249}
1250
1251static PyObject *
1252_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001253
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001254 PyObject *retval = NULL;
1255 BIO *biobuf = NULL;
1256 PyObject *peer;
1257 PyObject *peer_alt_names = NULL;
1258 PyObject *issuer;
1259 PyObject *version;
1260 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001261 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001262 ASN1_INTEGER *serialNumber;
1263 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001264 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001265 ASN1_TIME *notBefore, *notAfter;
1266 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001267
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001268 retval = PyDict_New();
1269 if (retval == NULL)
1270 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001271
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001272 peer = _create_tuple_for_X509_NAME(
1273 X509_get_subject_name(certificate));
1274 if (peer == NULL)
1275 goto fail0;
1276 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1277 Py_DECREF(peer);
1278 goto fail0;
1279 }
1280 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001281
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001282 issuer = _create_tuple_for_X509_NAME(
1283 X509_get_issuer_name(certificate));
1284 if (issuer == NULL)
1285 goto fail0;
1286 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001287 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001288 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001289 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001290 Py_DECREF(issuer);
1291
1292 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1293 if (version == NULL)
1294 goto fail0;
1295 if (PyDict_SetItemString(retval, "version", version) < 0) {
1296 Py_DECREF(version);
1297 goto fail0;
1298 }
1299 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001300
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001301 /* get a memory buffer */
1302 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001303
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001304 (void) BIO_reset(biobuf);
1305 serialNumber = X509_get_serialNumber(certificate);
1306 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1307 i2a_ASN1_INTEGER(biobuf, serialNumber);
1308 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1309 if (len < 0) {
1310 _setSSLError(NULL, 0, __FILE__, __LINE__);
1311 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001312 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001313 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1314 if (sn_obj == NULL)
1315 goto fail1;
1316 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1317 Py_DECREF(sn_obj);
1318 goto fail1;
1319 }
1320 Py_DECREF(sn_obj);
1321
1322 (void) BIO_reset(biobuf);
1323 notBefore = X509_get_notBefore(certificate);
1324 ASN1_TIME_print(biobuf, notBefore);
1325 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1326 if (len < 0) {
1327 _setSSLError(NULL, 0, __FILE__, __LINE__);
1328 goto fail1;
1329 }
1330 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1331 if (pnotBefore == NULL)
1332 goto fail1;
1333 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1334 Py_DECREF(pnotBefore);
1335 goto fail1;
1336 }
1337 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001338
1339 (void) BIO_reset(biobuf);
1340 notAfter = X509_get_notAfter(certificate);
1341 ASN1_TIME_print(biobuf, notAfter);
1342 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1343 if (len < 0) {
1344 _setSSLError(NULL, 0, __FILE__, __LINE__);
1345 goto fail1;
1346 }
1347 pnotAfter = PyString_FromStringAndSize(buf, len);
1348 if (pnotAfter == NULL)
1349 goto fail1;
1350 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1351 Py_DECREF(pnotAfter);
1352 goto fail1;
1353 }
1354 Py_DECREF(pnotAfter);
1355
1356 /* Now look for subjectAltName */
1357
1358 peer_alt_names = _get_peer_alt_names(certificate);
1359 if (peer_alt_names == NULL)
1360 goto fail1;
1361 else if (peer_alt_names != Py_None) {
1362 if (PyDict_SetItemString(retval, "subjectAltName",
1363 peer_alt_names) < 0) {
1364 Py_DECREF(peer_alt_names);
1365 goto fail1;
1366 }
1367 Py_DECREF(peer_alt_names);
1368 }
1369
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001370 /* Authority Information Access: OCSP URIs */
1371 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1372 if (obj == NULL) {
1373 goto fail1;
1374 } else if (obj != Py_None) {
1375 result = PyDict_SetItemString(retval, "OCSP", obj);
1376 Py_DECREF(obj);
1377 if (result < 0) {
1378 goto fail1;
1379 }
1380 }
1381
1382 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1383 if (obj == NULL) {
1384 goto fail1;
1385 } else if (obj != Py_None) {
1386 result = PyDict_SetItemString(retval, "caIssuers", obj);
1387 Py_DECREF(obj);
1388 if (result < 0) {
1389 goto fail1;
1390 }
1391 }
1392
1393 /* CDP (CRL distribution points) */
1394 obj = _get_crl_dp(certificate);
1395 if (obj == NULL) {
1396 goto fail1;
1397 } else if (obj != Py_None) {
1398 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1399 Py_DECREF(obj);
1400 if (result < 0) {
1401 goto fail1;
1402 }
1403 }
1404
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001405 BIO_free(biobuf);
1406 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001407
1408 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001409 if (biobuf != NULL)
1410 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001411 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001412 Py_XDECREF(retval);
1413 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001414}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001415
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001416static PyObject *
1417_certificate_to_der(X509 *certificate)
1418{
1419 unsigned char *bytes_buf = NULL;
1420 int len;
1421 PyObject *retval;
1422
1423 bytes_buf = NULL;
1424 len = i2d_X509(certificate, &bytes_buf);
1425 if (len < 0) {
1426 _setSSLError(NULL, 0, __FILE__, __LINE__);
1427 return NULL;
1428 }
1429 /* this is actually an immutable bytes sequence */
1430 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1431 OPENSSL_free(bytes_buf);
1432 return retval;
1433}
Bill Janssen98d19da2007-09-10 21:51:02 +00001434
1435static PyObject *
1436PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1437
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001438 PyObject *retval = NULL;
1439 char *filename = NULL;
1440 X509 *x=NULL;
1441 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001442
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001443 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001444 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001445
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001446 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001447 PyErr_SetString(PySSLErrorObject,
1448 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001449 goto fail0;
1450 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001453 PyErr_SetString(PySSLErrorObject,
1454 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001455 goto fail0;
1456 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001457
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001458 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1459 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001460 PyErr_SetString(PySSLErrorObject,
1461 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001462 goto fail0;
1463 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001464
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001465 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001466 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001467
1468 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001469
1470 if (cert != NULL) BIO_free(cert);
1471 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001472}
1473
1474
1475static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001476PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001477{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001478 int verification;
1479 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001480 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001481
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001482 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1483 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001484
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001485 if (!self->handshake_done) {
1486 PyErr_SetString(PyExc_ValueError,
1487 "handshake not done yet");
1488 return NULL;
1489 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001490 if (!self->peer_cert)
1491 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001492
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001493 b = PyObject_IsTrue(binary_mode);
1494 if (b < 0)
1495 return NULL;
1496 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001497 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001498 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001499 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001500 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001501 if ((verification & SSL_VERIFY_PEER) == 0)
1502 return PyDict_New();
1503 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001504 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001505 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001506}
1507
1508PyDoc_STRVAR(PySSL_peercert_doc,
1509"peer_certificate([der=False]) -> certificate\n\
1510\n\
1511Returns the certificate for the peer. If no certificate was provided,\n\
1512returns None. If a certificate was provided, but not validated, returns\n\
1513an empty dictionary. Otherwise returns a dict containing information\n\
1514about the peer certificate.\n\
1515\n\
1516If the optional argument is True, returns a DER-encoded copy of the\n\
1517peer certificate, or None if no certificate was provided. This will\n\
1518return the certificate even if it wasn't validated.");
1519
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001520static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001521
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001522 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001523 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001524 char *cipher_name;
1525 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001526
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001527 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001528 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001529 current = SSL_get_current_cipher(self->ssl);
1530 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001531 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001532
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001533 retval = PyTuple_New(3);
1534 if (retval == NULL)
1535 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001536
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001537 cipher_name = (char *) SSL_CIPHER_get_name(current);
1538 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001539 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001540 PyTuple_SET_ITEM(retval, 0, Py_None);
1541 } else {
1542 v = PyString_FromString(cipher_name);
1543 if (v == NULL)
1544 goto fail0;
1545 PyTuple_SET_ITEM(retval, 0, v);
1546 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001547 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001548 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001549 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001550 PyTuple_SET_ITEM(retval, 1, Py_None);
1551 } else {
1552 v = PyString_FromString(cipher_protocol);
1553 if (v == NULL)
1554 goto fail0;
1555 PyTuple_SET_ITEM(retval, 1, v);
1556 }
1557 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1558 if (v == NULL)
1559 goto fail0;
1560 PyTuple_SET_ITEM(retval, 2, v);
1561 return retval;
1562
Bill Janssen98d19da2007-09-10 21:51:02 +00001563 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001564 Py_DECREF(retval);
1565 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001566}
1567
Alex Gaynore98205d2014-09-04 13:33:22 -07001568static PyObject *PySSL_version(PySSLSocket *self)
1569{
1570 const char *version;
1571
1572 if (self->ssl == NULL)
1573 Py_RETURN_NONE;
1574 version = SSL_get_version(self->ssl);
1575 if (!strcmp(version, "unknown"))
1576 Py_RETURN_NONE;
1577 return PyUnicode_FromString(version);
1578}
1579
Christian Heimes72ed2332017-09-05 01:11:40 +02001580#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001581static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1582 const unsigned char *out;
1583 unsigned int outlen;
1584
1585 SSL_get0_next_proto_negotiated(self->ssl,
1586 &out, &outlen);
1587
1588 if (out == NULL)
1589 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001590 return PyString_FromStringAndSize((char *)out, outlen);
1591}
1592#endif
1593
Christian Heimesdf1732a2018-02-25 14:28:55 +01001594#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001595static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1596 const unsigned char *out;
1597 unsigned int outlen;
1598
1599 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1600
1601 if (out == NULL)
1602 Py_RETURN_NONE;
1603 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001604}
1605#endif
1606
1607static PyObject *PySSL_compression(PySSLSocket *self) {
1608#ifdef OPENSSL_NO_COMP
1609 Py_RETURN_NONE;
1610#else
1611 const COMP_METHOD *comp_method;
1612 const char *short_name;
1613
1614 if (self->ssl == NULL)
1615 Py_RETURN_NONE;
1616 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001617 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001618 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001619 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001620 if (short_name == NULL)
1621 Py_RETURN_NONE;
1622 return PyBytes_FromString(short_name);
1623#endif
1624}
1625
1626static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1627 Py_INCREF(self->ctx);
1628 return self->ctx;
1629}
1630
1631static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1632 void *closure) {
1633
1634 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1635#if !HAVE_SNI
1636 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1637 "context is not supported by your OpenSSL library");
1638 return -1;
1639#else
1640 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001641 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001642 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1643#endif
1644 } else {
1645 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1646 return -1;
1647 }
1648
1649 return 0;
1650}
1651
1652PyDoc_STRVAR(PySSL_set_context_doc,
1653"_setter_context(ctx)\n\
1654\
1655This changes the context associated with the SSLSocket. This is typically\n\
1656used from within a callback function set by the set_servername_callback\n\
1657on the SSLContext to change the certificate information associated with the\n\
1658SSLSocket before the cryptographic exchange handshake messages\n");
1659
1660
1661
1662static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001663{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001664 if (self->peer_cert) /* Possible not to have one? */
1665 X509_free (self->peer_cert);
1666 if (self->ssl)
1667 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001668 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001669 Py_XDECREF(self->ssl_sock);
1670 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001671 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001672}
1673
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001674/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001675 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001676 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001677 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001678
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001679static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001680check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001681{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001682 fd_set fds;
1683 struct timeval tv;
1684 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001685
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001686 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1687 if (s->sock_timeout < 0.0)
1688 return SOCKET_IS_BLOCKING;
1689 else if (s->sock_timeout == 0.0)
1690 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001691
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001692 /* Guard against closed socket */
1693 if (s->sock_fd < 0)
1694 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001695
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001696 /* Prefer poll, if available, since you can poll() any fd
1697 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001698#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001699 {
1700 struct pollfd pollfd;
1701 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001702
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001703 pollfd.fd = s->sock_fd;
1704 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001705
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001706 /* s->sock_timeout is in seconds, timeout in ms */
1707 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1708 PySSL_BEGIN_ALLOW_THREADS
1709 rc = poll(&pollfd, 1, timeout);
1710 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001711
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001712 goto normal_return;
1713 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001714#endif
1715
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001716 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001717 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001719
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 /* Construct the arguments to select */
1721 tv.tv_sec = (int)s->sock_timeout;
1722 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1723 FD_ZERO(&fds);
1724 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001725
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001726 /* See if the socket is ready */
1727 PySSL_BEGIN_ALLOW_THREADS
1728 if (writing)
1729 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1730 else
1731 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1732 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001733
Bill Janssen934b16d2008-06-28 22:19:33 +00001734#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001735normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001736#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001737 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1738 (when we are able to write or when there's something to read) */
1739 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001740}
1741
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001742static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001743{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001744 Py_buffer buf;
1745 int len;
1746 int sockstate;
1747 int err;
1748 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001749 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001751 Py_INCREF(sock);
1752
1753 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1754 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001755 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001756 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001757
Victor Stinnerc1a44262013-06-25 00:48:02 +02001758 if (buf.len > INT_MAX) {
1759 PyErr_Format(PyExc_OverflowError,
1760 "string longer than %d bytes", INT_MAX);
1761 goto error;
1762 }
1763
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001764 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001765 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001766 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1767 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001768
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001769 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001770 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1771 PyErr_SetString(PySSLErrorObject,
1772 "The write operation timed out");
1773 goto error;
1774 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1775 PyErr_SetString(PySSLErrorObject,
1776 "Underlying socket has been closed.");
1777 goto error;
1778 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1779 PyErr_SetString(PySSLErrorObject,
1780 "Underlying socket too large for select().");
1781 goto error;
1782 }
1783 do {
1784 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001785 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001786 err = SSL_get_error(self->ssl, len);
1787 PySSL_END_ALLOW_THREADS
1788 if (PyErr_CheckSignals()) {
1789 goto error;
1790 }
1791 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001792 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001793 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001794 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001795 } else {
1796 sockstate = SOCKET_OPERATION_OK;
1797 }
1798 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1799 PyErr_SetString(PySSLErrorObject,
1800 "The write operation timed out");
1801 goto error;
1802 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1803 PyErr_SetString(PySSLErrorObject,
1804 "Underlying socket has been closed.");
1805 goto error;
1806 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1807 break;
1808 }
1809 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001810
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001811 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001812 PyBuffer_Release(&buf);
1813 if (len > 0)
1814 return PyInt_FromLong(len);
1815 else
1816 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001817
1818error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001819 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001820 PyBuffer_Release(&buf);
1821 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001822}
1823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001824PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001825"write(s) -> len\n\
1826\n\
1827Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001828of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001829
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001830static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001831{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001832 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001833
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001834 PySSL_BEGIN_ALLOW_THREADS
1835 count = SSL_pending(self->ssl);
1836 PySSL_END_ALLOW_THREADS
1837 if (count < 0)
1838 return PySSL_SetError(self, count, __FILE__, __LINE__);
1839 else
1840 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001841}
1842
1843PyDoc_STRVAR(PySSL_SSLpending_doc,
1844"pending() -> count\n\
1845\n\
1846Returns the number of already decrypted bytes available for read,\n\
1847pending on the connection.\n");
1848
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001849static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001850{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001851 PyObject *dest = NULL;
1852 Py_buffer buf;
1853 char *mem;
1854 int len, count;
1855 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001856 int sockstate;
1857 int err;
1858 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001859 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001860
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001861 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001862
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001863 buf.obj = NULL;
1864 buf.buf = NULL;
1865 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1866 goto error;
1867
1868 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001869 if (len < 0) {
1870 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1871 goto error;
1872 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001873 dest = PyBytes_FromStringAndSize(NULL, len);
1874 if (dest == NULL)
1875 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001876 if (len == 0) {
1877 Py_XDECREF(sock);
1878 return dest;
1879 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001880 mem = PyBytes_AS_STRING(dest);
1881 }
1882 else {
1883 buf_passed = 1;
1884 mem = buf.buf;
1885 if (len <= 0 || len > buf.len) {
1886 len = (int) buf.len;
1887 if (buf.len != len) {
1888 PyErr_SetString(PyExc_OverflowError,
1889 "maximum length can't fit in a C 'int'");
1890 goto error;
1891 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001892 if (len == 0) {
1893 count = 0;
1894 goto done;
1895 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001896 }
1897 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001898
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001899 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001900 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001901 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1902 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001903
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001904 do {
1905 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001906 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 err = SSL_get_error(self->ssl, count);
1908 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001909 if (PyErr_CheckSignals())
1910 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001911 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001912 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001913 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001914 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001915 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1916 (SSL_get_shutdown(self->ssl) ==
1917 SSL_RECEIVED_SHUTDOWN))
1918 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001919 count = 0;
1920 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001921 } else {
1922 sockstate = SOCKET_OPERATION_OK;
1923 }
1924 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1925 PyErr_SetString(PySSLErrorObject,
1926 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001927 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001928 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1929 break;
1930 }
1931 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1932 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001933 PySSL_SetError(self, count, __FILE__, __LINE__);
1934 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001935 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001936
1937done:
1938 Py_DECREF(sock);
1939 if (!buf_passed) {
1940 _PyBytes_Resize(&dest, count);
1941 return dest;
1942 }
1943 else {
1944 PyBuffer_Release(&buf);
1945 return PyLong_FromLong(count);
1946 }
1947
1948error:
1949 Py_DECREF(sock);
1950 if (!buf_passed)
1951 Py_XDECREF(dest);
1952 else
1953 PyBuffer_Release(&buf);
1954 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001955}
1956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001957PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001958"read([len]) -> string\n\
1959\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001960Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001961
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001962static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001963{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001964 int err, ssl_err, sockstate, nonblocking;
1965 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001966 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001967
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001968 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001969 if (sock->sock_fd < 0) {
1970 _setSSLError("Underlying socket connection gone",
1971 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001972 return NULL;
1973 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001974 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001975
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001976 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001977 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001978 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1979 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001980
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001981 while (1) {
1982 PySSL_BEGIN_ALLOW_THREADS
1983 /* Disable read-ahead so that unwrap can work correctly.
1984 * Otherwise OpenSSL might read in too much data,
1985 * eating clear text data that happens to be
1986 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001987 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001988 * function is used and the shutdown_seen_zero != 0
1989 * condition is met.
1990 */
1991 if (self->shutdown_seen_zero)
1992 SSL_set_read_ahead(self->ssl, 0);
1993 err = SSL_shutdown(self->ssl);
1994 PySSL_END_ALLOW_THREADS
1995 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1996 if (err > 0)
1997 break;
1998 if (err == 0) {
1999 /* Don't loop endlessly; instead preserve legacy
2000 behaviour of trying SSL_shutdown() only twice.
2001 This looks necessary for OpenSSL < 0.9.8m */
2002 if (++zeros > 1)
2003 break;
2004 /* Shutdown was sent, now try receiving */
2005 self->shutdown_seen_zero = 1;
2006 continue;
2007 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00002008
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002009 /* Possibly retry shutdown until timeout or failure */
2010 ssl_err = SSL_get_error(self->ssl, err);
2011 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002012 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002013 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002014 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002015 else
2016 break;
2017 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2018 if (ssl_err == SSL_ERROR_WANT_READ)
2019 PyErr_SetString(PySSLErrorObject,
2020 "The read operation timed out");
2021 else
2022 PyErr_SetString(PySSLErrorObject,
2023 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002024 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002025 }
2026 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2027 PyErr_SetString(PySSLErrorObject,
2028 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002029 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002030 }
2031 else if (sockstate != SOCKET_OPERATION_OK)
2032 /* Retain the SSL error code */
2033 break;
2034 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002035
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002036 if (err < 0) {
2037 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002038 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002039 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002040 else
2041 /* It's already INCREF'ed */
2042 return (PyObject *) sock;
2043
2044error:
2045 Py_DECREF(sock);
2046 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002047}
2048
2049PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2050"shutdown(s) -> socket\n\
2051\n\
2052Does the SSL shutdown handshake with the remote end, and returns\n\
2053the underlying socket object.");
2054
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002055#if HAVE_OPENSSL_FINISHED
2056static PyObject *
2057PySSL_tls_unique_cb(PySSLSocket *self)
2058{
2059 PyObject *retval = NULL;
2060 char buf[PySSL_CB_MAXLEN];
2061 size_t len;
2062
2063 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2064 /* if session is resumed XOR we are the client */
2065 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2066 }
2067 else {
2068 /* if a new session XOR we are the server */
2069 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2070 }
2071
2072 /* It cannot be negative in current OpenSSL version as of July 2011 */
2073 if (len == 0)
2074 Py_RETURN_NONE;
2075
2076 retval = PyBytes_FromStringAndSize(buf, len);
2077
2078 return retval;
2079}
2080
2081PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2082"tls_unique_cb() -> bytes\n\
2083\n\
2084Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2085\n\
2086If the TLS handshake is not yet complete, None is returned");
2087
2088#endif /* HAVE_OPENSSL_FINISHED */
2089
2090static PyGetSetDef ssl_getsetlist[] = {
2091 {"context", (getter) PySSL_get_context,
2092 (setter) PySSL_set_context, PySSL_set_context_doc},
2093 {NULL}, /* sentinel */
2094};
2095
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002096static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002097 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2098 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2099 PySSL_SSLwrite_doc},
2100 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2101 PySSL_SSLread_doc},
2102 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2103 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002104 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2105 PySSL_peercert_doc},
2106 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002107 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002108#ifdef OPENSSL_NPN_NEGOTIATED
2109 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2110#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002111#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002112 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2113#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002114 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002115 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2116 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002117#if HAVE_OPENSSL_FINISHED
2118 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2119 PySSL_tls_unique_cb_doc},
2120#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002121 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002122};
2123
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002124static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002125 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002126 "_ssl._SSLSocket", /*tp_name*/
2127 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002128 0, /*tp_itemsize*/
2129 /* methods */
2130 (destructor)PySSL_dealloc, /*tp_dealloc*/
2131 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002132 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002133 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002134 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002135 0, /*tp_repr*/
2136 0, /*tp_as_number*/
2137 0, /*tp_as_sequence*/
2138 0, /*tp_as_mapping*/
2139 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002140 0, /*tp_call*/
2141 0, /*tp_str*/
2142 0, /*tp_getattro*/
2143 0, /*tp_setattro*/
2144 0, /*tp_as_buffer*/
2145 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2146 0, /*tp_doc*/
2147 0, /*tp_traverse*/
2148 0, /*tp_clear*/
2149 0, /*tp_richcompare*/
2150 0, /*tp_weaklistoffset*/
2151 0, /*tp_iter*/
2152 0, /*tp_iternext*/
2153 PySSLMethods, /*tp_methods*/
2154 0, /*tp_members*/
2155 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156};
2157
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002158
2159/*
2160 * _SSLContext objects
2161 */
2162
2163static PyObject *
2164context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2165{
2166 char *kwlist[] = {"protocol", NULL};
2167 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002168 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002169 long options;
2170 SSL_CTX *ctx = NULL;
2171
2172 if (!PyArg_ParseTupleAndKeywords(
2173 args, kwds, "i:_SSLContext", kwlist,
2174 &proto_version))
2175 return NULL;
2176
2177 PySSL_BEGIN_ALLOW_THREADS
2178 if (proto_version == PY_SSL_VERSION_TLS1)
2179 ctx = SSL_CTX_new(TLSv1_method());
2180#if HAVE_TLSv1_2
2181 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2182 ctx = SSL_CTX_new(TLSv1_1_method());
2183 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2184 ctx = SSL_CTX_new(TLSv1_2_method());
2185#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002186#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002187 else if (proto_version == PY_SSL_VERSION_SSL3)
2188 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002189#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002190#ifndef OPENSSL_NO_SSL2
2191 else if (proto_version == PY_SSL_VERSION_SSL2)
2192 ctx = SSL_CTX_new(SSLv2_method());
2193#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002194 else if (proto_version == PY_SSL_VERSION_TLS)
2195 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002196 else
2197 proto_version = -1;
2198 PySSL_END_ALLOW_THREADS
2199
2200 if (proto_version == -1) {
2201 PyErr_SetString(PyExc_ValueError,
2202 "invalid protocol version");
2203 return NULL;
2204 }
2205 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002206 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002207 return NULL;
2208 }
2209
2210 assert(type != NULL && type->tp_alloc != NULL);
2211 self = (PySSLContext *) type->tp_alloc(type, 0);
2212 if (self == NULL) {
2213 SSL_CTX_free(ctx);
2214 return NULL;
2215 }
2216 self->ctx = ctx;
Christian Heimesdf1732a2018-02-25 14:28:55 +01002217#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002218 self->npn_protocols = NULL;
2219#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002220#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002221 self->alpn_protocols = NULL;
2222#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002223#ifndef OPENSSL_NO_TLSEXT
2224 self->set_hostname = NULL;
2225#endif
2226 /* Don't check host name by default */
2227 self->check_hostname = 0;
2228 /* Defaults */
2229 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2230 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2231 if (proto_version != PY_SSL_VERSION_SSL2)
2232 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002233 if (proto_version != PY_SSL_VERSION_SSL3)
2234 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002235 SSL_CTX_set_options(self->ctx, options);
2236
Donald Stufftf1a696e2017-03-02 12:37:07 -05002237#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002238 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2239 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002240 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2241 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002242#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002243 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2244#else
2245 {
2246 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2247 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2248 EC_KEY_free(key);
2249 }
2250#endif
2251#endif
2252
2253#define SID_CTX "Python"
2254 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2255 sizeof(SID_CTX));
2256#undef SID_CTX
2257
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002258#ifdef X509_V_FLAG_TRUSTED_FIRST
2259 {
2260 /* Improve trust chain building when cross-signed intermediate
2261 certificates are present. See https://bugs.python.org/issue23476. */
2262 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2263 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2264 }
2265#endif
2266
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002267 return (PyObject *)self;
2268}
2269
2270static int
2271context_traverse(PySSLContext *self, visitproc visit, void *arg)
2272{
2273#ifndef OPENSSL_NO_TLSEXT
2274 Py_VISIT(self->set_hostname);
2275#endif
2276 return 0;
2277}
2278
2279static int
2280context_clear(PySSLContext *self)
2281{
2282#ifndef OPENSSL_NO_TLSEXT
2283 Py_CLEAR(self->set_hostname);
2284#endif
2285 return 0;
2286}
2287
2288static void
2289context_dealloc(PySSLContext *self)
2290{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002291 /* bpo-31095: UnTrack is needed before calling any callbacks */
2292 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002293 context_clear(self);
2294 SSL_CTX_free(self->ctx);
Christian Heimesdf1732a2018-02-25 14:28:55 +01002295#if HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002296 PyMem_FREE(self->npn_protocols);
2297#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002298#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002299 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002300#endif
2301 Py_TYPE(self)->tp_free(self);
2302}
2303
2304static PyObject *
2305set_ciphers(PySSLContext *self, PyObject *args)
2306{
2307 int ret;
2308 const char *cipherlist;
2309
2310 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2311 return NULL;
2312 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2313 if (ret == 0) {
2314 /* Clearing the error queue is necessary on some OpenSSL versions,
2315 otherwise the error will be reported again when another SSL call
2316 is done. */
2317 ERR_clear_error();
2318 PyErr_SetString(PySSLErrorObject,
2319 "No cipher can be selected.");
2320 return NULL;
2321 }
2322 Py_RETURN_NONE;
2323}
2324
Christian Heimesdf1732a2018-02-25 14:28:55 +01002325#if HAVE_NPN || HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002326static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002327do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2328 const unsigned char *server_protocols, unsigned int server_protocols_len,
2329 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002330{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002331 int ret;
2332 if (client_protocols == NULL) {
2333 client_protocols = (unsigned char *)"";
2334 client_protocols_len = 0;
2335 }
2336 if (server_protocols == NULL) {
2337 server_protocols = (unsigned char *)"";
2338 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002339 }
2340
Benjamin Petersonaa707582015-01-23 17:30:26 -05002341 ret = SSL_select_next_proto(out, outlen,
2342 server_protocols, server_protocols_len,
2343 client_protocols, client_protocols_len);
2344 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2345 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002346
2347 return SSL_TLSEXT_ERR_OK;
2348}
Christian Heimes72ed2332017-09-05 01:11:40 +02002349#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002350
Christian Heimesdf1732a2018-02-25 14:28:55 +01002351#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002352/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2353static int
2354_advertiseNPN_cb(SSL *s,
2355 const unsigned char **data, unsigned int *len,
2356 void *args)
2357{
2358 PySSLContext *ssl_ctx = (PySSLContext *) args;
2359
2360 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002361 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002362 *len = 0;
2363 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002364 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002365 *len = ssl_ctx->npn_protocols_len;
2366 }
2367
2368 return SSL_TLSEXT_ERR_OK;
2369}
2370/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2371static int
2372_selectNPN_cb(SSL *s,
2373 unsigned char **out, unsigned char *outlen,
2374 const unsigned char *server, unsigned int server_len,
2375 void *args)
2376{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002377 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002378 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002379 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002380}
2381#endif
2382
2383static PyObject *
2384_set_npn_protocols(PySSLContext *self, PyObject *args)
2385{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002386#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002387 Py_buffer protos;
2388
2389 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2390 return NULL;
2391
2392 if (self->npn_protocols != NULL) {
2393 PyMem_Free(self->npn_protocols);
2394 }
2395
2396 self->npn_protocols = PyMem_Malloc(protos.len);
2397 if (self->npn_protocols == NULL) {
2398 PyBuffer_Release(&protos);
2399 return PyErr_NoMemory();
2400 }
2401 memcpy(self->npn_protocols, protos.buf, protos.len);
2402 self->npn_protocols_len = (int) protos.len;
2403
2404 /* set both server and client callbacks, because the context can
2405 * be used to create both types of sockets */
2406 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2407 _advertiseNPN_cb,
2408 self);
2409 SSL_CTX_set_next_proto_select_cb(self->ctx,
2410 _selectNPN_cb,
2411 self);
2412
2413 PyBuffer_Release(&protos);
2414 Py_RETURN_NONE;
2415#else
2416 PyErr_SetString(PyExc_NotImplementedError,
2417 "The NPN extension requires OpenSSL 1.0.1 or later.");
2418 return NULL;
2419#endif
2420}
2421
Christian Heimesdf1732a2018-02-25 14:28:55 +01002422#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002423static int
2424_selectALPN_cb(SSL *s,
2425 const unsigned char **out, unsigned char *outlen,
2426 const unsigned char *client_protocols, unsigned int client_protocols_len,
2427 void *args)
2428{
2429 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002430 return do_protocol_selection(1, (unsigned char **)out, outlen,
2431 ctx->alpn_protocols, ctx->alpn_protocols_len,
2432 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002433}
2434#endif
2435
2436static PyObject *
2437_set_alpn_protocols(PySSLContext *self, PyObject *args)
2438{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002439#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002440 Py_buffer protos;
2441
2442 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2443 return NULL;
2444
2445 PyMem_FREE(self->alpn_protocols);
2446 self->alpn_protocols = PyMem_Malloc(protos.len);
2447 if (!self->alpn_protocols)
2448 return PyErr_NoMemory();
2449 memcpy(self->alpn_protocols, protos.buf, protos.len);
2450 self->alpn_protocols_len = protos.len;
2451 PyBuffer_Release(&protos);
2452
2453 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2454 return PyErr_NoMemory();
2455 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2456
2457 PyBuffer_Release(&protos);
2458 Py_RETURN_NONE;
2459#else
2460 PyErr_SetString(PyExc_NotImplementedError,
2461 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2462 return NULL;
2463#endif
2464}
2465
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002466static PyObject *
2467get_verify_mode(PySSLContext *self, void *c)
2468{
2469 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2470 case SSL_VERIFY_NONE:
2471 return PyLong_FromLong(PY_SSL_CERT_NONE);
2472 case SSL_VERIFY_PEER:
2473 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2474 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2475 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2476 }
2477 PyErr_SetString(PySSLErrorObject,
2478 "invalid return value from SSL_CTX_get_verify_mode");
2479 return NULL;
2480}
2481
2482static int
2483set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2484{
2485 int n, mode;
2486 if (!PyArg_Parse(arg, "i", &n))
2487 return -1;
2488 if (n == PY_SSL_CERT_NONE)
2489 mode = SSL_VERIFY_NONE;
2490 else if (n == PY_SSL_CERT_OPTIONAL)
2491 mode = SSL_VERIFY_PEER;
2492 else if (n == PY_SSL_CERT_REQUIRED)
2493 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2494 else {
2495 PyErr_SetString(PyExc_ValueError,
2496 "invalid value for verify_mode");
2497 return -1;
2498 }
2499 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2500 PyErr_SetString(PyExc_ValueError,
2501 "Cannot set verify_mode to CERT_NONE when "
2502 "check_hostname is enabled.");
2503 return -1;
2504 }
2505 SSL_CTX_set_verify(self->ctx, mode, NULL);
2506 return 0;
2507}
2508
2509#ifdef HAVE_OPENSSL_VERIFY_PARAM
2510static PyObject *
2511get_verify_flags(PySSLContext *self, void *c)
2512{
2513 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002514 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002515 unsigned long flags;
2516
2517 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002518 param = X509_STORE_get0_param(store);
2519 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002520 return PyLong_FromUnsignedLong(flags);
2521}
2522
2523static int
2524set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2525{
2526 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002527 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002528 unsigned long new_flags, flags, set, clear;
2529
2530 if (!PyArg_Parse(arg, "k", &new_flags))
2531 return -1;
2532 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002533 param = X509_STORE_get0_param(store);
2534 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002535 clear = flags & ~new_flags;
2536 set = ~flags & new_flags;
2537 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002538 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002539 _setSSLError(NULL, 0, __FILE__, __LINE__);
2540 return -1;
2541 }
2542 }
2543 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002544 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002545 _setSSLError(NULL, 0, __FILE__, __LINE__);
2546 return -1;
2547 }
2548 }
2549 return 0;
2550}
2551#endif
2552
2553static PyObject *
2554get_options(PySSLContext *self, void *c)
2555{
2556 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2557}
2558
2559static int
2560set_options(PySSLContext *self, PyObject *arg, void *c)
2561{
2562 long new_opts, opts, set, clear;
2563 if (!PyArg_Parse(arg, "l", &new_opts))
2564 return -1;
2565 opts = SSL_CTX_get_options(self->ctx);
2566 clear = opts & ~new_opts;
2567 set = ~opts & new_opts;
2568 if (clear) {
2569#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2570 SSL_CTX_clear_options(self->ctx, clear);
2571#else
2572 PyErr_SetString(PyExc_ValueError,
2573 "can't clear options before OpenSSL 0.9.8m");
2574 return -1;
2575#endif
2576 }
2577 if (set)
2578 SSL_CTX_set_options(self->ctx, set);
2579 return 0;
2580}
2581
2582static PyObject *
2583get_check_hostname(PySSLContext *self, void *c)
2584{
2585 return PyBool_FromLong(self->check_hostname);
2586}
2587
2588static int
2589set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2590{
2591 PyObject *py_check_hostname;
2592 int check_hostname;
2593 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2594 return -1;
2595
2596 check_hostname = PyObject_IsTrue(py_check_hostname);
2597 if (check_hostname < 0)
2598 return -1;
2599 if (check_hostname &&
2600 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2601 PyErr_SetString(PyExc_ValueError,
2602 "check_hostname needs a SSL context with either "
2603 "CERT_OPTIONAL or CERT_REQUIRED");
2604 return -1;
2605 }
2606 self->check_hostname = check_hostname;
2607 return 0;
2608}
2609
2610
2611typedef struct {
2612 PyThreadState *thread_state;
2613 PyObject *callable;
2614 char *password;
2615 int size;
2616 int error;
2617} _PySSLPasswordInfo;
2618
2619static int
2620_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2621 const char *bad_type_error)
2622{
2623 /* Set the password and size fields of a _PySSLPasswordInfo struct
2624 from a unicode, bytes, or byte array object.
2625 The password field will be dynamically allocated and must be freed
2626 by the caller */
2627 PyObject *password_bytes = NULL;
2628 const char *data = NULL;
2629 Py_ssize_t size;
2630
2631 if (PyUnicode_Check(password)) {
2632 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2633 if (!password_bytes) {
2634 goto error;
2635 }
2636 data = PyBytes_AS_STRING(password_bytes);
2637 size = PyBytes_GET_SIZE(password_bytes);
2638 } else if (PyBytes_Check(password)) {
2639 data = PyBytes_AS_STRING(password);
2640 size = PyBytes_GET_SIZE(password);
2641 } else if (PyByteArray_Check(password)) {
2642 data = PyByteArray_AS_STRING(password);
2643 size = PyByteArray_GET_SIZE(password);
2644 } else {
2645 PyErr_SetString(PyExc_TypeError, bad_type_error);
2646 goto error;
2647 }
2648
2649 if (size > (Py_ssize_t)INT_MAX) {
2650 PyErr_Format(PyExc_ValueError,
2651 "password cannot be longer than %d bytes", INT_MAX);
2652 goto error;
2653 }
2654
2655 PyMem_Free(pw_info->password);
2656 pw_info->password = PyMem_Malloc(size);
2657 if (!pw_info->password) {
2658 PyErr_SetString(PyExc_MemoryError,
2659 "unable to allocate password buffer");
2660 goto error;
2661 }
2662 memcpy(pw_info->password, data, size);
2663 pw_info->size = (int)size;
2664
2665 Py_XDECREF(password_bytes);
2666 return 1;
2667
2668error:
2669 Py_XDECREF(password_bytes);
2670 return 0;
2671}
2672
2673static int
2674_password_callback(char *buf, int size, int rwflag, void *userdata)
2675{
2676 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2677 PyObject *fn_ret = NULL;
2678
2679 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2680
2681 if (pw_info->callable) {
2682 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2683 if (!fn_ret) {
2684 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2685 core python API, so we could use it to add a frame here */
2686 goto error;
2687 }
2688
2689 if (!_pwinfo_set(pw_info, fn_ret,
2690 "password callback must return a string")) {
2691 goto error;
2692 }
2693 Py_CLEAR(fn_ret);
2694 }
2695
2696 if (pw_info->size > size) {
2697 PyErr_Format(PyExc_ValueError,
2698 "password cannot be longer than %d bytes", size);
2699 goto error;
2700 }
2701
2702 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2703 memcpy(buf, pw_info->password, pw_info->size);
2704 return pw_info->size;
2705
2706error:
2707 Py_XDECREF(fn_ret);
2708 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2709 pw_info->error = 1;
2710 return -1;
2711}
2712
2713static PyObject *
2714load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2715{
2716 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002717 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2718 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002719 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2720 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002721 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2722 int r;
2723
2724 errno = 0;
2725 ERR_clear_error();
2726 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002727 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002728 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002729 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002730 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002731
2732 if (keyfile && keyfile != Py_None) {
2733 if (PyString_Check(keyfile)) {
2734 Py_INCREF(keyfile);
2735 keyfile_bytes = keyfile;
2736 } else {
2737 PyObject *u = PyUnicode_FromObject(keyfile);
2738 if (!u)
2739 goto error;
2740 keyfile_bytes = PyUnicode_AsEncodedString(
2741 u, Py_FileSystemDefaultEncoding, NULL);
2742 Py_DECREF(u);
2743 if (!keyfile_bytes)
2744 goto error;
2745 }
2746 }
2747
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002748 if (password && password != Py_None) {
2749 if (PyCallable_Check(password)) {
2750 pw_info.callable = password;
2751 } else if (!_pwinfo_set(&pw_info, password,
2752 "password should be a string or callable")) {
2753 goto error;
2754 }
2755 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2756 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2757 }
2758 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2759 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
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_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002777 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002778 SSL_FILETYPE_PEM);
2779 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2780 if (r != 1) {
2781 if (pw_info.error) {
2782 ERR_clear_error();
2783 /* the password callback has already set the error information */
2784 }
2785 else if (errno != 0) {
2786 ERR_clear_error();
2787 PyErr_SetFromErrno(PyExc_IOError);
2788 }
2789 else {
2790 _setSSLError(NULL, 0, __FILE__, __LINE__);
2791 }
2792 goto error;
2793 }
2794 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2795 r = SSL_CTX_check_private_key(self->ctx);
2796 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2797 if (r != 1) {
2798 _setSSLError(NULL, 0, __FILE__, __LINE__);
2799 goto error;
2800 }
2801 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2802 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002803 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002804 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002805 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002806 Py_RETURN_NONE;
2807
2808error:
2809 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2810 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002811 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002812 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002813 PyMem_Free(certfile_bytes);
2814 return NULL;
2815}
2816
2817/* internal helper function, returns -1 on error
2818 */
2819static int
2820_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2821 int filetype)
2822{
2823 BIO *biobuf = NULL;
2824 X509_STORE *store;
2825 int retval = 0, err, loaded = 0;
2826
2827 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2828
2829 if (len <= 0) {
2830 PyErr_SetString(PyExc_ValueError,
2831 "Empty certificate data");
2832 return -1;
2833 } else if (len > INT_MAX) {
2834 PyErr_SetString(PyExc_OverflowError,
2835 "Certificate data is too long.");
2836 return -1;
2837 }
2838
2839 biobuf = BIO_new_mem_buf(data, (int)len);
2840 if (biobuf == NULL) {
2841 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2842 return -1;
2843 }
2844
2845 store = SSL_CTX_get_cert_store(self->ctx);
2846 assert(store != NULL);
2847
2848 while (1) {
2849 X509 *cert = NULL;
2850 int r;
2851
2852 if (filetype == SSL_FILETYPE_ASN1) {
2853 cert = d2i_X509_bio(biobuf, NULL);
2854 } else {
2855 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002856 SSL_CTX_get_default_passwd_cb(self->ctx),
2857 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2858 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002859 }
2860 if (cert == NULL) {
2861 break;
2862 }
2863 r = X509_STORE_add_cert(store, cert);
2864 X509_free(cert);
2865 if (!r) {
2866 err = ERR_peek_last_error();
2867 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2868 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2869 /* cert already in hash table, not an error */
2870 ERR_clear_error();
2871 } else {
2872 break;
2873 }
2874 }
2875 loaded++;
2876 }
2877
2878 err = ERR_peek_last_error();
2879 if ((filetype == SSL_FILETYPE_ASN1) &&
2880 (loaded > 0) &&
2881 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2882 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2883 /* EOF ASN1 file, not an error */
2884 ERR_clear_error();
2885 retval = 0;
2886 } else if ((filetype == SSL_FILETYPE_PEM) &&
2887 (loaded > 0) &&
2888 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2889 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2890 /* EOF PEM file, not an error */
2891 ERR_clear_error();
2892 retval = 0;
2893 } else {
2894 _setSSLError(NULL, 0, __FILE__, __LINE__);
2895 retval = -1;
2896 }
2897
2898 BIO_free(biobuf);
2899 return retval;
2900}
2901
2902
2903static PyObject *
2904load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2905{
2906 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2907 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2908 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2909 const char *cafile_buf = NULL, *capath_buf = NULL;
2910 int r = 0, ok = 1;
2911
2912 errno = 0;
2913 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2914 "|OOO:load_verify_locations", kwlist,
2915 &cafile, &capath, &cadata))
2916 return NULL;
2917
2918 if (cafile == Py_None)
2919 cafile = NULL;
2920 if (capath == Py_None)
2921 capath = NULL;
2922 if (cadata == Py_None)
2923 cadata = NULL;
2924
2925 if (cafile == NULL && capath == NULL && cadata == NULL) {
2926 PyErr_SetString(PyExc_TypeError,
2927 "cafile, capath and cadata cannot be all omitted");
2928 goto error;
2929 }
2930
2931 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002932 if (PyString_Check(cafile)) {
2933 Py_INCREF(cafile);
2934 cafile_bytes = cafile;
2935 } else {
2936 PyObject *u = PyUnicode_FromObject(cafile);
2937 if (!u)
2938 goto error;
2939 cafile_bytes = PyUnicode_AsEncodedString(
2940 u, Py_FileSystemDefaultEncoding, NULL);
2941 Py_DECREF(u);
2942 if (!cafile_bytes)
2943 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002944 }
2945 }
2946 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002947 if (PyString_Check(capath)) {
2948 Py_INCREF(capath);
2949 capath_bytes = capath;
2950 } else {
2951 PyObject *u = PyUnicode_FromObject(capath);
2952 if (!u)
2953 goto error;
2954 capath_bytes = PyUnicode_AsEncodedString(
2955 u, Py_FileSystemDefaultEncoding, NULL);
2956 Py_DECREF(u);
2957 if (!capath_bytes)
2958 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002959 }
2960 }
2961
2962 /* validata cadata type and load cadata */
2963 if (cadata) {
2964 Py_buffer buf;
2965 PyObject *cadata_ascii = NULL;
2966
2967 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2968 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2969 PyBuffer_Release(&buf);
2970 PyErr_SetString(PyExc_TypeError,
2971 "cadata should be a contiguous buffer with "
2972 "a single dimension");
2973 goto error;
2974 }
2975 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2976 PyBuffer_Release(&buf);
2977 if (r == -1) {
2978 goto error;
2979 }
2980 } else {
2981 PyErr_Clear();
2982 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2983 if (cadata_ascii == NULL) {
2984 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002985 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002986 "bytes-like object");
2987 goto error;
2988 }
2989 r = _add_ca_certs(self,
2990 PyBytes_AS_STRING(cadata_ascii),
2991 PyBytes_GET_SIZE(cadata_ascii),
2992 SSL_FILETYPE_PEM);
2993 Py_DECREF(cadata_ascii);
2994 if (r == -1) {
2995 goto error;
2996 }
2997 }
2998 }
2999
3000 /* load cafile or capath */
3001 if (cafile_bytes || capath_bytes) {
3002 if (cafile)
3003 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3004 if (capath)
3005 capath_buf = PyBytes_AS_STRING(capath_bytes);
3006 PySSL_BEGIN_ALLOW_THREADS
3007 r = SSL_CTX_load_verify_locations(
3008 self->ctx,
3009 cafile_buf,
3010 capath_buf);
3011 PySSL_END_ALLOW_THREADS
3012 if (r != 1) {
3013 ok = 0;
3014 if (errno != 0) {
3015 ERR_clear_error();
3016 PyErr_SetFromErrno(PyExc_IOError);
3017 }
3018 else {
3019 _setSSLError(NULL, 0, __FILE__, __LINE__);
3020 }
3021 goto error;
3022 }
3023 }
3024 goto end;
3025
3026 error:
3027 ok = 0;
3028 end:
3029 Py_XDECREF(cafile_bytes);
3030 Py_XDECREF(capath_bytes);
3031 if (ok) {
3032 Py_RETURN_NONE;
3033 } else {
3034 return NULL;
3035 }
3036}
3037
3038static PyObject *
3039load_dh_params(PySSLContext *self, PyObject *filepath)
3040{
3041 BIO *bio;
3042 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003043 PyObject *filepath_bytes = NULL;
3044
3045 if (PyString_Check(filepath)) {
3046 Py_INCREF(filepath);
3047 filepath_bytes = filepath;
3048 } else {
3049 PyObject *u = PyUnicode_FromObject(filepath);
3050 if (!u)
3051 return NULL;
3052 filepath_bytes = PyUnicode_AsEncodedString(
3053 u, Py_FileSystemDefaultEncoding, NULL);
3054 Py_DECREF(u);
3055 if (!filepath_bytes)
3056 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003057 }
3058
Christian Heimes6e8f3952018-02-25 09:48:02 +01003059 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003060 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003061 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003062 ERR_clear_error();
3063 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3064 return NULL;
3065 }
3066 errno = 0;
3067 PySSL_BEGIN_ALLOW_THREADS
3068 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3069 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003070 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003071 PySSL_END_ALLOW_THREADS
3072 if (dh == NULL) {
3073 if (errno != 0) {
3074 ERR_clear_error();
3075 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3076 }
3077 else {
3078 _setSSLError(NULL, 0, __FILE__, __LINE__);
3079 }
3080 return NULL;
3081 }
3082 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3083 _setSSLError(NULL, 0, __FILE__, __LINE__);
3084 DH_free(dh);
3085 Py_RETURN_NONE;
3086}
3087
3088static PyObject *
3089context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3090{
3091 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3092 PySocketSockObject *sock;
3093 int server_side = 0;
3094 char *hostname = NULL;
3095 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3096
3097 /* server_hostname is either None (or absent), or to be encoded
3098 using the idna encoding. */
3099 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3100 PySocketModule.Sock_Type,
3101 &sock, &server_side,
3102 Py_TYPE(Py_None), &hostname_obj,
3103 &ssl_sock)) {
3104 PyErr_Clear();
3105 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3106 PySocketModule.Sock_Type,
3107 &sock, &server_side,
3108 "idna", &hostname, &ssl_sock))
3109 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003110 }
3111
3112 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3113 hostname, ssl_sock);
3114 if (hostname != NULL)
3115 PyMem_Free(hostname);
3116 return res;
3117}
3118
3119static PyObject *
3120session_stats(PySSLContext *self, PyObject *unused)
3121{
3122 int r;
3123 PyObject *value, *stats = PyDict_New();
3124 if (!stats)
3125 return NULL;
3126
3127#define ADD_STATS(SSL_NAME, KEY_NAME) \
3128 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3129 if (value == NULL) \
3130 goto error; \
3131 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3132 Py_DECREF(value); \
3133 if (r < 0) \
3134 goto error;
3135
3136 ADD_STATS(number, "number");
3137 ADD_STATS(connect, "connect");
3138 ADD_STATS(connect_good, "connect_good");
3139 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3140 ADD_STATS(accept, "accept");
3141 ADD_STATS(accept_good, "accept_good");
3142 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3143 ADD_STATS(accept, "accept");
3144 ADD_STATS(hits, "hits");
3145 ADD_STATS(misses, "misses");
3146 ADD_STATS(timeouts, "timeouts");
3147 ADD_STATS(cache_full, "cache_full");
3148
3149#undef ADD_STATS
3150
3151 return stats;
3152
3153error:
3154 Py_DECREF(stats);
3155 return NULL;
3156}
3157
3158static PyObject *
3159set_default_verify_paths(PySSLContext *self, PyObject *unused)
3160{
3161 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3162 _setSSLError(NULL, 0, __FILE__, __LINE__);
3163 return NULL;
3164 }
3165 Py_RETURN_NONE;
3166}
3167
3168#ifndef OPENSSL_NO_ECDH
3169static PyObject *
3170set_ecdh_curve(PySSLContext *self, PyObject *name)
3171{
3172 char *name_bytes;
3173 int nid;
3174 EC_KEY *key;
3175
3176 name_bytes = PyBytes_AsString(name);
3177 if (!name_bytes) {
3178 return NULL;
3179 }
3180 nid = OBJ_sn2nid(name_bytes);
3181 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003182 PyObject *r = PyObject_Repr(name);
3183 if (!r)
3184 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003185 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003186 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3187 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003188 return NULL;
3189 }
3190 key = EC_KEY_new_by_curve_name(nid);
3191 if (key == NULL) {
3192 _setSSLError(NULL, 0, __FILE__, __LINE__);
3193 return NULL;
3194 }
3195 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3196 EC_KEY_free(key);
3197 Py_RETURN_NONE;
3198}
3199#endif
3200
3201#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3202static int
3203_servername_callback(SSL *s, int *al, void *args)
3204{
3205 int ret;
3206 PySSLContext *ssl_ctx = (PySSLContext *) args;
3207 PySSLSocket *ssl;
3208 PyObject *servername_o;
3209 PyObject *servername_idna;
3210 PyObject *result;
3211 /* The high-level ssl.SSLSocket object */
3212 PyObject *ssl_socket;
3213 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3214#ifdef WITH_THREAD
3215 PyGILState_STATE gstate = PyGILState_Ensure();
3216#endif
3217
3218 if (ssl_ctx->set_hostname == NULL) {
3219 /* remove race condition in this the call back while if removing the
3220 * callback is in progress */
3221#ifdef WITH_THREAD
3222 PyGILState_Release(gstate);
3223#endif
3224 return SSL_TLSEXT_ERR_OK;
3225 }
3226
3227 ssl = SSL_get_app_data(s);
3228 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003229 if (ssl->ssl_sock == NULL) {
3230 ssl_socket = Py_None;
3231 } else {
3232 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3233 Py_INCREF(ssl_socket);
3234 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003235 if (ssl_socket == Py_None) {
3236 goto error;
3237 }
3238
3239 if (servername == NULL) {
3240 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3241 Py_None, ssl_ctx, NULL);
3242 }
3243 else {
3244 servername_o = PyBytes_FromString(servername);
3245 if (servername_o == NULL) {
3246 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3247 goto error;
3248 }
3249 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3250 if (servername_idna == NULL) {
3251 PyErr_WriteUnraisable(servername_o);
3252 Py_DECREF(servername_o);
3253 goto error;
3254 }
3255 Py_DECREF(servername_o);
3256 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3257 servername_idna, ssl_ctx, NULL);
3258 Py_DECREF(servername_idna);
3259 }
3260 Py_DECREF(ssl_socket);
3261
3262 if (result == NULL) {
3263 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3264 *al = SSL_AD_HANDSHAKE_FAILURE;
3265 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3266 }
3267 else {
3268 if (result != Py_None) {
3269 *al = (int) PyLong_AsLong(result);
3270 if (PyErr_Occurred()) {
3271 PyErr_WriteUnraisable(result);
3272 *al = SSL_AD_INTERNAL_ERROR;
3273 }
3274 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3275 }
3276 else {
3277 ret = SSL_TLSEXT_ERR_OK;
3278 }
3279 Py_DECREF(result);
3280 }
3281
3282#ifdef WITH_THREAD
3283 PyGILState_Release(gstate);
3284#endif
3285 return ret;
3286
3287error:
3288 Py_DECREF(ssl_socket);
3289 *al = SSL_AD_INTERNAL_ERROR;
3290 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3291#ifdef WITH_THREAD
3292 PyGILState_Release(gstate);
3293#endif
3294 return ret;
3295}
3296#endif
3297
3298PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3299"set_servername_callback(method)\n\
3300\n\
3301This sets a callback that will be called when a server name is provided by\n\
3302the SSL/TLS client in the SNI extension.\n\
3303\n\
3304If the argument is None then the callback is disabled. The method is called\n\
3305with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3306See RFC 6066 for details of the SNI extension.");
3307
3308static PyObject *
3309set_servername_callback(PySSLContext *self, PyObject *args)
3310{
3311#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3312 PyObject *cb;
3313
3314 if (!PyArg_ParseTuple(args, "O", &cb))
3315 return NULL;
3316
3317 Py_CLEAR(self->set_hostname);
3318 if (cb == Py_None) {
3319 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3320 }
3321 else {
3322 if (!PyCallable_Check(cb)) {
3323 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3324 PyErr_SetString(PyExc_TypeError,
3325 "not a callable object");
3326 return NULL;
3327 }
3328 Py_INCREF(cb);
3329 self->set_hostname = cb;
3330 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3331 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3332 }
3333 Py_RETURN_NONE;
3334#else
3335 PyErr_SetString(PyExc_NotImplementedError,
3336 "The TLS extension servername callback, "
3337 "SSL_CTX_set_tlsext_servername_callback, "
3338 "is not in the current OpenSSL library.");
3339 return NULL;
3340#endif
3341}
3342
3343PyDoc_STRVAR(PySSL_get_stats_doc,
3344"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3345\n\
3346Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3347CA extension and certificate revocation lists inside the context's cert\n\
3348store.\n\
3349NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3350been used at least once.");
3351
3352static PyObject *
3353cert_store_stats(PySSLContext *self)
3354{
3355 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003356 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003357 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003358 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003359
3360 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003361 objs = X509_STORE_get0_objects(store);
3362 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3363 obj = sk_X509_OBJECT_value(objs, i);
3364 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003365 case X509_LU_X509:
3366 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003367 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003368 ca++;
3369 }
3370 break;
3371 case X509_LU_CRL:
3372 crl++;
3373 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003374 default:
3375 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3376 * As far as I can tell they are internal states and never
3377 * stored in a cert store */
3378 break;
3379 }
3380 }
3381 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3382 "x509_ca", ca);
3383}
3384
3385PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3386"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3387\n\
3388Returns a list of dicts with information of loaded CA certs. If the\n\
3389optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3390NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3391been used at least once.");
3392
3393static PyObject *
3394get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3395{
3396 char *kwlist[] = {"binary_form", NULL};
3397 X509_STORE *store;
3398 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003399 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003400 int i;
3401 int binary_mode = 0;
3402
3403 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3404 kwlist, &py_binary_mode)) {
3405 return NULL;
3406 }
3407 binary_mode = PyObject_IsTrue(py_binary_mode);
3408 if (binary_mode < 0) {
3409 return NULL;
3410 }
3411
3412 if ((rlist = PyList_New(0)) == NULL) {
3413 return NULL;
3414 }
3415
3416 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003417 objs = X509_STORE_get0_objects(store);
3418 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003419 X509_OBJECT *obj;
3420 X509 *cert;
3421
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003422 obj = sk_X509_OBJECT_value(objs, i);
3423 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003424 /* not a x509 cert */
3425 continue;
3426 }
3427 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003428 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003429 if (!X509_check_ca(cert)) {
3430 continue;
3431 }
3432 if (binary_mode) {
3433 ci = _certificate_to_der(cert);
3434 } else {
3435 ci = _decode_certificate(cert);
3436 }
3437 if (ci == NULL) {
3438 goto error;
3439 }
3440 if (PyList_Append(rlist, ci) == -1) {
3441 goto error;
3442 }
3443 Py_CLEAR(ci);
3444 }
3445 return rlist;
3446
3447 error:
3448 Py_XDECREF(ci);
3449 Py_XDECREF(rlist);
3450 return NULL;
3451}
3452
3453
3454static PyGetSetDef context_getsetlist[] = {
3455 {"check_hostname", (getter) get_check_hostname,
3456 (setter) set_check_hostname, NULL},
3457 {"options", (getter) get_options,
3458 (setter) set_options, NULL},
3459#ifdef HAVE_OPENSSL_VERIFY_PARAM
3460 {"verify_flags", (getter) get_verify_flags,
3461 (setter) set_verify_flags, NULL},
3462#endif
3463 {"verify_mode", (getter) get_verify_mode,
3464 (setter) set_verify_mode, NULL},
3465 {NULL}, /* sentinel */
3466};
3467
3468static struct PyMethodDef context_methods[] = {
3469 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3470 METH_VARARGS | METH_KEYWORDS, NULL},
3471 {"set_ciphers", (PyCFunction) set_ciphers,
3472 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003473 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3474 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003475 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3476 METH_VARARGS, NULL},
3477 {"load_cert_chain", (PyCFunction) load_cert_chain,
3478 METH_VARARGS | METH_KEYWORDS, NULL},
3479 {"load_dh_params", (PyCFunction) load_dh_params,
3480 METH_O, NULL},
3481 {"load_verify_locations", (PyCFunction) load_verify_locations,
3482 METH_VARARGS | METH_KEYWORDS, NULL},
3483 {"session_stats", (PyCFunction) session_stats,
3484 METH_NOARGS, NULL},
3485 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3486 METH_NOARGS, NULL},
3487#ifndef OPENSSL_NO_ECDH
3488 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3489 METH_O, NULL},
3490#endif
3491 {"set_servername_callback", (PyCFunction) set_servername_callback,
3492 METH_VARARGS, PySSL_set_servername_callback_doc},
3493 {"cert_store_stats", (PyCFunction) cert_store_stats,
3494 METH_NOARGS, PySSL_get_stats_doc},
3495 {"get_ca_certs", (PyCFunction) get_ca_certs,
3496 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3497 {NULL, NULL} /* sentinel */
3498};
3499
3500static PyTypeObject PySSLContext_Type = {
3501 PyVarObject_HEAD_INIT(NULL, 0)
3502 "_ssl._SSLContext", /*tp_name*/
3503 sizeof(PySSLContext), /*tp_basicsize*/
3504 0, /*tp_itemsize*/
3505 (destructor)context_dealloc, /*tp_dealloc*/
3506 0, /*tp_print*/
3507 0, /*tp_getattr*/
3508 0, /*tp_setattr*/
3509 0, /*tp_reserved*/
3510 0, /*tp_repr*/
3511 0, /*tp_as_number*/
3512 0, /*tp_as_sequence*/
3513 0, /*tp_as_mapping*/
3514 0, /*tp_hash*/
3515 0, /*tp_call*/
3516 0, /*tp_str*/
3517 0, /*tp_getattro*/
3518 0, /*tp_setattro*/
3519 0, /*tp_as_buffer*/
3520 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3521 0, /*tp_doc*/
3522 (traverseproc) context_traverse, /*tp_traverse*/
3523 (inquiry) context_clear, /*tp_clear*/
3524 0, /*tp_richcompare*/
3525 0, /*tp_weaklistoffset*/
3526 0, /*tp_iter*/
3527 0, /*tp_iternext*/
3528 context_methods, /*tp_methods*/
3529 0, /*tp_members*/
3530 context_getsetlist, /*tp_getset*/
3531 0, /*tp_base*/
3532 0, /*tp_dict*/
3533 0, /*tp_descr_get*/
3534 0, /*tp_descr_set*/
3535 0, /*tp_dictoffset*/
3536 0, /*tp_init*/
3537 0, /*tp_alloc*/
3538 context_new, /*tp_new*/
3539};
3540
3541
3542
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003543#ifdef HAVE_OPENSSL_RAND
3544
3545/* helper routines for seeding the SSL PRNG */
3546static PyObject *
3547PySSL_RAND_add(PyObject *self, PyObject *args)
3548{
3549 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003550 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003551 double entropy;
3552
3553 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003554 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003555 do {
3556 if (len >= INT_MAX) {
3557 written = INT_MAX;
3558 } else {
3559 written = len;
3560 }
3561 RAND_add(buf, (int)written, entropy);
3562 buf += written;
3563 len -= written;
3564 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003565 Py_INCREF(Py_None);
3566 return Py_None;
3567}
3568
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003569PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003570"RAND_add(string, entropy)\n\
3571\n\
3572Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003573bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003574
3575static PyObject *
3576PySSL_RAND_status(PyObject *self)
3577{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003578 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003579}
3580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003581PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003582"RAND_status() -> 0 or 1\n\
3583\n\
3584Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3585It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003587
Victor Stinner7c906672015-01-06 13:53:37 +01003588#endif /* HAVE_OPENSSL_RAND */
3589
3590
Benjamin Peterson42e10292016-07-07 00:02:31 -07003591#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003592
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003593static PyObject *
3594PySSL_RAND_egd(PyObject *self, PyObject *arg)
3595{
3596 int bytes;
3597
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003598 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003599 return PyErr_Format(PyExc_TypeError,
3600 "RAND_egd() expected string, found %s",
3601 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003602 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003603 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003604 PyErr_SetString(PySSLErrorObject,
3605 "EGD connection failed or EGD did not return "
3606 "enough data to seed the PRNG");
3607 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003608 }
3609 return PyInt_FromLong(bytes);
3610}
3611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003612PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003613"RAND_egd(path) -> bytes\n\
3614\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003615Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3616Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003617fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003618
Benjamin Peterson42e10292016-07-07 00:02:31 -07003619#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003620
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003621
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003622PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3623"get_default_verify_paths() -> tuple\n\
3624\n\
3625Return search paths and environment vars that are used by SSLContext's\n\
3626set_default_verify_paths() to load default CAs. The values are\n\
3627'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3628
3629static PyObject *
3630PySSL_get_default_verify_paths(PyObject *self)
3631{
3632 PyObject *ofile_env = NULL;
3633 PyObject *ofile = NULL;
3634 PyObject *odir_env = NULL;
3635 PyObject *odir = NULL;
3636
Benjamin Peterson65192c12015-07-18 10:59:13 -07003637#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003638 const char *tmp = (info); \
3639 target = NULL; \
3640 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3641 else { target = PyBytes_FromString(tmp); } \
3642 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003643 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003644
Benjamin Peterson65192c12015-07-18 10:59:13 -07003645 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3646 CONVERT(X509_get_default_cert_file(), ofile);
3647 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3648 CONVERT(X509_get_default_cert_dir(), odir);
3649#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003650
3651 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3652
3653 error:
3654 Py_XDECREF(ofile_env);
3655 Py_XDECREF(ofile);
3656 Py_XDECREF(odir_env);
3657 Py_XDECREF(odir);
3658 return NULL;
3659}
3660
3661static PyObject*
3662asn1obj2py(ASN1_OBJECT *obj)
3663{
3664 int nid;
3665 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003666
3667 nid = OBJ_obj2nid(obj);
3668 if (nid == NID_undef) {
3669 PyErr_Format(PyExc_ValueError, "Unknown object");
3670 return NULL;
3671 }
3672 sn = OBJ_nid2sn(nid);
3673 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003674 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003675}
3676
3677PyDoc_STRVAR(PySSL_txt2obj_doc,
3678"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3679\n\
3680Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3681objects are looked up by OID. With name=True short and long name are also\n\
3682matched.");
3683
3684static PyObject*
3685PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3686{
3687 char *kwlist[] = {"txt", "name", NULL};
3688 PyObject *result = NULL;
3689 char *txt;
3690 PyObject *pyname = Py_None;
3691 int name = 0;
3692 ASN1_OBJECT *obj;
3693
3694 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3695 kwlist, &txt, &pyname)) {
3696 return NULL;
3697 }
3698 name = PyObject_IsTrue(pyname);
3699 if (name < 0)
3700 return NULL;
3701 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3702 if (obj == NULL) {
3703 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3704 return NULL;
3705 }
3706 result = asn1obj2py(obj);
3707 ASN1_OBJECT_free(obj);
3708 return result;
3709}
3710
3711PyDoc_STRVAR(PySSL_nid2obj_doc,
3712"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3713\n\
3714Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3715
3716static PyObject*
3717PySSL_nid2obj(PyObject *self, PyObject *args)
3718{
3719 PyObject *result = NULL;
3720 int nid;
3721 ASN1_OBJECT *obj;
3722
3723 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3724 return NULL;
3725 }
3726 if (nid < NID_undef) {
3727 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3728 return NULL;
3729 }
3730 obj = OBJ_nid2obj(nid);
3731 if (obj == NULL) {
3732 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3733 return NULL;
3734 }
3735 result = asn1obj2py(obj);
3736 ASN1_OBJECT_free(obj);
3737 return result;
3738}
3739
3740#ifdef _MSC_VER
3741
3742static PyObject*
3743certEncodingType(DWORD encodingType)
3744{
3745 static PyObject *x509_asn = NULL;
3746 static PyObject *pkcs_7_asn = NULL;
3747
3748 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003749 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003750 if (x509_asn == NULL)
3751 return NULL;
3752 }
3753 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003754 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003755 if (pkcs_7_asn == NULL)
3756 return NULL;
3757 }
3758 switch(encodingType) {
3759 case X509_ASN_ENCODING:
3760 Py_INCREF(x509_asn);
3761 return x509_asn;
3762 case PKCS_7_ASN_ENCODING:
3763 Py_INCREF(pkcs_7_asn);
3764 return pkcs_7_asn;
3765 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003766 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003767 }
3768}
3769
3770static PyObject*
3771parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3772{
3773 CERT_ENHKEY_USAGE *usage;
3774 DWORD size, error, i;
3775 PyObject *retval;
3776
3777 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3778 error = GetLastError();
3779 if (error == CRYPT_E_NOT_FOUND) {
3780 Py_RETURN_TRUE;
3781 }
3782 return PyErr_SetFromWindowsErr(error);
3783 }
3784
3785 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3786 if (usage == NULL) {
3787 return PyErr_NoMemory();
3788 }
3789
3790 /* Now get the actual enhanced usage property */
3791 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3792 PyMem_Free(usage);
3793 error = GetLastError();
3794 if (error == CRYPT_E_NOT_FOUND) {
3795 Py_RETURN_TRUE;
3796 }
3797 return PyErr_SetFromWindowsErr(error);
3798 }
3799 retval = PySet_New(NULL);
3800 if (retval == NULL) {
3801 goto error;
3802 }
3803 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3804 if (usage->rgpszUsageIdentifier[i]) {
3805 PyObject *oid;
3806 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003807 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003808 if (oid == NULL) {
3809 Py_CLEAR(retval);
3810 goto error;
3811 }
3812 err = PySet_Add(retval, oid);
3813 Py_DECREF(oid);
3814 if (err == -1) {
3815 Py_CLEAR(retval);
3816 goto error;
3817 }
3818 }
3819 }
3820 error:
3821 PyMem_Free(usage);
3822 return retval;
3823}
3824
3825PyDoc_STRVAR(PySSL_enum_certificates_doc,
3826"enum_certificates(store_name) -> []\n\
3827\n\
3828Retrieve certificates from Windows' cert store. store_name may be one of\n\
3829'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3830The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3831encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3832PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3833boolean True.");
3834
3835static PyObject *
3836PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3837{
3838 char *kwlist[] = {"store_name", NULL};
3839 char *store_name;
3840 HCERTSTORE hStore = NULL;
3841 PCCERT_CONTEXT pCertCtx = NULL;
3842 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3843 PyObject *result = NULL;
3844
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003845 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003846 kwlist, &store_name)) {
3847 return NULL;
3848 }
3849 result = PyList_New(0);
3850 if (result == NULL) {
3851 return NULL;
3852 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003853 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3854 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3855 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003856 if (hStore == NULL) {
3857 Py_DECREF(result);
3858 return PyErr_SetFromWindowsErr(GetLastError());
3859 }
3860
3861 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3862 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3863 pCertCtx->cbCertEncoded);
3864 if (!cert) {
3865 Py_CLEAR(result);
3866 break;
3867 }
3868 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3869 Py_CLEAR(result);
3870 break;
3871 }
3872 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3873 if (keyusage == Py_True) {
3874 Py_DECREF(keyusage);
3875 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3876 }
3877 if (keyusage == NULL) {
3878 Py_CLEAR(result);
3879 break;
3880 }
3881 if ((tup = PyTuple_New(3)) == NULL) {
3882 Py_CLEAR(result);
3883 break;
3884 }
3885 PyTuple_SET_ITEM(tup, 0, cert);
3886 cert = NULL;
3887 PyTuple_SET_ITEM(tup, 1, enc);
3888 enc = NULL;
3889 PyTuple_SET_ITEM(tup, 2, keyusage);
3890 keyusage = NULL;
3891 if (PyList_Append(result, tup) < 0) {
3892 Py_CLEAR(result);
3893 break;
3894 }
3895 Py_CLEAR(tup);
3896 }
3897 if (pCertCtx) {
3898 /* loop ended with an error, need to clean up context manually */
3899 CertFreeCertificateContext(pCertCtx);
3900 }
3901
3902 /* In error cases cert, enc and tup may not be NULL */
3903 Py_XDECREF(cert);
3904 Py_XDECREF(enc);
3905 Py_XDECREF(keyusage);
3906 Py_XDECREF(tup);
3907
3908 if (!CertCloseStore(hStore, 0)) {
3909 /* This error case might shadow another exception.*/
3910 Py_XDECREF(result);
3911 return PyErr_SetFromWindowsErr(GetLastError());
3912 }
3913 return result;
3914}
3915
3916PyDoc_STRVAR(PySSL_enum_crls_doc,
3917"enum_crls(store_name) -> []\n\
3918\n\
3919Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3920'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3921The function returns a list of (bytes, encoding_type) tuples. The\n\
3922encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3923PKCS_7_ASN_ENCODING.");
3924
3925static PyObject *
3926PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3927{
3928 char *kwlist[] = {"store_name", NULL};
3929 char *store_name;
3930 HCERTSTORE hStore = NULL;
3931 PCCRL_CONTEXT pCrlCtx = NULL;
3932 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3933 PyObject *result = NULL;
3934
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003936 kwlist, &store_name)) {
3937 return NULL;
3938 }
3939 result = PyList_New(0);
3940 if (result == NULL) {
3941 return NULL;
3942 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003943 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3944 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3945 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003946 if (hStore == NULL) {
3947 Py_DECREF(result);
3948 return PyErr_SetFromWindowsErr(GetLastError());
3949 }
3950
3951 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3952 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3953 pCrlCtx->cbCrlEncoded);
3954 if (!crl) {
3955 Py_CLEAR(result);
3956 break;
3957 }
3958 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3959 Py_CLEAR(result);
3960 break;
3961 }
3962 if ((tup = PyTuple_New(2)) == NULL) {
3963 Py_CLEAR(result);
3964 break;
3965 }
3966 PyTuple_SET_ITEM(tup, 0, crl);
3967 crl = NULL;
3968 PyTuple_SET_ITEM(tup, 1, enc);
3969 enc = NULL;
3970
3971 if (PyList_Append(result, tup) < 0) {
3972 Py_CLEAR(result);
3973 break;
3974 }
3975 Py_CLEAR(tup);
3976 }
3977 if (pCrlCtx) {
3978 /* loop ended with an error, need to clean up context manually */
3979 CertFreeCRLContext(pCrlCtx);
3980 }
3981
3982 /* In error cases cert, enc and tup may not be NULL */
3983 Py_XDECREF(crl);
3984 Py_XDECREF(enc);
3985 Py_XDECREF(tup);
3986
3987 if (!CertCloseStore(hStore, 0)) {
3988 /* This error case might shadow another exception.*/
3989 Py_XDECREF(result);
3990 return PyErr_SetFromWindowsErr(GetLastError());
3991 }
3992 return result;
3993}
3994
3995#endif /* _MSC_VER */
3996
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003997/* List of functions exported by this module. */
3998
3999static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004000 {"_test_decode_cert", PySSL_test_decode_certificate,
4001 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004002#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004003 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4004 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004005 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4006 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004007#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07004008#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01004009 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
4010 PySSL_RAND_egd_doc},
4011#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004012 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
4013 METH_NOARGS, PySSL_get_default_verify_paths_doc},
4014#ifdef _MSC_VER
4015 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4016 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4017 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4018 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4019#endif
4020 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4021 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4022 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4023 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004024 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004025};
4026
4027
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004028#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004029
4030/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004031 * of the Python C thread library
4032 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4033 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004034
4035static PyThread_type_lock *_ssl_locks = NULL;
4036
Christian Heimes10107812013-08-19 17:36:29 +02004037#if OPENSSL_VERSION_NUMBER >= 0x10000000
4038/* use new CRYPTO_THREADID API. */
4039static void
4040_ssl_threadid_callback(CRYPTO_THREADID *id)
4041{
4042 CRYPTO_THREADID_set_numeric(id,
4043 (unsigned long)PyThread_get_thread_ident());
4044}
4045#else
4046/* deprecated CRYPTO_set_id_callback() API. */
4047static unsigned long
4048_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004049 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004050}
Christian Heimes10107812013-08-19 17:36:29 +02004051#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004052
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004053static void _ssl_thread_locking_function
4054 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004055 /* this function is needed to perform locking on shared data
4056 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004057 structures that will be implicitly shared whenever multiple
4058 threads use OpenSSL.) Multi-threaded applications will
4059 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004060
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004061 locking_function() must be able to handle up to
4062 CRYPTO_num_locks() different mutex locks. It sets the n-th
4063 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004064
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004065 file and line are the file number of the function setting the
4066 lock. They can be useful for debugging.
4067 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004068
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004069 if ((_ssl_locks == NULL) ||
4070 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4071 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004072
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004073 if (mode & CRYPTO_LOCK) {
4074 PyThread_acquire_lock(_ssl_locks[n], 1);
4075 } else {
4076 PyThread_release_lock(_ssl_locks[n]);
4077 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004078}
4079
4080static int _setup_ssl_threads(void) {
4081
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004082 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004083
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004084 if (_ssl_locks == NULL) {
4085 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004086 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4087 if (_ssl_locks == NULL) {
4088 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004089 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004090 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004091 memset(_ssl_locks, 0,
4092 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004093 for (i = 0; i < _ssl_locks_count; i++) {
4094 _ssl_locks[i] = PyThread_allocate_lock();
4095 if (_ssl_locks[i] == NULL) {
4096 unsigned int j;
4097 for (j = 0; j < i; j++) {
4098 PyThread_free_lock(_ssl_locks[j]);
4099 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004100 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004101 return 0;
4102 }
4103 }
4104 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004105#if OPENSSL_VERSION_NUMBER >= 0x10000000
4106 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4107#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004108 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004109#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004110 }
4111 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004112}
4113
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004114#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004116PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004117"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004118for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004119
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004120
4121
4122
4123static void
4124parse_openssl_version(unsigned long libver,
4125 unsigned int *major, unsigned int *minor,
4126 unsigned int *fix, unsigned int *patch,
4127 unsigned int *status)
4128{
4129 *status = libver & 0xF;
4130 libver >>= 4;
4131 *patch = libver & 0xFF;
4132 libver >>= 8;
4133 *fix = libver & 0xFF;
4134 libver >>= 8;
4135 *minor = libver & 0xFF;
4136 libver >>= 8;
4137 *major = libver & 0xFF;
4138}
4139
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004140PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004141init_ssl(void)
4142{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004143 PyObject *m, *d, *r;
4144 unsigned long libver;
4145 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004146 struct py_ssl_error_code *errcode;
4147 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004148
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004149 if (PyType_Ready(&PySSLContext_Type) < 0)
4150 return;
4151 if (PyType_Ready(&PySSLSocket_Type) < 0)
4152 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004153
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004154 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4155 if (m == NULL)
4156 return;
4157 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004158
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004159 /* Load _socket module and its C API */
4160 if (PySocketModule_ImportModuleAndAPI())
4161 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004162
Christian Heimes7daa45d2017-09-05 17:12:12 +02004163#ifndef OPENSSL_VERSION_1_1
4164 /* Load all algorithms and initialize cpuid */
4165 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004166 /* Init OpenSSL */
4167 SSL_load_error_strings();
4168 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004169#endif
4170
Bill Janssen98d19da2007-09-10 21:51:02 +00004171#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004172#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004173 /* note that this will start threading if not already started */
4174 if (!_setup_ssl_threads()) {
4175 return;
4176 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004177#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4178 /* OpenSSL 1.1.0 builtin thread support is enabled */
4179 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004180#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004181#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004182
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004183 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004184 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4185 "ssl.SSLError", SSLError_doc,
4186 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004187 if (PySSLErrorObject == NULL)
4188 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004189 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4190
4191 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4192 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4193 PySSLErrorObject, NULL);
4194 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4195 "ssl.SSLWantReadError", SSLWantReadError_doc,
4196 PySSLErrorObject, NULL);
4197 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4198 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4199 PySSLErrorObject, NULL);
4200 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4201 "ssl.SSLSyscallError", SSLSyscallError_doc,
4202 PySSLErrorObject, NULL);
4203 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4204 "ssl.SSLEOFError", SSLEOFError_doc,
4205 PySSLErrorObject, NULL);
4206 if (PySSLZeroReturnErrorObject == NULL
4207 || PySSLWantReadErrorObject == NULL
4208 || PySSLWantWriteErrorObject == NULL
4209 || PySSLSyscallErrorObject == NULL
4210 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004211 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004212
4213 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4214 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4215 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4216 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4217 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4218
4219 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4220 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4221 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4222 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4223 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4224 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4225 return;
4226 if (PyDict_SetItemString(d, "_SSLContext",
4227 (PyObject *)&PySSLContext_Type) != 0)
4228 return;
4229 if (PyDict_SetItemString(d, "_SSLSocket",
4230 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004231 return;
4232 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4233 PY_SSL_ERROR_ZERO_RETURN);
4234 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4235 PY_SSL_ERROR_WANT_READ);
4236 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4237 PY_SSL_ERROR_WANT_WRITE);
4238 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4239 PY_SSL_ERROR_WANT_X509_LOOKUP);
4240 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4241 PY_SSL_ERROR_SYSCALL);
4242 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4243 PY_SSL_ERROR_SSL);
4244 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4245 PY_SSL_ERROR_WANT_CONNECT);
4246 /* non ssl.h errorcodes */
4247 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4248 PY_SSL_ERROR_EOF);
4249 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4250 PY_SSL_ERROR_INVALID_ERROR_CODE);
4251 /* cert requirements */
4252 PyModule_AddIntConstant(m, "CERT_NONE",
4253 PY_SSL_CERT_NONE);
4254 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4255 PY_SSL_CERT_OPTIONAL);
4256 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4257 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004258 /* CRL verification for verification_flags */
4259 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4260 0);
4261 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4262 X509_V_FLAG_CRL_CHECK);
4263 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4264 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4265 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4266 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004267#ifdef X509_V_FLAG_TRUSTED_FIRST
4268 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4269 X509_V_FLAG_TRUSTED_FIRST);
4270#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004271
4272 /* Alert Descriptions from ssl.h */
4273 /* note RESERVED constants no longer intended for use have been removed */
4274 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4275
4276#define ADD_AD_CONSTANT(s) \
4277 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4278 SSL_AD_##s)
4279
4280 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4281 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4282 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4283 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4284 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4285 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4286 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4287 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4288 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4289 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4290 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4291 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4292 ADD_AD_CONSTANT(UNKNOWN_CA);
4293 ADD_AD_CONSTANT(ACCESS_DENIED);
4294 ADD_AD_CONSTANT(DECODE_ERROR);
4295 ADD_AD_CONSTANT(DECRYPT_ERROR);
4296 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4297 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4298 ADD_AD_CONSTANT(INTERNAL_ERROR);
4299 ADD_AD_CONSTANT(USER_CANCELLED);
4300 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4301 /* Not all constants are in old OpenSSL versions */
4302#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4303 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4304#endif
4305#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4306 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4307#endif
4308#ifdef SSL_AD_UNRECOGNIZED_NAME
4309 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4310#endif
4311#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4312 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4313#endif
4314#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4315 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4316#endif
4317#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4318 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4319#endif
4320
4321#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004322
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004323 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004324#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004325 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4326 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004327#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004328#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004329 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4330 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004331#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004332 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004333 PY_SSL_VERSION_TLS);
4334 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4335 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004336 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4337 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004338#if HAVE_TLSv1_2
4339 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4340 PY_SSL_VERSION_TLS1_1);
4341 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4342 PY_SSL_VERSION_TLS1_2);
4343#endif
4344
4345 /* protocol options */
4346 PyModule_AddIntConstant(m, "OP_ALL",
4347 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4348 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4349 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4350 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4351#if HAVE_TLSv1_2
4352 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4353 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4354#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004355#ifdef SSL_OP_NO_TLSv1_3
4356 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4357#else
4358 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4359#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004360 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4361 SSL_OP_CIPHER_SERVER_PREFERENCE);
4362 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4363#ifdef SSL_OP_SINGLE_ECDH_USE
4364 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4365#endif
4366#ifdef SSL_OP_NO_COMPRESSION
4367 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4368 SSL_OP_NO_COMPRESSION);
4369#endif
4370
4371#if HAVE_SNI
4372 r = Py_True;
4373#else
4374 r = Py_False;
4375#endif
4376 Py_INCREF(r);
4377 PyModule_AddObject(m, "HAS_SNI", r);
4378
4379#if HAVE_OPENSSL_FINISHED
4380 r = Py_True;
4381#else
4382 r = Py_False;
4383#endif
4384 Py_INCREF(r);
4385 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4386
4387#ifdef OPENSSL_NO_ECDH
4388 r = Py_False;
4389#else
4390 r = Py_True;
4391#endif
4392 Py_INCREF(r);
4393 PyModule_AddObject(m, "HAS_ECDH", r);
4394
Christian Heimesdf1732a2018-02-25 14:28:55 +01004395#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004396 r = Py_True;
4397#else
4398 r = Py_False;
4399#endif
4400 Py_INCREF(r);
4401 PyModule_AddObject(m, "HAS_NPN", r);
4402
Christian Heimesdf1732a2018-02-25 14:28:55 +01004403#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004404 r = Py_True;
4405#else
4406 r = Py_False;
4407#endif
4408 Py_INCREF(r);
4409 PyModule_AddObject(m, "HAS_ALPN", r);
4410
Christian Heimesb9a860f2017-09-07 22:31:17 -07004411#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4412 r = Py_True;
4413#else
4414 r = Py_False;
4415#endif
4416 Py_INCREF(r);
4417 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4418
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004419 /* Mappings for error codes */
4420 err_codes_to_names = PyDict_New();
4421 err_names_to_codes = PyDict_New();
4422 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4423 return;
4424 errcode = error_codes;
4425 while (errcode->mnemonic != NULL) {
4426 PyObject *mnemo, *key;
4427 mnemo = PyUnicode_FromString(errcode->mnemonic);
4428 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4429 if (mnemo == NULL || key == NULL)
4430 return;
4431 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4432 return;
4433 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4434 return;
4435 Py_DECREF(key);
4436 Py_DECREF(mnemo);
4437 errcode++;
4438 }
4439 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4440 return;
4441 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4442 return;
4443
4444 lib_codes_to_names = PyDict_New();
4445 if (lib_codes_to_names == NULL)
4446 return;
4447 libcode = library_codes;
4448 while (libcode->library != NULL) {
4449 PyObject *mnemo, *key;
4450 key = PyLong_FromLong(libcode->code);
4451 mnemo = PyUnicode_FromString(libcode->library);
4452 if (key == NULL || mnemo == NULL)
4453 return;
4454 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4455 return;
4456 Py_DECREF(key);
4457 Py_DECREF(mnemo);
4458 libcode++;
4459 }
4460 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4461 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004462
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004463 /* OpenSSL version */
4464 /* SSLeay() gives us the version of the library linked against,
4465 which could be different from the headers version.
4466 */
4467 libver = SSLeay();
4468 r = PyLong_FromUnsignedLong(libver);
4469 if (r == NULL)
4470 return;
4471 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4472 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004473 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004474 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4475 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4476 return;
4477 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4478 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4479 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004480
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004481 libver = OPENSSL_VERSION_NUMBER;
4482 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4483 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4484 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4485 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004486}