blob: f9ed94dee1e17a240c8e31e4aea6e38d5679d25d [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Benjamin Petersondaeb9252014-08-20 14:14:50 -050017#define PY_SSIZE_T_CLEAN
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000018#include "Python.h"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000019
Bill Janssen98d19da2007-09-10 21:51:02 +000020#ifdef WITH_THREAD
21#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020022
Christian Heimes0d604cf2013-08-21 13:26:05 +020023
Benjamin Petersondaeb9252014-08-20 14:14:50 -050024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Bill Janssen98d19da2007-09-10 21:51:02 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000029 PyThreadState *_save = NULL; \
Benjamin Petersondaeb9252014-08-20 14:14:50 -050030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Bill Janssen98d19da2007-09-10 21:51:02 +000034
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000035#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000036
Benjamin Petersondaeb9252014-08-20 14:14:50 -050037#define PySSL_BEGIN_ALLOW_THREADS_S(save)
38#define PySSL_END_ALLOW_THREADS_S(save)
Bill Janssen98d19da2007-09-10 21:51:02 +000039#define PySSL_BEGIN_ALLOW_THREADS
40#define PySSL_BLOCK_THREADS
41#define PySSL_UNBLOCK_THREADS
42#define PySSL_END_ALLOW_THREADS
43
44#endif
45
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000046/* Include symbols from _socket module */
47#include "socketmodule.h"
48
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000049#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000050#include <poll.h>
51#elif defined(HAVE_SYS_POLL_H)
52#include <sys/poll.h>
53#endif
54
Miss Islington (bot)a5c91122018-02-25 01:16:37 -080055#ifndef MS_WINDOWS
56/* inet_pton */
57#include <arpa/inet.h>
58#endif
59
Christian Heimesc2fc7c42016-09-05 23:37:13 +020060/* Don't warn about deprecated functions */
61#ifdef __GNUC__
62#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
63#endif
64#ifdef __clang__
65#pragma clang diagnostic ignored "-Wdeprecated-declarations"
66#endif
67
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000068/* Include OpenSSL header files */
69#include "openssl/rsa.h"
70#include "openssl/crypto.h"
71#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000072#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000073#include "openssl/pem.h"
74#include "openssl/ssl.h"
75#include "openssl/err.h"
76#include "openssl/rand.h"
77
78/* SSL error object */
79static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
100/* Include generated data (error codes) */
101#include "_ssl_data.h"
102
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200103#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
104# define OPENSSL_VERSION_1_1 1
105#endif
106
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500107/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
108 http://www.openssl.org/news/changelog.html
109 */
110#if OPENSSL_VERSION_NUMBER >= 0x10001000L
111# define HAVE_TLSv1_2 1
112#else
113# define HAVE_TLSv1_2 0
114#endif
115
116/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
117 * This includes the SSL_set_SSL_CTX() function.
118 */
119#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
120# define HAVE_SNI 1
121#else
122# define HAVE_SNI 0
123#endif
124
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500125/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500126#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500127# define HAVE_ALPN
128#endif
129
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100130/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
131 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
132 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
133 * OpenSSL 1.0.1+ and LibreSSL.
134 */
135#ifdef OPENSSL_NO_NEXTPROTONEG
136# define HAVE_NPN 0
137#elif defined(TLSEXT_TYPE_next_proto_neg)
138# define HAVE_NPN 1
139#else
140# define HAVE_NPN 0
141# endif
142
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200143#ifndef INVALID_SOCKET /* MS defines this */
144#define INVALID_SOCKET (-1)
145#endif
146
147#ifdef OPENSSL_VERSION_1_1
148/* OpenSSL 1.1.0+ */
149#ifndef OPENSSL_NO_SSL2
150#define OPENSSL_NO_SSL2
151#endif
152#else /* OpenSSL < 1.1.0 */
153#if defined(WITH_THREAD)
154#define HAVE_OPENSSL_CRYPTO_LOCK
155#endif
156
157#define TLS_method SSLv23_method
158
159static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
160{
161 return ne->set;
162}
163
164#ifndef OPENSSL_NO_COMP
165static int COMP_get_type(const COMP_METHOD *meth)
166{
167 return meth->type;
168}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200169#endif
170
171static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
172{
173 return ctx->default_passwd_callback;
174}
175
176static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
177{
178 return ctx->default_passwd_callback_userdata;
179}
180
181static int X509_OBJECT_get_type(X509_OBJECT *x)
182{
183 return x->type;
184}
185
186static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
187{
188 return x->data.x509;
189}
190
191static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
192 return store->objs;
193}
194
195static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
196{
197 return store->param;
198}
199#endif /* OpenSSL < 1.1.0 or LibreSSL */
200
201
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500202enum py_ssl_error {
203 /* these mirror ssl.h */
204 PY_SSL_ERROR_NONE,
205 PY_SSL_ERROR_SSL,
206 PY_SSL_ERROR_WANT_READ,
207 PY_SSL_ERROR_WANT_WRITE,
208 PY_SSL_ERROR_WANT_X509_LOOKUP,
209 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
210 PY_SSL_ERROR_ZERO_RETURN,
211 PY_SSL_ERROR_WANT_CONNECT,
212 /* start of non ssl.h errorcodes */
213 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
214 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
215 PY_SSL_ERROR_INVALID_ERROR_CODE
216};
217
218enum py_ssl_server_or_client {
219 PY_SSL_CLIENT,
220 PY_SSL_SERVER
221};
222
223enum py_ssl_cert_requirements {
224 PY_SSL_CERT_NONE,
225 PY_SSL_CERT_OPTIONAL,
226 PY_SSL_CERT_REQUIRED
227};
228
229enum py_ssl_version {
230 PY_SSL_VERSION_SSL2,
231 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200232 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500233#if HAVE_TLSv1_2
234 PY_SSL_VERSION_TLS1,
235 PY_SSL_VERSION_TLS1_1,
236 PY_SSL_VERSION_TLS1_2
237#else
238 PY_SSL_VERSION_TLS1
239#endif
240};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000241
Bill Janssen98d19da2007-09-10 21:51:02 +0000242#ifdef WITH_THREAD
243
244/* serves as a flag to see whether we've initialized the SSL thread support. */
245/* 0 means no, greater than 0 means yes */
246
247static unsigned int _ssl_locks_count = 0;
248
249#endif /* def WITH_THREAD */
250
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000251/* SSL socket object */
252
253#define X509_NAME_MAXLEN 256
254
255/* RAND_* APIs got added to OpenSSL in 0.9.5 */
256#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
257# define HAVE_OPENSSL_RAND 1
258#else
259# undef HAVE_OPENSSL_RAND
260#endif
261
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500262/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
263 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
264 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
265#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
266# define HAVE_SSL_CTX_CLEAR_OPTIONS
267#else
268# undef HAVE_SSL_CTX_CLEAR_OPTIONS
269#endif
270
271/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
272 * older SSL, but let's be safe */
273#define PySSL_CB_MAXLEN 128
274
275/* SSL_get_finished got added to OpenSSL in 0.9.5 */
276#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
277# define HAVE_OPENSSL_FINISHED 1
278#else
279# define HAVE_OPENSSL_FINISHED 0
280#endif
281
282/* ECDH support got added to OpenSSL in 0.9.8 */
283#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
284# define OPENSSL_NO_ECDH
285#endif
286
287/* compression support got added to OpenSSL in 0.9.8 */
288#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
289# define OPENSSL_NO_COMP
290#endif
291
292/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
293#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
294# define HAVE_OPENSSL_VERIFY_PARAM
295#endif
296
297
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000298typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000299 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500300 SSL_CTX *ctx;
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100301#ifdef HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500302 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500303 int npn_protocols_len;
304#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500305#ifdef HAVE_ALPN
306 unsigned char *alpn_protocols;
307 int alpn_protocols_len;
308#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500309#ifndef OPENSSL_NO_TLSEXT
310 PyObject *set_hostname;
311#endif
312 int check_hostname;
313} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000314
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500315typedef struct {
316 PyObject_HEAD
317 PySocketSockObject *Socket;
318 PyObject *ssl_sock;
319 SSL *ssl;
320 PySSLContext *ctx; /* weakref to SSL context */
321 X509 *peer_cert;
322 char shutdown_seen_zero;
323 char handshake_done;
324 enum py_ssl_server_or_client socket_type;
325} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500327static PyTypeObject PySSLContext_Type;
328static PyTypeObject PySSLSocket_Type;
329
330static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
331static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000332static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000333 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500334static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
335static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000336
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500337#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
338#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000339
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000340typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000341 SOCKET_IS_NONBLOCKING,
342 SOCKET_IS_BLOCKING,
343 SOCKET_HAS_TIMED_OUT,
344 SOCKET_HAS_BEEN_CLOSED,
345 SOCKET_TOO_LARGE_FOR_SELECT,
346 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000347} timeout_state;
348
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000349/* Wrap error strings with filename and line # */
350#define STRINGIFY1(x) #x
351#define STRINGIFY2(x) STRINGIFY1(x)
352#define ERRSTR1(x,y,z) (x ":" y ": " z)
353#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
354
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500355
356/*
357 * SSL errors.
358 */
359
360PyDoc_STRVAR(SSLError_doc,
361"An error occurred in the SSL implementation.");
362
363PyDoc_STRVAR(SSLZeroReturnError_doc,
364"SSL/TLS session closed cleanly.");
365
366PyDoc_STRVAR(SSLWantReadError_doc,
367"Non-blocking SSL socket needs to read more data\n"
368"before the requested operation can be completed.");
369
370PyDoc_STRVAR(SSLWantWriteError_doc,
371"Non-blocking SSL socket needs to write more data\n"
372"before the requested operation can be completed.");
373
374PyDoc_STRVAR(SSLSyscallError_doc,
375"System error when attempting SSL operation.");
376
377PyDoc_STRVAR(SSLEOFError_doc,
378"SSL/TLS connection terminated abruptly.");
379
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380
381static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500382SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500384 if (self->strerror != NULL) {
385 Py_INCREF(self->strerror);
386 return self->strerror;
387 }
388 else
389 return PyObject_Str(self->args);
390}
391
392static void
393fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
394 int lineno, unsigned long errcode)
395{
396 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
397 PyObject *init_value, *msg, *key;
398
399 if (errcode != 0) {
400 int lib, reason;
401
402 lib = ERR_GET_LIB(errcode);
403 reason = ERR_GET_REASON(errcode);
404 key = Py_BuildValue("ii", lib, reason);
405 if (key == NULL)
406 goto fail;
407 reason_obj = PyDict_GetItem(err_codes_to_names, key);
408 Py_DECREF(key);
409 if (reason_obj == NULL) {
410 /* XXX if reason < 100, it might reflect a library number (!!) */
411 PyErr_Clear();
412 }
413 key = PyLong_FromLong(lib);
414 if (key == NULL)
415 goto fail;
416 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
417 Py_DECREF(key);
418 if (lib_obj == NULL) {
419 PyErr_Clear();
420 }
421 if (errstr == NULL)
422 errstr = ERR_reason_error_string(errcode);
423 }
424 if (errstr == NULL)
425 errstr = "unknown error";
426
427 if (reason_obj && lib_obj)
428 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
429 lib_obj, reason_obj, errstr, lineno);
430 else if (lib_obj)
431 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
432 lib_obj, errstr, lineno);
433 else
434 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
435 if (msg == NULL)
436 goto fail;
437
438 init_value = Py_BuildValue("iN", ssl_errno, msg);
439 if (init_value == NULL)
440 goto fail;
441
442 err_value = PyObject_CallObject(type, init_value);
443 Py_DECREF(init_value);
444 if (err_value == NULL)
445 goto fail;
446
447 if (reason_obj == NULL)
448 reason_obj = Py_None;
449 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
450 goto fail;
451 if (lib_obj == NULL)
452 lib_obj = Py_None;
453 if (PyObject_SetAttrString(err_value, "library", lib_obj))
454 goto fail;
455 PyErr_SetObject(type, err_value);
456fail:
457 Py_XDECREF(err_value);
458}
459
460static PyObject *
461PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
462{
463 PyObject *type = PySSLErrorObject;
464 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000465 int err;
466 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500467 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000468
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000469 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500470 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000471
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000472 if (obj->ssl != NULL) {
473 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000474
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000475 switch (err) {
476 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500477 errstr = "TLS/SSL connection has been closed (EOF)";
478 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000479 p = PY_SSL_ERROR_ZERO_RETURN;
480 break;
481 case SSL_ERROR_WANT_READ:
482 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500483 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000484 p = PY_SSL_ERROR_WANT_READ;
485 break;
486 case SSL_ERROR_WANT_WRITE:
487 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500488 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000489 errstr = "The operation did not complete (write)";
490 break;
491 case SSL_ERROR_WANT_X509_LOOKUP:
492 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000493 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000494 break;
495 case SSL_ERROR_WANT_CONNECT:
496 p = PY_SSL_ERROR_WANT_CONNECT;
497 errstr = "The operation did not complete (connect)";
498 break;
499 case SSL_ERROR_SYSCALL:
500 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000501 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500502 PySocketSockObject *s = obj->Socket;
503 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000504 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500505 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000506 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000507 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000508 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500509 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000510 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500511 s->errorhandler();
512 Py_DECREF(s);
513 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000514 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000515 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500516 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000517 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000518 }
519 } else {
520 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000521 }
522 break;
523 }
524 case SSL_ERROR_SSL:
525 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000526 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500527 if (e == 0)
528 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000529 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000530 break;
531 }
532 default:
533 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
534 errstr = "Invalid error code";
535 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000536 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500537 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000538 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000539 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000540}
541
Bill Janssen98d19da2007-09-10 21:51:02 +0000542static PyObject *
543_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
544
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500545 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000546 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500547 else
548 errcode = 0;
549 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000550 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000551 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000552}
553
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500554/*
555 * SSL objects
556 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000557
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500558static PySSLSocket *
559newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
560 enum py_ssl_server_or_client socket_type,
561 char *server_hostname, PyObject *ssl_sock)
562{
563 PySSLSocket *self;
564 SSL_CTX *ctx = sslctx->ctx;
565 long mode;
566
567 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000568 if (self == NULL)
569 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500570
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000571 self->peer_cert = NULL;
572 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000573 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500574 self->ssl_sock = NULL;
575 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200576 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500577 self->handshake_done = 0;
578 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000579
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000580 /* Make sure the SSL error state is initialized */
581 (void) ERR_get_state();
582 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000583
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000584 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500585 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000586 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500587 SSL_set_app_data(self->ssl,self);
588 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
589 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000590#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500591 mode |= SSL_MODE_AUTO_RETRY;
592#endif
593 SSL_set_mode(self->ssl, mode);
594
595#if HAVE_SNI
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800596 if (server_hostname != NULL) {
597/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
598 * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
599 * available on all platforms. Use OpenSSL's IP address parser. It's
600 * available since 1.0.2 and LibreSSL since at least 2.3.0. */
601 int send_sni = 1;
602#if OPENSSL_VERSION_NUMBER >= 0x10200000L
603 ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
604 if (ip == NULL) {
605 send_sni = 1;
606 ERR_clear_error();
607 } else {
608 send_sni = 0;
609 ASN1_OCTET_STRING_free(ip);
610 }
611#elif defined(HAVE_INET_PTON)
612#ifdef ENABLE_IPV6
Christian Heimes439956a2018-02-25 13:08:05 +0100613 #define PySSL_MAX(x, y) (((x) > (y)) ? (x) : (y))
614 char packed[PySSL_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800615#else
616 char packed[sizeof(struct in_addr)];
617#endif /* ENABLE_IPV6 */
618 if (inet_pton(AF_INET, server_hostname, packed)) {
619 send_sni = 0;
620#ifdef ENABLE_IPV6
621 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
622 send_sni = 0;
623#endif /* ENABLE_IPV6 */
624 } else {
625 send_sni = 1;
626 }
627#endif /* HAVE_INET_PTON */
628 if (send_sni) {
629 SSL_set_tlsext_host_name(self->ssl, server_hostname);
630 }
631 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000632#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000633
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000634 /* If the socket is in non-blocking mode or timeout mode, set the BIO
635 * to non-blocking mode (blocking is the default)
636 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500637 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000638 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
639 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
640 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000641
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000642 PySSL_BEGIN_ALLOW_THREADS
643 if (socket_type == PY_SSL_CLIENT)
644 SSL_set_connect_state(self->ssl);
645 else
646 SSL_set_accept_state(self->ssl);
647 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000648
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500649 self->socket_type = socket_type;
650 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000651 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400652 if (ssl_sock != Py_None) {
653 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
654 if (self->ssl_sock == NULL) {
655 Py_DECREF(self);
656 return NULL;
657 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500658 }
659 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000660}
661
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000662
663/* SSL object methods */
664
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500665static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000666{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000667 int ret;
668 int err;
669 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500670 PySocketSockObject *sock = self->Socket;
671
672 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000673
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000674 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500675 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000676 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
677 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000678
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000679 /* Actually negotiate SSL connection */
680 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
681 do {
682 PySSL_BEGIN_ALLOW_THREADS
683 ret = SSL_do_handshake(self->ssl);
684 err = SSL_get_error(self->ssl, ret);
685 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500686 if (PyErr_CheckSignals())
687 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000688 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500689 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000690 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500691 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000692 } else {
693 sockstate = SOCKET_OPERATION_OK;
694 }
695 if (sockstate == SOCKET_HAS_TIMED_OUT) {
696 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000697 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500698 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000699 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
700 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000701 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500702 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000703 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
704 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000705 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500706 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000707 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
708 break;
709 }
710 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500711 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000712 if (ret < 1)
713 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000714
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000715 if (self->peer_cert)
716 X509_free (self->peer_cert);
717 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500718 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000719 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500720 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000721
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000722 Py_INCREF(Py_None);
723 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000724
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500725error:
726 Py_DECREF(sock);
727 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000728}
729
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000730static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200731_asn1obj2py(const ASN1_OBJECT *name, int no_name)
732{
733 char buf[X509_NAME_MAXLEN];
734 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000735 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200736 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000737
Christian Heimesc9d668c2017-09-05 19:13:07 +0200738 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000739 if (buflen < 0) {
740 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200741 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000742 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200743 /* initial buffer is too small for oid + terminating null byte */
744 if (buflen > X509_NAME_MAXLEN - 1) {
745 /* make OBJ_obj2txt() calculate the required buflen */
746 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
747 /* allocate len + 1 for terminating NULL byte */
748 namebuf = PyMem_Malloc(buflen + 1);
749 if (namebuf == NULL) {
750 PyErr_NoMemory();
751 return NULL;
752 }
753 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
754 if (buflen < 0) {
755 _setSSLError(NULL, 0, __FILE__, __LINE__);
756 goto done;
757 }
758 }
759 if (!buflen && no_name) {
760 Py_INCREF(Py_None);
761 name_obj = Py_None;
762 }
763 else {
764 name_obj = PyString_FromStringAndSize(namebuf, buflen);
765 }
766
767 done:
768 if (buf != namebuf) {
769 PyMem_Free(namebuf);
770 }
771 return name_obj;
772}
773
774static PyObject *
775_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
776{
777 Py_ssize_t buflen;
778 unsigned char *valuebuf = NULL;
779 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000780
781 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
782 if (buflen < 0) {
783 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200784 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000785 }
786 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000787 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000788
Christian Heimesc9d668c2017-09-05 19:13:07 +0200789 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
790 OPENSSL_free(valuebuf);
791 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000792}
793
794static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000795_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000796{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000797 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
798 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
799 PyObject *rdnt;
800 PyObject *attr = NULL; /* tuple to hold an attribute */
801 int entry_count = X509_NAME_entry_count(xname);
802 X509_NAME_ENTRY *entry;
803 ASN1_OBJECT *name;
804 ASN1_STRING *value;
805 int index_counter;
806 int rdn_level = -1;
807 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000808
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000809 dn = PyList_New(0);
810 if (dn == NULL)
811 return NULL;
812 /* now create another tuple to hold the top-level RDN */
813 rdn = PyList_New(0);
814 if (rdn == NULL)
815 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000816
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000817 for (index_counter = 0;
818 index_counter < entry_count;
819 index_counter++)
820 {
821 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000822
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000823 /* check to see if we've gotten to a new RDN */
824 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200825 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000826 /* yes, new RDN */
827 /* add old RDN to DN */
828 rdnt = PyList_AsTuple(rdn);
829 Py_DECREF(rdn);
830 if (rdnt == NULL)
831 goto fail0;
832 retcode = PyList_Append(dn, rdnt);
833 Py_DECREF(rdnt);
834 if (retcode < 0)
835 goto fail0;
836 /* create new RDN */
837 rdn = PyList_New(0);
838 if (rdn == NULL)
839 goto fail0;
840 }
841 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200842 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000843
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000844 /* now add this attribute to the current RDN */
845 name = X509_NAME_ENTRY_get_object(entry);
846 value = X509_NAME_ENTRY_get_data(entry);
847 attr = _create_tuple_for_attribute(name, value);
848 /*
849 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
850 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500851 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
852 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000853 */
854 if (attr == NULL)
855 goto fail1;
856 retcode = PyList_Append(rdn, attr);
857 Py_DECREF(attr);
858 if (retcode < 0)
859 goto fail1;
860 }
861 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100862 if (rdn != NULL) {
863 if (PyList_GET_SIZE(rdn) > 0) {
864 rdnt = PyList_AsTuple(rdn);
865 Py_DECREF(rdn);
866 if (rdnt == NULL)
867 goto fail0;
868 retcode = PyList_Append(dn, rdnt);
869 Py_DECREF(rdnt);
870 if (retcode < 0)
871 goto fail0;
872 }
873 else {
874 Py_DECREF(rdn);
875 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000876 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000877
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000878 /* convert list to tuple */
879 rdnt = PyList_AsTuple(dn);
880 Py_DECREF(dn);
881 if (rdnt == NULL)
882 return NULL;
883 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000884
885 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000886 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000887
888 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000889 Py_XDECREF(dn);
890 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000891}
892
893static PyObject *
894_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000895
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000896 /* this code follows the procedure outlined in
897 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
898 function to extract the STACK_OF(GENERAL_NAME),
899 then iterates through the stack to add the
900 names. */
901
902 int i, j;
903 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200904 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000905 X509_EXTENSION *ext = NULL;
906 GENERAL_NAMES *names = NULL;
907 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000908 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000909 BIO *biobuf = NULL;
910 char buf[2048];
911 char *vptr;
912 int len;
913 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000914#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000915 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000916#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000917 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000918#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000919
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000920 if (certificate == NULL)
921 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000922
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000923 /* get a memory buffer */
924 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000925
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200926 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000927 while ((i = X509_get_ext_by_NID(
928 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000929
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000930 if (peer_alt_names == Py_None) {
931 peer_alt_names = PyList_New(0);
932 if (peer_alt_names == NULL)
933 goto fail;
934 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000935
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000936 /* now decode the altName */
937 ext = X509_get_ext(certificate, i);
938 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500939 PyErr_SetString
940 (PySSLErrorObject,
941 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000942 goto fail;
943 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000944
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200945 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000946 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500947 names = (GENERAL_NAMES*)
948 (ASN1_item_d2i(NULL,
949 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200950 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500951 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000952 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500953 names = (GENERAL_NAMES*)
954 (method->d2i(NULL,
955 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200956 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000957
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000958 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000959 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200960 int gntype;
961 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000962
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000963 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200964 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200965 switch (gntype) {
966 case GEN_DIRNAME:
967 /* we special-case DirName as a tuple of
968 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000969
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000970 t = PyTuple_New(2);
971 if (t == NULL) {
972 goto fail;
973 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000974
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000975 v = PyString_FromString("DirName");
976 if (v == NULL) {
977 Py_DECREF(t);
978 goto fail;
979 }
980 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000981
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000982 v = _create_tuple_for_X509_NAME (name->d.dirn);
983 if (v == NULL) {
984 Py_DECREF(t);
985 goto fail;
986 }
987 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200988 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000989
Christian Heimes88b174c2013-08-17 00:54:47 +0200990 case GEN_EMAIL:
991 case GEN_DNS:
992 case GEN_URI:
993 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
994 correctly, CVE-2013-4238 */
995 t = PyTuple_New(2);
996 if (t == NULL)
997 goto fail;
998 switch (gntype) {
999 case GEN_EMAIL:
1000 v = PyString_FromString("email");
1001 as = name->d.rfc822Name;
1002 break;
1003 case GEN_DNS:
1004 v = PyString_FromString("DNS");
1005 as = name->d.dNSName;
1006 break;
1007 case GEN_URI:
1008 v = PyString_FromString("URI");
1009 as = name->d.uniformResourceIdentifier;
1010 break;
1011 }
1012 if (v == NULL) {
1013 Py_DECREF(t);
1014 goto fail;
1015 }
1016 PyTuple_SET_ITEM(t, 0, v);
1017 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1018 ASN1_STRING_length(as));
1019 if (v == NULL) {
1020 Py_DECREF(t);
1021 goto fail;
1022 }
1023 PyTuple_SET_ITEM(t, 1, v);
1024 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001025
Christian Heimes6663eb62016-09-06 23:25:35 +02001026 case GEN_RID:
1027 t = PyTuple_New(2);
1028 if (t == NULL)
1029 goto fail;
1030
1031 v = PyUnicode_FromString("Registered ID");
1032 if (v == NULL) {
1033 Py_DECREF(t);
1034 goto fail;
1035 }
1036 PyTuple_SET_ITEM(t, 0, v);
1037
1038 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1039 if (len < 0) {
1040 Py_DECREF(t);
1041 _setSSLError(NULL, 0, __FILE__, __LINE__);
1042 goto fail;
1043 } else if (len >= (int)sizeof(buf)) {
1044 v = PyUnicode_FromString("<INVALID>");
1045 } else {
1046 v = PyUnicode_FromStringAndSize(buf, len);
1047 }
1048 if (v == NULL) {
1049 Py_DECREF(t);
1050 goto fail;
1051 }
1052 PyTuple_SET_ITEM(t, 1, v);
1053 break;
1054
Christian Heimes88b174c2013-08-17 00:54:47 +02001055 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001056 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001057 switch (gntype) {
1058 /* check for new general name type */
1059 case GEN_OTHERNAME:
1060 case GEN_X400:
1061 case GEN_EDIPARTY:
1062 case GEN_IPADD:
1063 case GEN_RID:
1064 break;
1065 default:
1066 if (PyErr_Warn(PyExc_RuntimeWarning,
1067 "Unknown general name type") == -1) {
1068 goto fail;
1069 }
1070 break;
1071 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001072 (void) BIO_reset(biobuf);
1073 GENERAL_NAME_print(biobuf, name);
1074 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1075 if (len < 0) {
1076 _setSSLError(NULL, 0, __FILE__, __LINE__);
1077 goto fail;
1078 }
1079 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001080 if (vptr == NULL) {
1081 PyErr_Format(PyExc_ValueError,
1082 "Invalid value %.200s",
1083 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001084 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001085 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001086 t = PyTuple_New(2);
1087 if (t == NULL)
1088 goto fail;
1089 v = PyString_FromStringAndSize(buf, (vptr - buf));
1090 if (v == NULL) {
1091 Py_DECREF(t);
1092 goto fail;
1093 }
1094 PyTuple_SET_ITEM(t, 0, v);
1095 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1096 if (v == NULL) {
1097 Py_DECREF(t);
1098 goto fail;
1099 }
1100 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001101 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001102 }
1103
1104 /* and add that rendering to the list */
1105
1106 if (PyList_Append(peer_alt_names, t) < 0) {
1107 Py_DECREF(t);
1108 goto fail;
1109 }
1110 Py_DECREF(t);
1111 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001112 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001113 }
1114 BIO_free(biobuf);
1115 if (peer_alt_names != Py_None) {
1116 v = PyList_AsTuple(peer_alt_names);
1117 Py_DECREF(peer_alt_names);
1118 return v;
1119 } else {
1120 return peer_alt_names;
1121 }
1122
Bill Janssen98d19da2007-09-10 21:51:02 +00001123
1124 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001125 if (biobuf != NULL)
1126 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001127
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001128 if (peer_alt_names != Py_None) {
1129 Py_XDECREF(peer_alt_names);
1130 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001131
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001132 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001133}
1134
1135static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001136_get_aia_uri(X509 *certificate, int nid) {
1137 PyObject *lst = NULL, *ostr = NULL;
1138 int i, result;
1139 AUTHORITY_INFO_ACCESS *info;
1140
1141 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001142 if (info == NULL)
1143 return Py_None;
1144 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1145 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001146 return Py_None;
1147 }
1148
1149 if ((lst = PyList_New(0)) == NULL) {
1150 goto fail;
1151 }
1152
1153 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1154 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1155 ASN1_IA5STRING *uri;
1156
1157 if ((OBJ_obj2nid(ad->method) != nid) ||
1158 (ad->location->type != GEN_URI)) {
1159 continue;
1160 }
1161 uri = ad->location->d.uniformResourceIdentifier;
1162 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1163 uri->length);
1164 if (ostr == NULL) {
1165 goto fail;
1166 }
1167 result = PyList_Append(lst, ostr);
1168 Py_DECREF(ostr);
1169 if (result < 0) {
1170 goto fail;
1171 }
1172 }
1173 AUTHORITY_INFO_ACCESS_free(info);
1174
1175 /* convert to tuple or None */
1176 if (PyList_Size(lst) == 0) {
1177 Py_DECREF(lst);
1178 return Py_None;
1179 } else {
1180 PyObject *tup;
1181 tup = PyList_AsTuple(lst);
1182 Py_DECREF(lst);
1183 return tup;
1184 }
1185
1186 fail:
1187 AUTHORITY_INFO_ACCESS_free(info);
1188 Py_XDECREF(lst);
1189 return NULL;
1190}
1191
1192static PyObject *
1193_get_crl_dp(X509 *certificate) {
1194 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001195 int i, j;
1196 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001197
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001198 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001199
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001200 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001201 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001202
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001203 lst = PyList_New(0);
1204 if (lst == NULL)
1205 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001206
1207 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1208 DIST_POINT *dp;
1209 STACK_OF(GENERAL_NAME) *gns;
1210
1211 dp = sk_DIST_POINT_value(dps, i);
1212 gns = dp->distpoint->name.fullname;
1213
1214 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1215 GENERAL_NAME *gn;
1216 ASN1_IA5STRING *uri;
1217 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001218 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001219
1220 gn = sk_GENERAL_NAME_value(gns, j);
1221 if (gn->type != GEN_URI) {
1222 continue;
1223 }
1224 uri = gn->d.uniformResourceIdentifier;
1225 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1226 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001227 if (ouri == NULL)
1228 goto done;
1229
1230 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001231 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001232 if (err < 0)
1233 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001234 }
1235 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001236
1237 /* Convert to tuple. */
1238 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1239
1240 done:
1241 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001242 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001243 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001244}
1245
1246static PyObject *
1247_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001248
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001249 PyObject *retval = NULL;
1250 BIO *biobuf = NULL;
1251 PyObject *peer;
1252 PyObject *peer_alt_names = NULL;
1253 PyObject *issuer;
1254 PyObject *version;
1255 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001256 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001257 ASN1_INTEGER *serialNumber;
1258 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001259 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001260 ASN1_TIME *notBefore, *notAfter;
1261 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001262
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001263 retval = PyDict_New();
1264 if (retval == NULL)
1265 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001266
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001267 peer = _create_tuple_for_X509_NAME(
1268 X509_get_subject_name(certificate));
1269 if (peer == NULL)
1270 goto fail0;
1271 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1272 Py_DECREF(peer);
1273 goto fail0;
1274 }
1275 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001276
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001277 issuer = _create_tuple_for_X509_NAME(
1278 X509_get_issuer_name(certificate));
1279 if (issuer == NULL)
1280 goto fail0;
1281 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001282 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001283 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001284 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001285 Py_DECREF(issuer);
1286
1287 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1288 if (version == NULL)
1289 goto fail0;
1290 if (PyDict_SetItemString(retval, "version", version) < 0) {
1291 Py_DECREF(version);
1292 goto fail0;
1293 }
1294 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001295
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001296 /* get a memory buffer */
1297 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001298
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001299 (void) BIO_reset(biobuf);
1300 serialNumber = X509_get_serialNumber(certificate);
1301 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1302 i2a_ASN1_INTEGER(biobuf, serialNumber);
1303 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1304 if (len < 0) {
1305 _setSSLError(NULL, 0, __FILE__, __LINE__);
1306 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001307 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001308 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1309 if (sn_obj == NULL)
1310 goto fail1;
1311 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1312 Py_DECREF(sn_obj);
1313 goto fail1;
1314 }
1315 Py_DECREF(sn_obj);
1316
1317 (void) BIO_reset(biobuf);
1318 notBefore = X509_get_notBefore(certificate);
1319 ASN1_TIME_print(biobuf, notBefore);
1320 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1321 if (len < 0) {
1322 _setSSLError(NULL, 0, __FILE__, __LINE__);
1323 goto fail1;
1324 }
1325 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1326 if (pnotBefore == NULL)
1327 goto fail1;
1328 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1329 Py_DECREF(pnotBefore);
1330 goto fail1;
1331 }
1332 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001333
1334 (void) BIO_reset(biobuf);
1335 notAfter = X509_get_notAfter(certificate);
1336 ASN1_TIME_print(biobuf, notAfter);
1337 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1338 if (len < 0) {
1339 _setSSLError(NULL, 0, __FILE__, __LINE__);
1340 goto fail1;
1341 }
1342 pnotAfter = PyString_FromStringAndSize(buf, len);
1343 if (pnotAfter == NULL)
1344 goto fail1;
1345 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1346 Py_DECREF(pnotAfter);
1347 goto fail1;
1348 }
1349 Py_DECREF(pnotAfter);
1350
1351 /* Now look for subjectAltName */
1352
1353 peer_alt_names = _get_peer_alt_names(certificate);
1354 if (peer_alt_names == NULL)
1355 goto fail1;
1356 else if (peer_alt_names != Py_None) {
1357 if (PyDict_SetItemString(retval, "subjectAltName",
1358 peer_alt_names) < 0) {
1359 Py_DECREF(peer_alt_names);
1360 goto fail1;
1361 }
1362 Py_DECREF(peer_alt_names);
1363 }
1364
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001365 /* Authority Information Access: OCSP URIs */
1366 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1367 if (obj == NULL) {
1368 goto fail1;
1369 } else if (obj != Py_None) {
1370 result = PyDict_SetItemString(retval, "OCSP", obj);
1371 Py_DECREF(obj);
1372 if (result < 0) {
1373 goto fail1;
1374 }
1375 }
1376
1377 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1378 if (obj == NULL) {
1379 goto fail1;
1380 } else if (obj != Py_None) {
1381 result = PyDict_SetItemString(retval, "caIssuers", obj);
1382 Py_DECREF(obj);
1383 if (result < 0) {
1384 goto fail1;
1385 }
1386 }
1387
1388 /* CDP (CRL distribution points) */
1389 obj = _get_crl_dp(certificate);
1390 if (obj == NULL) {
1391 goto fail1;
1392 } else if (obj != Py_None) {
1393 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1394 Py_DECREF(obj);
1395 if (result < 0) {
1396 goto fail1;
1397 }
1398 }
1399
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001400 BIO_free(biobuf);
1401 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001402
1403 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001404 if (biobuf != NULL)
1405 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001406 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001407 Py_XDECREF(retval);
1408 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001409}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001410
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001411static PyObject *
1412_certificate_to_der(X509 *certificate)
1413{
1414 unsigned char *bytes_buf = NULL;
1415 int len;
1416 PyObject *retval;
1417
1418 bytes_buf = NULL;
1419 len = i2d_X509(certificate, &bytes_buf);
1420 if (len < 0) {
1421 _setSSLError(NULL, 0, __FILE__, __LINE__);
1422 return NULL;
1423 }
1424 /* this is actually an immutable bytes sequence */
1425 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1426 OPENSSL_free(bytes_buf);
1427 return retval;
1428}
Bill Janssen98d19da2007-09-10 21:51:02 +00001429
1430static PyObject *
1431PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1432
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001433 PyObject *retval = NULL;
1434 char *filename = NULL;
1435 X509 *x=NULL;
1436 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001437
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001438 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001439 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001440
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001441 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001442 PyErr_SetString(PySSLErrorObject,
1443 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001444 goto fail0;
1445 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001446
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001447 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001448 PyErr_SetString(PySSLErrorObject,
1449 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001450 goto fail0;
1451 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001452
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001453 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1454 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001455 PyErr_SetString(PySSLErrorObject,
1456 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001457 goto fail0;
1458 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001459
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001460 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001461 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001462
1463 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001464
1465 if (cert != NULL) BIO_free(cert);
1466 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001467}
1468
1469
1470static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001471PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001472{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001473 int verification;
1474 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001475 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001476
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001477 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1478 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001479
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001480 if (!self->handshake_done) {
1481 PyErr_SetString(PyExc_ValueError,
1482 "handshake not done yet");
1483 return NULL;
1484 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001485 if (!self->peer_cert)
1486 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001487
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001488 b = PyObject_IsTrue(binary_mode);
1489 if (b < 0)
1490 return NULL;
1491 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001492 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001493 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001494 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001495 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001496 if ((verification & SSL_VERIFY_PEER) == 0)
1497 return PyDict_New();
1498 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001499 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001500 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001501}
1502
1503PyDoc_STRVAR(PySSL_peercert_doc,
1504"peer_certificate([der=False]) -> certificate\n\
1505\n\
1506Returns the certificate for the peer. If no certificate was provided,\n\
1507returns None. If a certificate was provided, but not validated, returns\n\
1508an empty dictionary. Otherwise returns a dict containing information\n\
1509about the peer certificate.\n\
1510\n\
1511If the optional argument is True, returns a DER-encoded copy of the\n\
1512peer certificate, or None if no certificate was provided. This will\n\
1513return the certificate even if it wasn't validated.");
1514
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001515static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001516
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001517 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001518 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001519 char *cipher_name;
1520 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001521
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001522 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001523 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001524 current = SSL_get_current_cipher(self->ssl);
1525 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001526 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001527
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001528 retval = PyTuple_New(3);
1529 if (retval == NULL)
1530 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001531
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001532 cipher_name = (char *) SSL_CIPHER_get_name(current);
1533 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001534 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001535 PyTuple_SET_ITEM(retval, 0, Py_None);
1536 } else {
1537 v = PyString_FromString(cipher_name);
1538 if (v == NULL)
1539 goto fail0;
1540 PyTuple_SET_ITEM(retval, 0, v);
1541 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001542 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001543 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001544 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001545 PyTuple_SET_ITEM(retval, 1, Py_None);
1546 } else {
1547 v = PyString_FromString(cipher_protocol);
1548 if (v == NULL)
1549 goto fail0;
1550 PyTuple_SET_ITEM(retval, 1, v);
1551 }
1552 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1553 if (v == NULL)
1554 goto fail0;
1555 PyTuple_SET_ITEM(retval, 2, v);
1556 return retval;
1557
Bill Janssen98d19da2007-09-10 21:51:02 +00001558 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001559 Py_DECREF(retval);
1560 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001561}
1562
Alex Gaynore98205d2014-09-04 13:33:22 -07001563static PyObject *PySSL_version(PySSLSocket *self)
1564{
1565 const char *version;
1566
1567 if (self->ssl == NULL)
1568 Py_RETURN_NONE;
1569 version = SSL_get_version(self->ssl);
1570 if (!strcmp(version, "unknown"))
1571 Py_RETURN_NONE;
1572 return PyUnicode_FromString(version);
1573}
1574
Christian Heimes72ed2332017-09-05 01:11:40 +02001575#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001576static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1577 const unsigned char *out;
1578 unsigned int outlen;
1579
1580 SSL_get0_next_proto_negotiated(self->ssl,
1581 &out, &outlen);
1582
1583 if (out == NULL)
1584 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001585 return PyString_FromStringAndSize((char *)out, outlen);
1586}
1587#endif
1588
1589#ifdef HAVE_ALPN
1590static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1591 const unsigned char *out;
1592 unsigned int outlen;
1593
1594 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1595
1596 if (out == NULL)
1597 Py_RETURN_NONE;
1598 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001599}
1600#endif
1601
1602static PyObject *PySSL_compression(PySSLSocket *self) {
1603#ifdef OPENSSL_NO_COMP
1604 Py_RETURN_NONE;
1605#else
1606 const COMP_METHOD *comp_method;
1607 const char *short_name;
1608
1609 if (self->ssl == NULL)
1610 Py_RETURN_NONE;
1611 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001612 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001613 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001614 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001615 if (short_name == NULL)
1616 Py_RETURN_NONE;
1617 return PyBytes_FromString(short_name);
1618#endif
1619}
1620
1621static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1622 Py_INCREF(self->ctx);
1623 return self->ctx;
1624}
1625
1626static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1627 void *closure) {
1628
1629 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1630#if !HAVE_SNI
1631 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1632 "context is not supported by your OpenSSL library");
1633 return -1;
1634#else
1635 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001636 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001637 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1638#endif
1639 } else {
1640 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1641 return -1;
1642 }
1643
1644 return 0;
1645}
1646
1647PyDoc_STRVAR(PySSL_set_context_doc,
1648"_setter_context(ctx)\n\
1649\
1650This changes the context associated with the SSLSocket. This is typically\n\
1651used from within a callback function set by the set_servername_callback\n\
1652on the SSLContext to change the certificate information associated with the\n\
1653SSLSocket before the cryptographic exchange handshake messages\n");
1654
1655
1656
1657static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001658{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001659 if (self->peer_cert) /* Possible not to have one? */
1660 X509_free (self->peer_cert);
1661 if (self->ssl)
1662 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001663 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001664 Py_XDECREF(self->ssl_sock);
1665 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001666 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001667}
1668
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001669/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001670 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001671 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001672 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001673
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001674static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001675check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001677 fd_set fds;
1678 struct timeval tv;
1679 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001680
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001681 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1682 if (s->sock_timeout < 0.0)
1683 return SOCKET_IS_BLOCKING;
1684 else if (s->sock_timeout == 0.0)
1685 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001686
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001687 /* Guard against closed socket */
1688 if (s->sock_fd < 0)
1689 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001690
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001691 /* Prefer poll, if available, since you can poll() any fd
1692 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001693#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001694 {
1695 struct pollfd pollfd;
1696 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001697
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001698 pollfd.fd = s->sock_fd;
1699 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001700
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001701 /* s->sock_timeout is in seconds, timeout in ms */
1702 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1703 PySSL_BEGIN_ALLOW_THREADS
1704 rc = poll(&pollfd, 1, timeout);
1705 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001706
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001707 goto normal_return;
1708 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001709#endif
1710
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001711 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001712 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001713 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001714
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001715 /* Construct the arguments to select */
1716 tv.tv_sec = (int)s->sock_timeout;
1717 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1718 FD_ZERO(&fds);
1719 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001720
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001721 /* See if the socket is ready */
1722 PySSL_BEGIN_ALLOW_THREADS
1723 if (writing)
1724 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1725 else
1726 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1727 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001728
Bill Janssen934b16d2008-06-28 22:19:33 +00001729#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001730normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001731#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001732 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1733 (when we are able to write or when there's something to read) */
1734 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001735}
1736
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001737static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001738{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001739 Py_buffer buf;
1740 int len;
1741 int sockstate;
1742 int err;
1743 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001744 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001745
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001746 Py_INCREF(sock);
1747
1748 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1749 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001750 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001751 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001752
Victor Stinnerc1a44262013-06-25 00:48:02 +02001753 if (buf.len > INT_MAX) {
1754 PyErr_Format(PyExc_OverflowError,
1755 "string longer than %d bytes", INT_MAX);
1756 goto error;
1757 }
1758
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001759 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001760 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001761 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1762 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001763
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001764 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001765 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1766 PyErr_SetString(PySSLErrorObject,
1767 "The write operation timed out");
1768 goto error;
1769 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1770 PyErr_SetString(PySSLErrorObject,
1771 "Underlying socket has been closed.");
1772 goto error;
1773 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1774 PyErr_SetString(PySSLErrorObject,
1775 "Underlying socket too large for select().");
1776 goto error;
1777 }
1778 do {
1779 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001780 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001781 err = SSL_get_error(self->ssl, len);
1782 PySSL_END_ALLOW_THREADS
1783 if (PyErr_CheckSignals()) {
1784 goto error;
1785 }
1786 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001787 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001788 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001789 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001790 } else {
1791 sockstate = SOCKET_OPERATION_OK;
1792 }
1793 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1794 PyErr_SetString(PySSLErrorObject,
1795 "The write operation timed out");
1796 goto error;
1797 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1798 PyErr_SetString(PySSLErrorObject,
1799 "Underlying socket has been closed.");
1800 goto error;
1801 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1802 break;
1803 }
1804 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001805
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001806 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001807 PyBuffer_Release(&buf);
1808 if (len > 0)
1809 return PyInt_FromLong(len);
1810 else
1811 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001812
1813error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001814 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001815 PyBuffer_Release(&buf);
1816 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001817}
1818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001819PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001820"write(s) -> len\n\
1821\n\
1822Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001823of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001824
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001825static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001826{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001827 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001828
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001829 PySSL_BEGIN_ALLOW_THREADS
1830 count = SSL_pending(self->ssl);
1831 PySSL_END_ALLOW_THREADS
1832 if (count < 0)
1833 return PySSL_SetError(self, count, __FILE__, __LINE__);
1834 else
1835 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001836}
1837
1838PyDoc_STRVAR(PySSL_SSLpending_doc,
1839"pending() -> count\n\
1840\n\
1841Returns the number of already decrypted bytes available for read,\n\
1842pending on the connection.\n");
1843
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001845{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001846 PyObject *dest = NULL;
1847 Py_buffer buf;
1848 char *mem;
1849 int len, count;
1850 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001851 int sockstate;
1852 int err;
1853 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001854 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001855
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001856 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001857
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858 buf.obj = NULL;
1859 buf.buf = NULL;
1860 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1861 goto error;
1862
1863 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001864 if (len < 0) {
1865 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1866 goto error;
1867 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001868 dest = PyBytes_FromStringAndSize(NULL, len);
1869 if (dest == NULL)
1870 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001871 if (len == 0) {
1872 Py_XDECREF(sock);
1873 return dest;
1874 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001875 mem = PyBytes_AS_STRING(dest);
1876 }
1877 else {
1878 buf_passed = 1;
1879 mem = buf.buf;
1880 if (len <= 0 || len > buf.len) {
1881 len = (int) buf.len;
1882 if (buf.len != len) {
1883 PyErr_SetString(PyExc_OverflowError,
1884 "maximum length can't fit in a C 'int'");
1885 goto error;
1886 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001887 if (len == 0) {
1888 count = 0;
1889 goto done;
1890 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001891 }
1892 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001893
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001894 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001895 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001896 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1897 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001898
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001899 do {
1900 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001901 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001902 err = SSL_get_error(self->ssl, count);
1903 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001904 if (PyErr_CheckSignals())
1905 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001906 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001907 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001908 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001909 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001910 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1911 (SSL_get_shutdown(self->ssl) ==
1912 SSL_RECEIVED_SHUTDOWN))
1913 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001914 count = 0;
1915 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001916 } else {
1917 sockstate = SOCKET_OPERATION_OK;
1918 }
1919 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1920 PyErr_SetString(PySSLErrorObject,
1921 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001922 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001923 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1924 break;
1925 }
1926 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1927 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001928 PySSL_SetError(self, count, __FILE__, __LINE__);
1929 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001930 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001931
1932done:
1933 Py_DECREF(sock);
1934 if (!buf_passed) {
1935 _PyBytes_Resize(&dest, count);
1936 return dest;
1937 }
1938 else {
1939 PyBuffer_Release(&buf);
1940 return PyLong_FromLong(count);
1941 }
1942
1943error:
1944 Py_DECREF(sock);
1945 if (!buf_passed)
1946 Py_XDECREF(dest);
1947 else
1948 PyBuffer_Release(&buf);
1949 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001950}
1951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001952PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001953"read([len]) -> string\n\
1954\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001955Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001956
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001957static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001958{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001959 int err, ssl_err, sockstate, nonblocking;
1960 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001961 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001962
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001963 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001964 if (sock->sock_fd < 0) {
1965 _setSSLError("Underlying socket connection gone",
1966 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001967 return NULL;
1968 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001969 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001970
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001971 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001972 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001973 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1974 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001975
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001976 while (1) {
1977 PySSL_BEGIN_ALLOW_THREADS
1978 /* Disable read-ahead so that unwrap can work correctly.
1979 * Otherwise OpenSSL might read in too much data,
1980 * eating clear text data that happens to be
1981 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001982 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001983 * function is used and the shutdown_seen_zero != 0
1984 * condition is met.
1985 */
1986 if (self->shutdown_seen_zero)
1987 SSL_set_read_ahead(self->ssl, 0);
1988 err = SSL_shutdown(self->ssl);
1989 PySSL_END_ALLOW_THREADS
1990 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1991 if (err > 0)
1992 break;
1993 if (err == 0) {
1994 /* Don't loop endlessly; instead preserve legacy
1995 behaviour of trying SSL_shutdown() only twice.
1996 This looks necessary for OpenSSL < 0.9.8m */
1997 if (++zeros > 1)
1998 break;
1999 /* Shutdown was sent, now try receiving */
2000 self->shutdown_seen_zero = 1;
2001 continue;
2002 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00002003
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002004 /* Possibly retry shutdown until timeout or failure */
2005 ssl_err = SSL_get_error(self->ssl, err);
2006 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002007 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002008 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002009 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002010 else
2011 break;
2012 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2013 if (ssl_err == SSL_ERROR_WANT_READ)
2014 PyErr_SetString(PySSLErrorObject,
2015 "The read operation timed out");
2016 else
2017 PyErr_SetString(PySSLErrorObject,
2018 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002019 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002020 }
2021 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2022 PyErr_SetString(PySSLErrorObject,
2023 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002024 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002025 }
2026 else if (sockstate != SOCKET_OPERATION_OK)
2027 /* Retain the SSL error code */
2028 break;
2029 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002030
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002031 if (err < 0) {
2032 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002033 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002034 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002035 else
2036 /* It's already INCREF'ed */
2037 return (PyObject *) sock;
2038
2039error:
2040 Py_DECREF(sock);
2041 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002042}
2043
2044PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2045"shutdown(s) -> socket\n\
2046\n\
2047Does the SSL shutdown handshake with the remote end, and returns\n\
2048the underlying socket object.");
2049
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002050#if HAVE_OPENSSL_FINISHED
2051static PyObject *
2052PySSL_tls_unique_cb(PySSLSocket *self)
2053{
2054 PyObject *retval = NULL;
2055 char buf[PySSL_CB_MAXLEN];
2056 size_t len;
2057
2058 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2059 /* if session is resumed XOR we are the client */
2060 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2061 }
2062 else {
2063 /* if a new session XOR we are the server */
2064 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2065 }
2066
2067 /* It cannot be negative in current OpenSSL version as of July 2011 */
2068 if (len == 0)
2069 Py_RETURN_NONE;
2070
2071 retval = PyBytes_FromStringAndSize(buf, len);
2072
2073 return retval;
2074}
2075
2076PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2077"tls_unique_cb() -> bytes\n\
2078\n\
2079Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2080\n\
2081If the TLS handshake is not yet complete, None is returned");
2082
2083#endif /* HAVE_OPENSSL_FINISHED */
2084
2085static PyGetSetDef ssl_getsetlist[] = {
2086 {"context", (getter) PySSL_get_context,
2087 (setter) PySSL_set_context, PySSL_set_context_doc},
2088 {NULL}, /* sentinel */
2089};
2090
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002091static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002092 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2093 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2094 PySSL_SSLwrite_doc},
2095 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2096 PySSL_SSLread_doc},
2097 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2098 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002099 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2100 PySSL_peercert_doc},
2101 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002102 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002103#ifdef OPENSSL_NPN_NEGOTIATED
2104 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2105#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002106#ifdef HAVE_ALPN
2107 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2108#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002109 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002110 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2111 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002112#if HAVE_OPENSSL_FINISHED
2113 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2114 PySSL_tls_unique_cb_doc},
2115#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002116 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002117};
2118
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002119static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002120 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002121 "_ssl._SSLSocket", /*tp_name*/
2122 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002123 0, /*tp_itemsize*/
2124 /* methods */
2125 (destructor)PySSL_dealloc, /*tp_dealloc*/
2126 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002127 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002128 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002129 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002130 0, /*tp_repr*/
2131 0, /*tp_as_number*/
2132 0, /*tp_as_sequence*/
2133 0, /*tp_as_mapping*/
2134 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002135 0, /*tp_call*/
2136 0, /*tp_str*/
2137 0, /*tp_getattro*/
2138 0, /*tp_setattro*/
2139 0, /*tp_as_buffer*/
2140 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2141 0, /*tp_doc*/
2142 0, /*tp_traverse*/
2143 0, /*tp_clear*/
2144 0, /*tp_richcompare*/
2145 0, /*tp_weaklistoffset*/
2146 0, /*tp_iter*/
2147 0, /*tp_iternext*/
2148 PySSLMethods, /*tp_methods*/
2149 0, /*tp_members*/
2150 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002151};
2152
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002153
2154/*
2155 * _SSLContext objects
2156 */
2157
2158static PyObject *
2159context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2160{
2161 char *kwlist[] = {"protocol", NULL};
2162 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002163 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002164 long options;
2165 SSL_CTX *ctx = NULL;
2166
2167 if (!PyArg_ParseTupleAndKeywords(
2168 args, kwds, "i:_SSLContext", kwlist,
2169 &proto_version))
2170 return NULL;
2171
2172 PySSL_BEGIN_ALLOW_THREADS
2173 if (proto_version == PY_SSL_VERSION_TLS1)
2174 ctx = SSL_CTX_new(TLSv1_method());
2175#if HAVE_TLSv1_2
2176 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2177 ctx = SSL_CTX_new(TLSv1_1_method());
2178 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2179 ctx = SSL_CTX_new(TLSv1_2_method());
2180#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002181#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002182 else if (proto_version == PY_SSL_VERSION_SSL3)
2183 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002184#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002185#ifndef OPENSSL_NO_SSL2
2186 else if (proto_version == PY_SSL_VERSION_SSL2)
2187 ctx = SSL_CTX_new(SSLv2_method());
2188#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002189 else if (proto_version == PY_SSL_VERSION_TLS)
2190 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002191 else
2192 proto_version = -1;
2193 PySSL_END_ALLOW_THREADS
2194
2195 if (proto_version == -1) {
2196 PyErr_SetString(PyExc_ValueError,
2197 "invalid protocol version");
2198 return NULL;
2199 }
2200 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002201 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002202 return NULL;
2203 }
2204
2205 assert(type != NULL && type->tp_alloc != NULL);
2206 self = (PySSLContext *) type->tp_alloc(type, 0);
2207 if (self == NULL) {
2208 SSL_CTX_free(ctx);
2209 return NULL;
2210 }
2211 self->ctx = ctx;
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002212#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002213 self->npn_protocols = NULL;
2214#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002215#ifdef HAVE_ALPN
2216 self->alpn_protocols = NULL;
2217#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002218#ifndef OPENSSL_NO_TLSEXT
2219 self->set_hostname = NULL;
2220#endif
2221 /* Don't check host name by default */
2222 self->check_hostname = 0;
2223 /* Defaults */
2224 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2225 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2226 if (proto_version != PY_SSL_VERSION_SSL2)
2227 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002228 if (proto_version != PY_SSL_VERSION_SSL3)
2229 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002230 SSL_CTX_set_options(self->ctx, options);
2231
Donald Stufftf1a696e2017-03-02 12:37:07 -05002232#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002233 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2234 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002235 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2236 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002237#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002238 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2239#else
2240 {
2241 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2242 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2243 EC_KEY_free(key);
2244 }
2245#endif
2246#endif
2247
2248#define SID_CTX "Python"
2249 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2250 sizeof(SID_CTX));
2251#undef SID_CTX
2252
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002253#ifdef X509_V_FLAG_TRUSTED_FIRST
2254 {
2255 /* Improve trust chain building when cross-signed intermediate
2256 certificates are present. See https://bugs.python.org/issue23476. */
2257 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2258 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2259 }
2260#endif
2261
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002262 return (PyObject *)self;
2263}
2264
2265static int
2266context_traverse(PySSLContext *self, visitproc visit, void *arg)
2267{
2268#ifndef OPENSSL_NO_TLSEXT
2269 Py_VISIT(self->set_hostname);
2270#endif
2271 return 0;
2272}
2273
2274static int
2275context_clear(PySSLContext *self)
2276{
2277#ifndef OPENSSL_NO_TLSEXT
2278 Py_CLEAR(self->set_hostname);
2279#endif
2280 return 0;
2281}
2282
2283static void
2284context_dealloc(PySSLContext *self)
2285{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002286 /* bpo-31095: UnTrack is needed before calling any callbacks */
2287 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002288 context_clear(self);
2289 SSL_CTX_free(self->ctx);
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002290#ifdef HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002291 PyMem_FREE(self->npn_protocols);
2292#endif
2293#ifdef HAVE_ALPN
2294 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002295#endif
2296 Py_TYPE(self)->tp_free(self);
2297}
2298
2299static PyObject *
2300set_ciphers(PySSLContext *self, PyObject *args)
2301{
2302 int ret;
2303 const char *cipherlist;
2304
2305 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2306 return NULL;
2307 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2308 if (ret == 0) {
2309 /* Clearing the error queue is necessary on some OpenSSL versions,
2310 otherwise the error will be reported again when another SSL call
2311 is done. */
2312 ERR_clear_error();
2313 PyErr_SetString(PySSLErrorObject,
2314 "No cipher can be selected.");
2315 return NULL;
2316 }
2317 Py_RETURN_NONE;
2318}
2319
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002320#if defined(HAVE_NPN) || defined(HAVE_ALPN)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002321static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002322do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2323 const unsigned char *server_protocols, unsigned int server_protocols_len,
2324 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002325{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002326 int ret;
2327 if (client_protocols == NULL) {
2328 client_protocols = (unsigned char *)"";
2329 client_protocols_len = 0;
2330 }
2331 if (server_protocols == NULL) {
2332 server_protocols = (unsigned char *)"";
2333 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002334 }
2335
Benjamin Petersonaa707582015-01-23 17:30:26 -05002336 ret = SSL_select_next_proto(out, outlen,
2337 server_protocols, server_protocols_len,
2338 client_protocols, client_protocols_len);
2339 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2340 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002341
2342 return SSL_TLSEXT_ERR_OK;
2343}
Christian Heimes72ed2332017-09-05 01:11:40 +02002344#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002345
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002346#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002347/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2348static int
2349_advertiseNPN_cb(SSL *s,
2350 const unsigned char **data, unsigned int *len,
2351 void *args)
2352{
2353 PySSLContext *ssl_ctx = (PySSLContext *) args;
2354
2355 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002356 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002357 *len = 0;
2358 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002359 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002360 *len = ssl_ctx->npn_protocols_len;
2361 }
2362
2363 return SSL_TLSEXT_ERR_OK;
2364}
2365/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2366static int
2367_selectNPN_cb(SSL *s,
2368 unsigned char **out, unsigned char *outlen,
2369 const unsigned char *server, unsigned int server_len,
2370 void *args)
2371{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002372 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002373 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002374 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002375}
2376#endif
2377
2378static PyObject *
2379_set_npn_protocols(PySSLContext *self, PyObject *args)
2380{
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002381#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002382 Py_buffer protos;
2383
2384 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2385 return NULL;
2386
2387 if (self->npn_protocols != NULL) {
2388 PyMem_Free(self->npn_protocols);
2389 }
2390
2391 self->npn_protocols = PyMem_Malloc(protos.len);
2392 if (self->npn_protocols == NULL) {
2393 PyBuffer_Release(&protos);
2394 return PyErr_NoMemory();
2395 }
2396 memcpy(self->npn_protocols, protos.buf, protos.len);
2397 self->npn_protocols_len = (int) protos.len;
2398
2399 /* set both server and client callbacks, because the context can
2400 * be used to create both types of sockets */
2401 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2402 _advertiseNPN_cb,
2403 self);
2404 SSL_CTX_set_next_proto_select_cb(self->ctx,
2405 _selectNPN_cb,
2406 self);
2407
2408 PyBuffer_Release(&protos);
2409 Py_RETURN_NONE;
2410#else
2411 PyErr_SetString(PyExc_NotImplementedError,
2412 "The NPN extension requires OpenSSL 1.0.1 or later.");
2413 return NULL;
2414#endif
2415}
2416
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002417#ifdef HAVE_ALPN
2418static int
2419_selectALPN_cb(SSL *s,
2420 const unsigned char **out, unsigned char *outlen,
2421 const unsigned char *client_protocols, unsigned int client_protocols_len,
2422 void *args)
2423{
2424 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002425 return do_protocol_selection(1, (unsigned char **)out, outlen,
2426 ctx->alpn_protocols, ctx->alpn_protocols_len,
2427 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002428}
2429#endif
2430
2431static PyObject *
2432_set_alpn_protocols(PySSLContext *self, PyObject *args)
2433{
2434#ifdef HAVE_ALPN
2435 Py_buffer protos;
2436
2437 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2438 return NULL;
2439
2440 PyMem_FREE(self->alpn_protocols);
2441 self->alpn_protocols = PyMem_Malloc(protos.len);
2442 if (!self->alpn_protocols)
2443 return PyErr_NoMemory();
2444 memcpy(self->alpn_protocols, protos.buf, protos.len);
2445 self->alpn_protocols_len = protos.len;
2446 PyBuffer_Release(&protos);
2447
2448 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2449 return PyErr_NoMemory();
2450 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2451
2452 PyBuffer_Release(&protos);
2453 Py_RETURN_NONE;
2454#else
2455 PyErr_SetString(PyExc_NotImplementedError,
2456 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2457 return NULL;
2458#endif
2459}
2460
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002461static PyObject *
2462get_verify_mode(PySSLContext *self, void *c)
2463{
2464 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2465 case SSL_VERIFY_NONE:
2466 return PyLong_FromLong(PY_SSL_CERT_NONE);
2467 case SSL_VERIFY_PEER:
2468 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2469 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2470 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2471 }
2472 PyErr_SetString(PySSLErrorObject,
2473 "invalid return value from SSL_CTX_get_verify_mode");
2474 return NULL;
2475}
2476
2477static int
2478set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2479{
2480 int n, mode;
2481 if (!PyArg_Parse(arg, "i", &n))
2482 return -1;
2483 if (n == PY_SSL_CERT_NONE)
2484 mode = SSL_VERIFY_NONE;
2485 else if (n == PY_SSL_CERT_OPTIONAL)
2486 mode = SSL_VERIFY_PEER;
2487 else if (n == PY_SSL_CERT_REQUIRED)
2488 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2489 else {
2490 PyErr_SetString(PyExc_ValueError,
2491 "invalid value for verify_mode");
2492 return -1;
2493 }
2494 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2495 PyErr_SetString(PyExc_ValueError,
2496 "Cannot set verify_mode to CERT_NONE when "
2497 "check_hostname is enabled.");
2498 return -1;
2499 }
2500 SSL_CTX_set_verify(self->ctx, mode, NULL);
2501 return 0;
2502}
2503
2504#ifdef HAVE_OPENSSL_VERIFY_PARAM
2505static PyObject *
2506get_verify_flags(PySSLContext *self, void *c)
2507{
2508 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002509 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002510 unsigned long flags;
2511
2512 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002513 param = X509_STORE_get0_param(store);
2514 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002515 return PyLong_FromUnsignedLong(flags);
2516}
2517
2518static int
2519set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2520{
2521 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002522 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002523 unsigned long new_flags, flags, set, clear;
2524
2525 if (!PyArg_Parse(arg, "k", &new_flags))
2526 return -1;
2527 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002528 param = X509_STORE_get0_param(store);
2529 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002530 clear = flags & ~new_flags;
2531 set = ~flags & new_flags;
2532 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002533 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002534 _setSSLError(NULL, 0, __FILE__, __LINE__);
2535 return -1;
2536 }
2537 }
2538 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002539 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002540 _setSSLError(NULL, 0, __FILE__, __LINE__);
2541 return -1;
2542 }
2543 }
2544 return 0;
2545}
2546#endif
2547
2548static PyObject *
2549get_options(PySSLContext *self, void *c)
2550{
2551 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2552}
2553
2554static int
2555set_options(PySSLContext *self, PyObject *arg, void *c)
2556{
2557 long new_opts, opts, set, clear;
2558 if (!PyArg_Parse(arg, "l", &new_opts))
2559 return -1;
2560 opts = SSL_CTX_get_options(self->ctx);
2561 clear = opts & ~new_opts;
2562 set = ~opts & new_opts;
2563 if (clear) {
2564#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2565 SSL_CTX_clear_options(self->ctx, clear);
2566#else
2567 PyErr_SetString(PyExc_ValueError,
2568 "can't clear options before OpenSSL 0.9.8m");
2569 return -1;
2570#endif
2571 }
2572 if (set)
2573 SSL_CTX_set_options(self->ctx, set);
2574 return 0;
2575}
2576
2577static PyObject *
2578get_check_hostname(PySSLContext *self, void *c)
2579{
2580 return PyBool_FromLong(self->check_hostname);
2581}
2582
2583static int
2584set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2585{
2586 PyObject *py_check_hostname;
2587 int check_hostname;
2588 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2589 return -1;
2590
2591 check_hostname = PyObject_IsTrue(py_check_hostname);
2592 if (check_hostname < 0)
2593 return -1;
2594 if (check_hostname &&
2595 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2596 PyErr_SetString(PyExc_ValueError,
2597 "check_hostname needs a SSL context with either "
2598 "CERT_OPTIONAL or CERT_REQUIRED");
2599 return -1;
2600 }
2601 self->check_hostname = check_hostname;
2602 return 0;
2603}
2604
2605
2606typedef struct {
2607 PyThreadState *thread_state;
2608 PyObject *callable;
2609 char *password;
2610 int size;
2611 int error;
2612} _PySSLPasswordInfo;
2613
2614static int
2615_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2616 const char *bad_type_error)
2617{
2618 /* Set the password and size fields of a _PySSLPasswordInfo struct
2619 from a unicode, bytes, or byte array object.
2620 The password field will be dynamically allocated and must be freed
2621 by the caller */
2622 PyObject *password_bytes = NULL;
2623 const char *data = NULL;
2624 Py_ssize_t size;
2625
2626 if (PyUnicode_Check(password)) {
2627 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2628 if (!password_bytes) {
2629 goto error;
2630 }
2631 data = PyBytes_AS_STRING(password_bytes);
2632 size = PyBytes_GET_SIZE(password_bytes);
2633 } else if (PyBytes_Check(password)) {
2634 data = PyBytes_AS_STRING(password);
2635 size = PyBytes_GET_SIZE(password);
2636 } else if (PyByteArray_Check(password)) {
2637 data = PyByteArray_AS_STRING(password);
2638 size = PyByteArray_GET_SIZE(password);
2639 } else {
2640 PyErr_SetString(PyExc_TypeError, bad_type_error);
2641 goto error;
2642 }
2643
2644 if (size > (Py_ssize_t)INT_MAX) {
2645 PyErr_Format(PyExc_ValueError,
2646 "password cannot be longer than %d bytes", INT_MAX);
2647 goto error;
2648 }
2649
2650 PyMem_Free(pw_info->password);
2651 pw_info->password = PyMem_Malloc(size);
2652 if (!pw_info->password) {
2653 PyErr_SetString(PyExc_MemoryError,
2654 "unable to allocate password buffer");
2655 goto error;
2656 }
2657 memcpy(pw_info->password, data, size);
2658 pw_info->size = (int)size;
2659
2660 Py_XDECREF(password_bytes);
2661 return 1;
2662
2663error:
2664 Py_XDECREF(password_bytes);
2665 return 0;
2666}
2667
2668static int
2669_password_callback(char *buf, int size, int rwflag, void *userdata)
2670{
2671 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2672 PyObject *fn_ret = NULL;
2673
2674 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2675
2676 if (pw_info->callable) {
2677 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2678 if (!fn_ret) {
2679 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2680 core python API, so we could use it to add a frame here */
2681 goto error;
2682 }
2683
2684 if (!_pwinfo_set(pw_info, fn_ret,
2685 "password callback must return a string")) {
2686 goto error;
2687 }
2688 Py_CLEAR(fn_ret);
2689 }
2690
2691 if (pw_info->size > size) {
2692 PyErr_Format(PyExc_ValueError,
2693 "password cannot be longer than %d bytes", size);
2694 goto error;
2695 }
2696
2697 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2698 memcpy(buf, pw_info->password, pw_info->size);
2699 return pw_info->size;
2700
2701error:
2702 Py_XDECREF(fn_ret);
2703 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2704 pw_info->error = 1;
2705 return -1;
2706}
2707
2708static PyObject *
2709load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2710{
2711 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002712 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2713 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002714 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2715 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002716 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2717 int r;
2718
2719 errno = 0;
2720 ERR_clear_error();
2721 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002722 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002723 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002724 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002725 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002726
2727 if (keyfile && keyfile != Py_None) {
2728 if (PyString_Check(keyfile)) {
2729 Py_INCREF(keyfile);
2730 keyfile_bytes = keyfile;
2731 } else {
2732 PyObject *u = PyUnicode_FromObject(keyfile);
2733 if (!u)
2734 goto error;
2735 keyfile_bytes = PyUnicode_AsEncodedString(
2736 u, Py_FileSystemDefaultEncoding, NULL);
2737 Py_DECREF(u);
2738 if (!keyfile_bytes)
2739 goto error;
2740 }
2741 }
2742
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002743 if (password && password != Py_None) {
2744 if (PyCallable_Check(password)) {
2745 pw_info.callable = password;
2746 } else if (!_pwinfo_set(&pw_info, password,
2747 "password should be a string or callable")) {
2748 goto error;
2749 }
2750 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2751 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2752 }
2753 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2754 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2755 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2756 if (r != 1) {
2757 if (pw_info.error) {
2758 ERR_clear_error();
2759 /* the password callback has already set the error information */
2760 }
2761 else if (errno != 0) {
2762 ERR_clear_error();
2763 PyErr_SetFromErrno(PyExc_IOError);
2764 }
2765 else {
2766 _setSSLError(NULL, 0, __FILE__, __LINE__);
2767 }
2768 goto error;
2769 }
2770 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2771 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002772 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002773 SSL_FILETYPE_PEM);
2774 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2775 if (r != 1) {
2776 if (pw_info.error) {
2777 ERR_clear_error();
2778 /* the password callback has already set the error information */
2779 }
2780 else if (errno != 0) {
2781 ERR_clear_error();
2782 PyErr_SetFromErrno(PyExc_IOError);
2783 }
2784 else {
2785 _setSSLError(NULL, 0, __FILE__, __LINE__);
2786 }
2787 goto error;
2788 }
2789 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2790 r = SSL_CTX_check_private_key(self->ctx);
2791 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2792 if (r != 1) {
2793 _setSSLError(NULL, 0, __FILE__, __LINE__);
2794 goto error;
2795 }
2796 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2797 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002798 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002799 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002800 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002801 Py_RETURN_NONE;
2802
2803error:
2804 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2805 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002806 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002807 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002808 PyMem_Free(certfile_bytes);
2809 return NULL;
2810}
2811
2812/* internal helper function, returns -1 on error
2813 */
2814static int
2815_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2816 int filetype)
2817{
2818 BIO *biobuf = NULL;
2819 X509_STORE *store;
2820 int retval = 0, err, loaded = 0;
2821
2822 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2823
2824 if (len <= 0) {
2825 PyErr_SetString(PyExc_ValueError,
2826 "Empty certificate data");
2827 return -1;
2828 } else if (len > INT_MAX) {
2829 PyErr_SetString(PyExc_OverflowError,
2830 "Certificate data is too long.");
2831 return -1;
2832 }
2833
2834 biobuf = BIO_new_mem_buf(data, (int)len);
2835 if (biobuf == NULL) {
2836 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2837 return -1;
2838 }
2839
2840 store = SSL_CTX_get_cert_store(self->ctx);
2841 assert(store != NULL);
2842
2843 while (1) {
2844 X509 *cert = NULL;
2845 int r;
2846
2847 if (filetype == SSL_FILETYPE_ASN1) {
2848 cert = d2i_X509_bio(biobuf, NULL);
2849 } else {
2850 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002851 SSL_CTX_get_default_passwd_cb(self->ctx),
2852 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2853 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002854 }
2855 if (cert == NULL) {
2856 break;
2857 }
2858 r = X509_STORE_add_cert(store, cert);
2859 X509_free(cert);
2860 if (!r) {
2861 err = ERR_peek_last_error();
2862 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2863 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2864 /* cert already in hash table, not an error */
2865 ERR_clear_error();
2866 } else {
2867 break;
2868 }
2869 }
2870 loaded++;
2871 }
2872
2873 err = ERR_peek_last_error();
2874 if ((filetype == SSL_FILETYPE_ASN1) &&
2875 (loaded > 0) &&
2876 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2877 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2878 /* EOF ASN1 file, not an error */
2879 ERR_clear_error();
2880 retval = 0;
2881 } else if ((filetype == SSL_FILETYPE_PEM) &&
2882 (loaded > 0) &&
2883 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2884 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2885 /* EOF PEM file, not an error */
2886 ERR_clear_error();
2887 retval = 0;
2888 } else {
2889 _setSSLError(NULL, 0, __FILE__, __LINE__);
2890 retval = -1;
2891 }
2892
2893 BIO_free(biobuf);
2894 return retval;
2895}
2896
2897
2898static PyObject *
2899load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2900{
2901 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2902 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2903 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2904 const char *cafile_buf = NULL, *capath_buf = NULL;
2905 int r = 0, ok = 1;
2906
2907 errno = 0;
2908 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2909 "|OOO:load_verify_locations", kwlist,
2910 &cafile, &capath, &cadata))
2911 return NULL;
2912
2913 if (cafile == Py_None)
2914 cafile = NULL;
2915 if (capath == Py_None)
2916 capath = NULL;
2917 if (cadata == Py_None)
2918 cadata = NULL;
2919
2920 if (cafile == NULL && capath == NULL && cadata == NULL) {
2921 PyErr_SetString(PyExc_TypeError,
2922 "cafile, capath and cadata cannot be all omitted");
2923 goto error;
2924 }
2925
2926 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002927 if (PyString_Check(cafile)) {
2928 Py_INCREF(cafile);
2929 cafile_bytes = cafile;
2930 } else {
2931 PyObject *u = PyUnicode_FromObject(cafile);
2932 if (!u)
2933 goto error;
2934 cafile_bytes = PyUnicode_AsEncodedString(
2935 u, Py_FileSystemDefaultEncoding, NULL);
2936 Py_DECREF(u);
2937 if (!cafile_bytes)
2938 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002939 }
2940 }
2941 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002942 if (PyString_Check(capath)) {
2943 Py_INCREF(capath);
2944 capath_bytes = capath;
2945 } else {
2946 PyObject *u = PyUnicode_FromObject(capath);
2947 if (!u)
2948 goto error;
2949 capath_bytes = PyUnicode_AsEncodedString(
2950 u, Py_FileSystemDefaultEncoding, NULL);
2951 Py_DECREF(u);
2952 if (!capath_bytes)
2953 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002954 }
2955 }
2956
2957 /* validata cadata type and load cadata */
2958 if (cadata) {
2959 Py_buffer buf;
2960 PyObject *cadata_ascii = NULL;
2961
2962 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2963 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2964 PyBuffer_Release(&buf);
2965 PyErr_SetString(PyExc_TypeError,
2966 "cadata should be a contiguous buffer with "
2967 "a single dimension");
2968 goto error;
2969 }
2970 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2971 PyBuffer_Release(&buf);
2972 if (r == -1) {
2973 goto error;
2974 }
2975 } else {
2976 PyErr_Clear();
2977 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2978 if (cadata_ascii == NULL) {
2979 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002980 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002981 "bytes-like object");
2982 goto error;
2983 }
2984 r = _add_ca_certs(self,
2985 PyBytes_AS_STRING(cadata_ascii),
2986 PyBytes_GET_SIZE(cadata_ascii),
2987 SSL_FILETYPE_PEM);
2988 Py_DECREF(cadata_ascii);
2989 if (r == -1) {
2990 goto error;
2991 }
2992 }
2993 }
2994
2995 /* load cafile or capath */
2996 if (cafile_bytes || capath_bytes) {
2997 if (cafile)
2998 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2999 if (capath)
3000 capath_buf = PyBytes_AS_STRING(capath_bytes);
3001 PySSL_BEGIN_ALLOW_THREADS
3002 r = SSL_CTX_load_verify_locations(
3003 self->ctx,
3004 cafile_buf,
3005 capath_buf);
3006 PySSL_END_ALLOW_THREADS
3007 if (r != 1) {
3008 ok = 0;
3009 if (errno != 0) {
3010 ERR_clear_error();
3011 PyErr_SetFromErrno(PyExc_IOError);
3012 }
3013 else {
3014 _setSSLError(NULL, 0, __FILE__, __LINE__);
3015 }
3016 goto error;
3017 }
3018 }
3019 goto end;
3020
3021 error:
3022 ok = 0;
3023 end:
3024 Py_XDECREF(cafile_bytes);
3025 Py_XDECREF(capath_bytes);
3026 if (ok) {
3027 Py_RETURN_NONE;
3028 } else {
3029 return NULL;
3030 }
3031}
3032
3033static PyObject *
3034load_dh_params(PySSLContext *self, PyObject *filepath)
3035{
3036 BIO *bio;
3037 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003038 PyObject *filepath_bytes = NULL;
3039
3040 if (PyString_Check(filepath)) {
3041 Py_INCREF(filepath);
3042 filepath_bytes = filepath;
3043 } else {
3044 PyObject *u = PyUnicode_FromObject(filepath);
3045 if (!u)
3046 return NULL;
3047 filepath_bytes = PyUnicode_AsEncodedString(
3048 u, Py_FileSystemDefaultEncoding, NULL);
3049 Py_DECREF(u);
3050 if (!filepath_bytes)
3051 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003052 }
3053
Christian Heimes6e8f3952018-02-25 09:48:02 +01003054 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003055 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003056 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003057 ERR_clear_error();
3058 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3059 return NULL;
3060 }
3061 errno = 0;
3062 PySSL_BEGIN_ALLOW_THREADS
3063 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3064 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003065 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003066 PySSL_END_ALLOW_THREADS
3067 if (dh == NULL) {
3068 if (errno != 0) {
3069 ERR_clear_error();
3070 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3071 }
3072 else {
3073 _setSSLError(NULL, 0, __FILE__, __LINE__);
3074 }
3075 return NULL;
3076 }
3077 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3078 _setSSLError(NULL, 0, __FILE__, __LINE__);
3079 DH_free(dh);
3080 Py_RETURN_NONE;
3081}
3082
3083static PyObject *
3084context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3085{
3086 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3087 PySocketSockObject *sock;
3088 int server_side = 0;
3089 char *hostname = NULL;
3090 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3091
3092 /* server_hostname is either None (or absent), or to be encoded
3093 using the idna encoding. */
3094 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3095 PySocketModule.Sock_Type,
3096 &sock, &server_side,
3097 Py_TYPE(Py_None), &hostname_obj,
3098 &ssl_sock)) {
3099 PyErr_Clear();
3100 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3101 PySocketModule.Sock_Type,
3102 &sock, &server_side,
3103 "idna", &hostname, &ssl_sock))
3104 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003105 }
3106
3107 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3108 hostname, ssl_sock);
3109 if (hostname != NULL)
3110 PyMem_Free(hostname);
3111 return res;
3112}
3113
3114static PyObject *
3115session_stats(PySSLContext *self, PyObject *unused)
3116{
3117 int r;
3118 PyObject *value, *stats = PyDict_New();
3119 if (!stats)
3120 return NULL;
3121
3122#define ADD_STATS(SSL_NAME, KEY_NAME) \
3123 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3124 if (value == NULL) \
3125 goto error; \
3126 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3127 Py_DECREF(value); \
3128 if (r < 0) \
3129 goto error;
3130
3131 ADD_STATS(number, "number");
3132 ADD_STATS(connect, "connect");
3133 ADD_STATS(connect_good, "connect_good");
3134 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3135 ADD_STATS(accept, "accept");
3136 ADD_STATS(accept_good, "accept_good");
3137 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3138 ADD_STATS(accept, "accept");
3139 ADD_STATS(hits, "hits");
3140 ADD_STATS(misses, "misses");
3141 ADD_STATS(timeouts, "timeouts");
3142 ADD_STATS(cache_full, "cache_full");
3143
3144#undef ADD_STATS
3145
3146 return stats;
3147
3148error:
3149 Py_DECREF(stats);
3150 return NULL;
3151}
3152
3153static PyObject *
3154set_default_verify_paths(PySSLContext *self, PyObject *unused)
3155{
3156 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3157 _setSSLError(NULL, 0, __FILE__, __LINE__);
3158 return NULL;
3159 }
3160 Py_RETURN_NONE;
3161}
3162
3163#ifndef OPENSSL_NO_ECDH
3164static PyObject *
3165set_ecdh_curve(PySSLContext *self, PyObject *name)
3166{
3167 char *name_bytes;
3168 int nid;
3169 EC_KEY *key;
3170
3171 name_bytes = PyBytes_AsString(name);
3172 if (!name_bytes) {
3173 return NULL;
3174 }
3175 nid = OBJ_sn2nid(name_bytes);
3176 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003177 PyObject *r = PyObject_Repr(name);
3178 if (!r)
3179 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003180 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003181 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3182 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003183 return NULL;
3184 }
3185 key = EC_KEY_new_by_curve_name(nid);
3186 if (key == NULL) {
3187 _setSSLError(NULL, 0, __FILE__, __LINE__);
3188 return NULL;
3189 }
3190 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3191 EC_KEY_free(key);
3192 Py_RETURN_NONE;
3193}
3194#endif
3195
3196#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3197static int
3198_servername_callback(SSL *s, int *al, void *args)
3199{
3200 int ret;
3201 PySSLContext *ssl_ctx = (PySSLContext *) args;
3202 PySSLSocket *ssl;
3203 PyObject *servername_o;
3204 PyObject *servername_idna;
3205 PyObject *result;
3206 /* The high-level ssl.SSLSocket object */
3207 PyObject *ssl_socket;
3208 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3209#ifdef WITH_THREAD
3210 PyGILState_STATE gstate = PyGILState_Ensure();
3211#endif
3212
3213 if (ssl_ctx->set_hostname == NULL) {
3214 /* remove race condition in this the call back while if removing the
3215 * callback is in progress */
3216#ifdef WITH_THREAD
3217 PyGILState_Release(gstate);
3218#endif
3219 return SSL_TLSEXT_ERR_OK;
3220 }
3221
3222 ssl = SSL_get_app_data(s);
3223 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003224 if (ssl->ssl_sock == NULL) {
3225 ssl_socket = Py_None;
3226 } else {
3227 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3228 Py_INCREF(ssl_socket);
3229 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003230 if (ssl_socket == Py_None) {
3231 goto error;
3232 }
3233
3234 if (servername == NULL) {
3235 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3236 Py_None, ssl_ctx, NULL);
3237 }
3238 else {
3239 servername_o = PyBytes_FromString(servername);
3240 if (servername_o == NULL) {
3241 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3242 goto error;
3243 }
3244 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3245 if (servername_idna == NULL) {
3246 PyErr_WriteUnraisable(servername_o);
3247 Py_DECREF(servername_o);
3248 goto error;
3249 }
3250 Py_DECREF(servername_o);
3251 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3252 servername_idna, ssl_ctx, NULL);
3253 Py_DECREF(servername_idna);
3254 }
3255 Py_DECREF(ssl_socket);
3256
3257 if (result == NULL) {
3258 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3259 *al = SSL_AD_HANDSHAKE_FAILURE;
3260 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3261 }
3262 else {
3263 if (result != Py_None) {
3264 *al = (int) PyLong_AsLong(result);
3265 if (PyErr_Occurred()) {
3266 PyErr_WriteUnraisable(result);
3267 *al = SSL_AD_INTERNAL_ERROR;
3268 }
3269 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3270 }
3271 else {
3272 ret = SSL_TLSEXT_ERR_OK;
3273 }
3274 Py_DECREF(result);
3275 }
3276
3277#ifdef WITH_THREAD
3278 PyGILState_Release(gstate);
3279#endif
3280 return ret;
3281
3282error:
3283 Py_DECREF(ssl_socket);
3284 *al = SSL_AD_INTERNAL_ERROR;
3285 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3286#ifdef WITH_THREAD
3287 PyGILState_Release(gstate);
3288#endif
3289 return ret;
3290}
3291#endif
3292
3293PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3294"set_servername_callback(method)\n\
3295\n\
3296This sets a callback that will be called when a server name is provided by\n\
3297the SSL/TLS client in the SNI extension.\n\
3298\n\
3299If the argument is None then the callback is disabled. The method is called\n\
3300with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3301See RFC 6066 for details of the SNI extension.");
3302
3303static PyObject *
3304set_servername_callback(PySSLContext *self, PyObject *args)
3305{
3306#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3307 PyObject *cb;
3308
3309 if (!PyArg_ParseTuple(args, "O", &cb))
3310 return NULL;
3311
3312 Py_CLEAR(self->set_hostname);
3313 if (cb == Py_None) {
3314 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3315 }
3316 else {
3317 if (!PyCallable_Check(cb)) {
3318 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3319 PyErr_SetString(PyExc_TypeError,
3320 "not a callable object");
3321 return NULL;
3322 }
3323 Py_INCREF(cb);
3324 self->set_hostname = cb;
3325 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3326 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3327 }
3328 Py_RETURN_NONE;
3329#else
3330 PyErr_SetString(PyExc_NotImplementedError,
3331 "The TLS extension servername callback, "
3332 "SSL_CTX_set_tlsext_servername_callback, "
3333 "is not in the current OpenSSL library.");
3334 return NULL;
3335#endif
3336}
3337
3338PyDoc_STRVAR(PySSL_get_stats_doc,
3339"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3340\n\
3341Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3342CA extension and certificate revocation lists inside the context's cert\n\
3343store.\n\
3344NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3345been used at least once.");
3346
3347static PyObject *
3348cert_store_stats(PySSLContext *self)
3349{
3350 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003351 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003352 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003353 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003354
3355 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003356 objs = X509_STORE_get0_objects(store);
3357 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3358 obj = sk_X509_OBJECT_value(objs, i);
3359 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003360 case X509_LU_X509:
3361 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003362 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003363 ca++;
3364 }
3365 break;
3366 case X509_LU_CRL:
3367 crl++;
3368 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003369 default:
3370 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3371 * As far as I can tell they are internal states and never
3372 * stored in a cert store */
3373 break;
3374 }
3375 }
3376 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3377 "x509_ca", ca);
3378}
3379
3380PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3381"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3382\n\
3383Returns a list of dicts with information of loaded CA certs. If the\n\
3384optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3385NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3386been used at least once.");
3387
3388static PyObject *
3389get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3390{
3391 char *kwlist[] = {"binary_form", NULL};
3392 X509_STORE *store;
3393 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003394 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003395 int i;
3396 int binary_mode = 0;
3397
3398 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3399 kwlist, &py_binary_mode)) {
3400 return NULL;
3401 }
3402 binary_mode = PyObject_IsTrue(py_binary_mode);
3403 if (binary_mode < 0) {
3404 return NULL;
3405 }
3406
3407 if ((rlist = PyList_New(0)) == NULL) {
3408 return NULL;
3409 }
3410
3411 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003412 objs = X509_STORE_get0_objects(store);
3413 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003414 X509_OBJECT *obj;
3415 X509 *cert;
3416
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003417 obj = sk_X509_OBJECT_value(objs, i);
3418 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003419 /* not a x509 cert */
3420 continue;
3421 }
3422 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003423 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003424 if (!X509_check_ca(cert)) {
3425 continue;
3426 }
3427 if (binary_mode) {
3428 ci = _certificate_to_der(cert);
3429 } else {
3430 ci = _decode_certificate(cert);
3431 }
3432 if (ci == NULL) {
3433 goto error;
3434 }
3435 if (PyList_Append(rlist, ci) == -1) {
3436 goto error;
3437 }
3438 Py_CLEAR(ci);
3439 }
3440 return rlist;
3441
3442 error:
3443 Py_XDECREF(ci);
3444 Py_XDECREF(rlist);
3445 return NULL;
3446}
3447
3448
3449static PyGetSetDef context_getsetlist[] = {
3450 {"check_hostname", (getter) get_check_hostname,
3451 (setter) set_check_hostname, NULL},
3452 {"options", (getter) get_options,
3453 (setter) set_options, NULL},
3454#ifdef HAVE_OPENSSL_VERIFY_PARAM
3455 {"verify_flags", (getter) get_verify_flags,
3456 (setter) set_verify_flags, NULL},
3457#endif
3458 {"verify_mode", (getter) get_verify_mode,
3459 (setter) set_verify_mode, NULL},
3460 {NULL}, /* sentinel */
3461};
3462
3463static struct PyMethodDef context_methods[] = {
3464 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3465 METH_VARARGS | METH_KEYWORDS, NULL},
3466 {"set_ciphers", (PyCFunction) set_ciphers,
3467 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003468 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3469 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003470 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3471 METH_VARARGS, NULL},
3472 {"load_cert_chain", (PyCFunction) load_cert_chain,
3473 METH_VARARGS | METH_KEYWORDS, NULL},
3474 {"load_dh_params", (PyCFunction) load_dh_params,
3475 METH_O, NULL},
3476 {"load_verify_locations", (PyCFunction) load_verify_locations,
3477 METH_VARARGS | METH_KEYWORDS, NULL},
3478 {"session_stats", (PyCFunction) session_stats,
3479 METH_NOARGS, NULL},
3480 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3481 METH_NOARGS, NULL},
3482#ifndef OPENSSL_NO_ECDH
3483 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3484 METH_O, NULL},
3485#endif
3486 {"set_servername_callback", (PyCFunction) set_servername_callback,
3487 METH_VARARGS, PySSL_set_servername_callback_doc},
3488 {"cert_store_stats", (PyCFunction) cert_store_stats,
3489 METH_NOARGS, PySSL_get_stats_doc},
3490 {"get_ca_certs", (PyCFunction) get_ca_certs,
3491 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3492 {NULL, NULL} /* sentinel */
3493};
3494
3495static PyTypeObject PySSLContext_Type = {
3496 PyVarObject_HEAD_INIT(NULL, 0)
3497 "_ssl._SSLContext", /*tp_name*/
3498 sizeof(PySSLContext), /*tp_basicsize*/
3499 0, /*tp_itemsize*/
3500 (destructor)context_dealloc, /*tp_dealloc*/
3501 0, /*tp_print*/
3502 0, /*tp_getattr*/
3503 0, /*tp_setattr*/
3504 0, /*tp_reserved*/
3505 0, /*tp_repr*/
3506 0, /*tp_as_number*/
3507 0, /*tp_as_sequence*/
3508 0, /*tp_as_mapping*/
3509 0, /*tp_hash*/
3510 0, /*tp_call*/
3511 0, /*tp_str*/
3512 0, /*tp_getattro*/
3513 0, /*tp_setattro*/
3514 0, /*tp_as_buffer*/
3515 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3516 0, /*tp_doc*/
3517 (traverseproc) context_traverse, /*tp_traverse*/
3518 (inquiry) context_clear, /*tp_clear*/
3519 0, /*tp_richcompare*/
3520 0, /*tp_weaklistoffset*/
3521 0, /*tp_iter*/
3522 0, /*tp_iternext*/
3523 context_methods, /*tp_methods*/
3524 0, /*tp_members*/
3525 context_getsetlist, /*tp_getset*/
3526 0, /*tp_base*/
3527 0, /*tp_dict*/
3528 0, /*tp_descr_get*/
3529 0, /*tp_descr_set*/
3530 0, /*tp_dictoffset*/
3531 0, /*tp_init*/
3532 0, /*tp_alloc*/
3533 context_new, /*tp_new*/
3534};
3535
3536
3537
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003538#ifdef HAVE_OPENSSL_RAND
3539
3540/* helper routines for seeding the SSL PRNG */
3541static PyObject *
3542PySSL_RAND_add(PyObject *self, PyObject *args)
3543{
3544 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003545 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003546 double entropy;
3547
3548 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003549 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003550 do {
3551 if (len >= INT_MAX) {
3552 written = INT_MAX;
3553 } else {
3554 written = len;
3555 }
3556 RAND_add(buf, (int)written, entropy);
3557 buf += written;
3558 len -= written;
3559 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003560 Py_INCREF(Py_None);
3561 return Py_None;
3562}
3563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003564PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003565"RAND_add(string, entropy)\n\
3566\n\
3567Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003568bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003569
3570static PyObject *
3571PySSL_RAND_status(PyObject *self)
3572{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003573 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003574}
3575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003576PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003577"RAND_status() -> 0 or 1\n\
3578\n\
3579Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3580It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003581using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003582
Victor Stinner7c906672015-01-06 13:53:37 +01003583#endif /* HAVE_OPENSSL_RAND */
3584
3585
Benjamin Peterson42e10292016-07-07 00:02:31 -07003586#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003587
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003588static PyObject *
3589PySSL_RAND_egd(PyObject *self, PyObject *arg)
3590{
3591 int bytes;
3592
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003593 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003594 return PyErr_Format(PyExc_TypeError,
3595 "RAND_egd() expected string, found %s",
3596 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003597 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003598 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003599 PyErr_SetString(PySSLErrorObject,
3600 "EGD connection failed or EGD did not return "
3601 "enough data to seed the PRNG");
3602 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003603 }
3604 return PyInt_FromLong(bytes);
3605}
3606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003608"RAND_egd(path) -> bytes\n\
3609\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003610Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3611Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003612fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003613
Benjamin Peterson42e10292016-07-07 00:02:31 -07003614#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003615
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003616
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003617PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3618"get_default_verify_paths() -> tuple\n\
3619\n\
3620Return search paths and environment vars that are used by SSLContext's\n\
3621set_default_verify_paths() to load default CAs. The values are\n\
3622'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3623
3624static PyObject *
3625PySSL_get_default_verify_paths(PyObject *self)
3626{
3627 PyObject *ofile_env = NULL;
3628 PyObject *ofile = NULL;
3629 PyObject *odir_env = NULL;
3630 PyObject *odir = NULL;
3631
Benjamin Peterson65192c12015-07-18 10:59:13 -07003632#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003633 const char *tmp = (info); \
3634 target = NULL; \
3635 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3636 else { target = PyBytes_FromString(tmp); } \
3637 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003638 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003639
Benjamin Peterson65192c12015-07-18 10:59:13 -07003640 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3641 CONVERT(X509_get_default_cert_file(), ofile);
3642 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3643 CONVERT(X509_get_default_cert_dir(), odir);
3644#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003645
3646 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3647
3648 error:
3649 Py_XDECREF(ofile_env);
3650 Py_XDECREF(ofile);
3651 Py_XDECREF(odir_env);
3652 Py_XDECREF(odir);
3653 return NULL;
3654}
3655
3656static PyObject*
3657asn1obj2py(ASN1_OBJECT *obj)
3658{
3659 int nid;
3660 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003661
3662 nid = OBJ_obj2nid(obj);
3663 if (nid == NID_undef) {
3664 PyErr_Format(PyExc_ValueError, "Unknown object");
3665 return NULL;
3666 }
3667 sn = OBJ_nid2sn(nid);
3668 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003669 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003670}
3671
3672PyDoc_STRVAR(PySSL_txt2obj_doc,
3673"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3674\n\
3675Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3676objects are looked up by OID. With name=True short and long name are also\n\
3677matched.");
3678
3679static PyObject*
3680PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3681{
3682 char *kwlist[] = {"txt", "name", NULL};
3683 PyObject *result = NULL;
3684 char *txt;
3685 PyObject *pyname = Py_None;
3686 int name = 0;
3687 ASN1_OBJECT *obj;
3688
3689 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3690 kwlist, &txt, &pyname)) {
3691 return NULL;
3692 }
3693 name = PyObject_IsTrue(pyname);
3694 if (name < 0)
3695 return NULL;
3696 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3697 if (obj == NULL) {
3698 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3699 return NULL;
3700 }
3701 result = asn1obj2py(obj);
3702 ASN1_OBJECT_free(obj);
3703 return result;
3704}
3705
3706PyDoc_STRVAR(PySSL_nid2obj_doc,
3707"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3708\n\
3709Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3710
3711static PyObject*
3712PySSL_nid2obj(PyObject *self, PyObject *args)
3713{
3714 PyObject *result = NULL;
3715 int nid;
3716 ASN1_OBJECT *obj;
3717
3718 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3719 return NULL;
3720 }
3721 if (nid < NID_undef) {
3722 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3723 return NULL;
3724 }
3725 obj = OBJ_nid2obj(nid);
3726 if (obj == NULL) {
3727 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3728 return NULL;
3729 }
3730 result = asn1obj2py(obj);
3731 ASN1_OBJECT_free(obj);
3732 return result;
3733}
3734
3735#ifdef _MSC_VER
3736
3737static PyObject*
3738certEncodingType(DWORD encodingType)
3739{
3740 static PyObject *x509_asn = NULL;
3741 static PyObject *pkcs_7_asn = NULL;
3742
3743 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003744 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003745 if (x509_asn == NULL)
3746 return NULL;
3747 }
3748 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003749 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003750 if (pkcs_7_asn == NULL)
3751 return NULL;
3752 }
3753 switch(encodingType) {
3754 case X509_ASN_ENCODING:
3755 Py_INCREF(x509_asn);
3756 return x509_asn;
3757 case PKCS_7_ASN_ENCODING:
3758 Py_INCREF(pkcs_7_asn);
3759 return pkcs_7_asn;
3760 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003761 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003762 }
3763}
3764
3765static PyObject*
3766parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3767{
3768 CERT_ENHKEY_USAGE *usage;
3769 DWORD size, error, i;
3770 PyObject *retval;
3771
3772 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3773 error = GetLastError();
3774 if (error == CRYPT_E_NOT_FOUND) {
3775 Py_RETURN_TRUE;
3776 }
3777 return PyErr_SetFromWindowsErr(error);
3778 }
3779
3780 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3781 if (usage == NULL) {
3782 return PyErr_NoMemory();
3783 }
3784
3785 /* Now get the actual enhanced usage property */
3786 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3787 PyMem_Free(usage);
3788 error = GetLastError();
3789 if (error == CRYPT_E_NOT_FOUND) {
3790 Py_RETURN_TRUE;
3791 }
3792 return PyErr_SetFromWindowsErr(error);
3793 }
3794 retval = PySet_New(NULL);
3795 if (retval == NULL) {
3796 goto error;
3797 }
3798 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3799 if (usage->rgpszUsageIdentifier[i]) {
3800 PyObject *oid;
3801 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003802 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003803 if (oid == NULL) {
3804 Py_CLEAR(retval);
3805 goto error;
3806 }
3807 err = PySet_Add(retval, oid);
3808 Py_DECREF(oid);
3809 if (err == -1) {
3810 Py_CLEAR(retval);
3811 goto error;
3812 }
3813 }
3814 }
3815 error:
3816 PyMem_Free(usage);
3817 return retval;
3818}
3819
3820PyDoc_STRVAR(PySSL_enum_certificates_doc,
3821"enum_certificates(store_name) -> []\n\
3822\n\
3823Retrieve certificates from Windows' cert store. store_name may be one of\n\
3824'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3825The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3826encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3827PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3828boolean True.");
3829
3830static PyObject *
3831PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3832{
3833 char *kwlist[] = {"store_name", NULL};
3834 char *store_name;
3835 HCERTSTORE hStore = NULL;
3836 PCCERT_CONTEXT pCertCtx = NULL;
3837 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3838 PyObject *result = NULL;
3839
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003840 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003841 kwlist, &store_name)) {
3842 return NULL;
3843 }
3844 result = PyList_New(0);
3845 if (result == NULL) {
3846 return NULL;
3847 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003848 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3849 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3850 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003851 if (hStore == NULL) {
3852 Py_DECREF(result);
3853 return PyErr_SetFromWindowsErr(GetLastError());
3854 }
3855
3856 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3857 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3858 pCertCtx->cbCertEncoded);
3859 if (!cert) {
3860 Py_CLEAR(result);
3861 break;
3862 }
3863 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3864 Py_CLEAR(result);
3865 break;
3866 }
3867 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3868 if (keyusage == Py_True) {
3869 Py_DECREF(keyusage);
3870 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3871 }
3872 if (keyusage == NULL) {
3873 Py_CLEAR(result);
3874 break;
3875 }
3876 if ((tup = PyTuple_New(3)) == NULL) {
3877 Py_CLEAR(result);
3878 break;
3879 }
3880 PyTuple_SET_ITEM(tup, 0, cert);
3881 cert = NULL;
3882 PyTuple_SET_ITEM(tup, 1, enc);
3883 enc = NULL;
3884 PyTuple_SET_ITEM(tup, 2, keyusage);
3885 keyusage = NULL;
3886 if (PyList_Append(result, tup) < 0) {
3887 Py_CLEAR(result);
3888 break;
3889 }
3890 Py_CLEAR(tup);
3891 }
3892 if (pCertCtx) {
3893 /* loop ended with an error, need to clean up context manually */
3894 CertFreeCertificateContext(pCertCtx);
3895 }
3896
3897 /* In error cases cert, enc and tup may not be NULL */
3898 Py_XDECREF(cert);
3899 Py_XDECREF(enc);
3900 Py_XDECREF(keyusage);
3901 Py_XDECREF(tup);
3902
3903 if (!CertCloseStore(hStore, 0)) {
3904 /* This error case might shadow another exception.*/
3905 Py_XDECREF(result);
3906 return PyErr_SetFromWindowsErr(GetLastError());
3907 }
3908 return result;
3909}
3910
3911PyDoc_STRVAR(PySSL_enum_crls_doc,
3912"enum_crls(store_name) -> []\n\
3913\n\
3914Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3915'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3916The function returns a list of (bytes, encoding_type) tuples. The\n\
3917encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3918PKCS_7_ASN_ENCODING.");
3919
3920static PyObject *
3921PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3922{
3923 char *kwlist[] = {"store_name", NULL};
3924 char *store_name;
3925 HCERTSTORE hStore = NULL;
3926 PCCRL_CONTEXT pCrlCtx = NULL;
3927 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3928 PyObject *result = NULL;
3929
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003930 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003931 kwlist, &store_name)) {
3932 return NULL;
3933 }
3934 result = PyList_New(0);
3935 if (result == NULL) {
3936 return NULL;
3937 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003938 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3939 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3940 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003941 if (hStore == NULL) {
3942 Py_DECREF(result);
3943 return PyErr_SetFromWindowsErr(GetLastError());
3944 }
3945
3946 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3947 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3948 pCrlCtx->cbCrlEncoded);
3949 if (!crl) {
3950 Py_CLEAR(result);
3951 break;
3952 }
3953 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3954 Py_CLEAR(result);
3955 break;
3956 }
3957 if ((tup = PyTuple_New(2)) == NULL) {
3958 Py_CLEAR(result);
3959 break;
3960 }
3961 PyTuple_SET_ITEM(tup, 0, crl);
3962 crl = NULL;
3963 PyTuple_SET_ITEM(tup, 1, enc);
3964 enc = NULL;
3965
3966 if (PyList_Append(result, tup) < 0) {
3967 Py_CLEAR(result);
3968 break;
3969 }
3970 Py_CLEAR(tup);
3971 }
3972 if (pCrlCtx) {
3973 /* loop ended with an error, need to clean up context manually */
3974 CertFreeCRLContext(pCrlCtx);
3975 }
3976
3977 /* In error cases cert, enc and tup may not be NULL */
3978 Py_XDECREF(crl);
3979 Py_XDECREF(enc);
3980 Py_XDECREF(tup);
3981
3982 if (!CertCloseStore(hStore, 0)) {
3983 /* This error case might shadow another exception.*/
3984 Py_XDECREF(result);
3985 return PyErr_SetFromWindowsErr(GetLastError());
3986 }
3987 return result;
3988}
3989
3990#endif /* _MSC_VER */
3991
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003992/* List of functions exported by this module. */
3993
3994static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003995 {"_test_decode_cert", PySSL_test_decode_certificate,
3996 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003997#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003998 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3999 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004000 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4001 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004002#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07004003#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01004004 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
4005 PySSL_RAND_egd_doc},
4006#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004007 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
4008 METH_NOARGS, PySSL_get_default_verify_paths_doc},
4009#ifdef _MSC_VER
4010 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4011 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4012 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4013 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4014#endif
4015 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4016 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4017 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4018 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004019 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004020};
4021
4022
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004023#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004024
4025/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004026 * of the Python C thread library
4027 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4028 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004029
4030static PyThread_type_lock *_ssl_locks = NULL;
4031
Christian Heimes10107812013-08-19 17:36:29 +02004032#if OPENSSL_VERSION_NUMBER >= 0x10000000
4033/* use new CRYPTO_THREADID API. */
4034static void
4035_ssl_threadid_callback(CRYPTO_THREADID *id)
4036{
4037 CRYPTO_THREADID_set_numeric(id,
4038 (unsigned long)PyThread_get_thread_ident());
4039}
4040#else
4041/* deprecated CRYPTO_set_id_callback() API. */
4042static unsigned long
4043_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004044 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004045}
Christian Heimes10107812013-08-19 17:36:29 +02004046#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004047
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004048static void _ssl_thread_locking_function
4049 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004050 /* this function is needed to perform locking on shared data
4051 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004052 structures that will be implicitly shared whenever multiple
4053 threads use OpenSSL.) Multi-threaded applications will
4054 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004055
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004056 locking_function() must be able to handle up to
4057 CRYPTO_num_locks() different mutex locks. It sets the n-th
4058 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004059
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004060 file and line are the file number of the function setting the
4061 lock. They can be useful for debugging.
4062 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004063
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004064 if ((_ssl_locks == NULL) ||
4065 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4066 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004067
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004068 if (mode & CRYPTO_LOCK) {
4069 PyThread_acquire_lock(_ssl_locks[n], 1);
4070 } else {
4071 PyThread_release_lock(_ssl_locks[n]);
4072 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004073}
4074
4075static int _setup_ssl_threads(void) {
4076
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004077 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004078
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004079 if (_ssl_locks == NULL) {
4080 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004081 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4082 if (_ssl_locks == NULL) {
4083 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004084 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004085 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004086 memset(_ssl_locks, 0,
4087 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004088 for (i = 0; i < _ssl_locks_count; i++) {
4089 _ssl_locks[i] = PyThread_allocate_lock();
4090 if (_ssl_locks[i] == NULL) {
4091 unsigned int j;
4092 for (j = 0; j < i; j++) {
4093 PyThread_free_lock(_ssl_locks[j]);
4094 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004095 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004096 return 0;
4097 }
4098 }
4099 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004100#if OPENSSL_VERSION_NUMBER >= 0x10000000
4101 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4102#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004103 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004104#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004105 }
4106 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004107}
4108
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004109#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004111PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004112"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004113for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004114
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004115
4116
4117
4118static void
4119parse_openssl_version(unsigned long libver,
4120 unsigned int *major, unsigned int *minor,
4121 unsigned int *fix, unsigned int *patch,
4122 unsigned int *status)
4123{
4124 *status = libver & 0xF;
4125 libver >>= 4;
4126 *patch = libver & 0xFF;
4127 libver >>= 8;
4128 *fix = libver & 0xFF;
4129 libver >>= 8;
4130 *minor = libver & 0xFF;
4131 libver >>= 8;
4132 *major = libver & 0xFF;
4133}
4134
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004135PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004136init_ssl(void)
4137{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004138 PyObject *m, *d, *r;
4139 unsigned long libver;
4140 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004141 struct py_ssl_error_code *errcode;
4142 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004143
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004144 if (PyType_Ready(&PySSLContext_Type) < 0)
4145 return;
4146 if (PyType_Ready(&PySSLSocket_Type) < 0)
4147 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004148
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004149 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4150 if (m == NULL)
4151 return;
4152 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004153
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004154 /* Load _socket module and its C API */
4155 if (PySocketModule_ImportModuleAndAPI())
4156 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004157
Christian Heimes7daa45d2017-09-05 17:12:12 +02004158#ifndef OPENSSL_VERSION_1_1
4159 /* Load all algorithms and initialize cpuid */
4160 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004161 /* Init OpenSSL */
4162 SSL_load_error_strings();
4163 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004164#endif
4165
Bill Janssen98d19da2007-09-10 21:51:02 +00004166#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004167#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004168 /* note that this will start threading if not already started */
4169 if (!_setup_ssl_threads()) {
4170 return;
4171 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004172#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4173 /* OpenSSL 1.1.0 builtin thread support is enabled */
4174 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004175#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004176#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004177
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004178 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004179 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4180 "ssl.SSLError", SSLError_doc,
4181 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004182 if (PySSLErrorObject == NULL)
4183 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004184 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4185
4186 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4187 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4188 PySSLErrorObject, NULL);
4189 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4190 "ssl.SSLWantReadError", SSLWantReadError_doc,
4191 PySSLErrorObject, NULL);
4192 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4193 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4194 PySSLErrorObject, NULL);
4195 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4196 "ssl.SSLSyscallError", SSLSyscallError_doc,
4197 PySSLErrorObject, NULL);
4198 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4199 "ssl.SSLEOFError", SSLEOFError_doc,
4200 PySSLErrorObject, NULL);
4201 if (PySSLZeroReturnErrorObject == NULL
4202 || PySSLWantReadErrorObject == NULL
4203 || PySSLWantWriteErrorObject == NULL
4204 || PySSLSyscallErrorObject == NULL
4205 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004206 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004207
4208 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4209 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4210 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4211 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4212 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4213
4214 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4215 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4216 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4217 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4218 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4219 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4220 return;
4221 if (PyDict_SetItemString(d, "_SSLContext",
4222 (PyObject *)&PySSLContext_Type) != 0)
4223 return;
4224 if (PyDict_SetItemString(d, "_SSLSocket",
4225 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004226 return;
4227 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4228 PY_SSL_ERROR_ZERO_RETURN);
4229 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4230 PY_SSL_ERROR_WANT_READ);
4231 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4232 PY_SSL_ERROR_WANT_WRITE);
4233 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4234 PY_SSL_ERROR_WANT_X509_LOOKUP);
4235 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4236 PY_SSL_ERROR_SYSCALL);
4237 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4238 PY_SSL_ERROR_SSL);
4239 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4240 PY_SSL_ERROR_WANT_CONNECT);
4241 /* non ssl.h errorcodes */
4242 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4243 PY_SSL_ERROR_EOF);
4244 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4245 PY_SSL_ERROR_INVALID_ERROR_CODE);
4246 /* cert requirements */
4247 PyModule_AddIntConstant(m, "CERT_NONE",
4248 PY_SSL_CERT_NONE);
4249 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4250 PY_SSL_CERT_OPTIONAL);
4251 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4252 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004253 /* CRL verification for verification_flags */
4254 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4255 0);
4256 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4257 X509_V_FLAG_CRL_CHECK);
4258 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4259 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4260 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4261 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004262#ifdef X509_V_FLAG_TRUSTED_FIRST
4263 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4264 X509_V_FLAG_TRUSTED_FIRST);
4265#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004266
4267 /* Alert Descriptions from ssl.h */
4268 /* note RESERVED constants no longer intended for use have been removed */
4269 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4270
4271#define ADD_AD_CONSTANT(s) \
4272 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4273 SSL_AD_##s)
4274
4275 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4276 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4277 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4278 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4279 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4280 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4281 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4282 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4283 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4284 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4285 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4286 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4287 ADD_AD_CONSTANT(UNKNOWN_CA);
4288 ADD_AD_CONSTANT(ACCESS_DENIED);
4289 ADD_AD_CONSTANT(DECODE_ERROR);
4290 ADD_AD_CONSTANT(DECRYPT_ERROR);
4291 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4292 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4293 ADD_AD_CONSTANT(INTERNAL_ERROR);
4294 ADD_AD_CONSTANT(USER_CANCELLED);
4295 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4296 /* Not all constants are in old OpenSSL versions */
4297#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4298 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4299#endif
4300#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4301 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4302#endif
4303#ifdef SSL_AD_UNRECOGNIZED_NAME
4304 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4305#endif
4306#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4307 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4308#endif
4309#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4310 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4311#endif
4312#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4313 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4314#endif
4315
4316#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004317
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004318 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004319#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004320 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4321 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004322#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004323#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004324 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4325 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004326#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004327 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004328 PY_SSL_VERSION_TLS);
4329 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4330 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004331 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4332 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004333#if HAVE_TLSv1_2
4334 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4335 PY_SSL_VERSION_TLS1_1);
4336 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4337 PY_SSL_VERSION_TLS1_2);
4338#endif
4339
4340 /* protocol options */
4341 PyModule_AddIntConstant(m, "OP_ALL",
4342 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4343 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4344 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4345 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4346#if HAVE_TLSv1_2
4347 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4348 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4349#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004350#ifdef SSL_OP_NO_TLSv1_3
4351 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4352#else
4353 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4354#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004355 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4356 SSL_OP_CIPHER_SERVER_PREFERENCE);
4357 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4358#ifdef SSL_OP_SINGLE_ECDH_USE
4359 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4360#endif
4361#ifdef SSL_OP_NO_COMPRESSION
4362 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4363 SSL_OP_NO_COMPRESSION);
4364#endif
4365
4366#if HAVE_SNI
4367 r = Py_True;
4368#else
4369 r = Py_False;
4370#endif
4371 Py_INCREF(r);
4372 PyModule_AddObject(m, "HAS_SNI", r);
4373
4374#if HAVE_OPENSSL_FINISHED
4375 r = Py_True;
4376#else
4377 r = Py_False;
4378#endif
4379 Py_INCREF(r);
4380 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4381
4382#ifdef OPENSSL_NO_ECDH
4383 r = Py_False;
4384#else
4385 r = Py_True;
4386#endif
4387 Py_INCREF(r);
4388 PyModule_AddObject(m, "HAS_ECDH", r);
4389
Christian Heimes3d87f4c2018-02-25 10:21:03 +01004390#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004391 r = Py_True;
4392#else
4393 r = Py_False;
4394#endif
4395 Py_INCREF(r);
4396 PyModule_AddObject(m, "HAS_NPN", r);
4397
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004398#ifdef HAVE_ALPN
4399 r = Py_True;
4400#else
4401 r = Py_False;
4402#endif
4403 Py_INCREF(r);
4404 PyModule_AddObject(m, "HAS_ALPN", r);
4405
Christian Heimesb9a860f2017-09-07 22:31:17 -07004406#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4407 r = Py_True;
4408#else
4409 r = Py_False;
4410#endif
4411 Py_INCREF(r);
4412 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4413
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004414 /* Mappings for error codes */
4415 err_codes_to_names = PyDict_New();
4416 err_names_to_codes = PyDict_New();
4417 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4418 return;
4419 errcode = error_codes;
4420 while (errcode->mnemonic != NULL) {
4421 PyObject *mnemo, *key;
4422 mnemo = PyUnicode_FromString(errcode->mnemonic);
4423 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4424 if (mnemo == NULL || key == NULL)
4425 return;
4426 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4427 return;
4428 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4429 return;
4430 Py_DECREF(key);
4431 Py_DECREF(mnemo);
4432 errcode++;
4433 }
4434 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4435 return;
4436 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4437 return;
4438
4439 lib_codes_to_names = PyDict_New();
4440 if (lib_codes_to_names == NULL)
4441 return;
4442 libcode = library_codes;
4443 while (libcode->library != NULL) {
4444 PyObject *mnemo, *key;
4445 key = PyLong_FromLong(libcode->code);
4446 mnemo = PyUnicode_FromString(libcode->library);
4447 if (key == NULL || mnemo == NULL)
4448 return;
4449 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4450 return;
4451 Py_DECREF(key);
4452 Py_DECREF(mnemo);
4453 libcode++;
4454 }
4455 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4456 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004457
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004458 /* OpenSSL version */
4459 /* SSLeay() gives us the version of the library linked against,
4460 which could be different from the headers version.
4461 */
4462 libver = SSLeay();
4463 r = PyLong_FromUnsignedLong(libver);
4464 if (r == NULL)
4465 return;
4466 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4467 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004468 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004469 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4470 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4471 return;
4472 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4473 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4474 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004475
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004476 libver = OPENSSL_VERSION_NUMBER;
4477 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4478 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4479 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4480 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004481}