blob: af66a581e15a3f99c9d65157d1276cf4ab896b87 [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
613 char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
614#else
615 char packed[sizeof(struct in_addr)];
616#endif /* ENABLE_IPV6 */
617 if (inet_pton(AF_INET, server_hostname, packed)) {
618 send_sni = 0;
619#ifdef ENABLE_IPV6
620 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
621 send_sni = 0;
622#endif /* ENABLE_IPV6 */
623 } else {
624 send_sni = 1;
625 }
626#endif /* HAVE_INET_PTON */
627 if (send_sni) {
628 SSL_set_tlsext_host_name(self->ssl, server_hostname);
629 }
630 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000631#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000632
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000633 /* If the socket is in non-blocking mode or timeout mode, set the BIO
634 * to non-blocking mode (blocking is the default)
635 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500636 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000637 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
638 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
639 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000640
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000641 PySSL_BEGIN_ALLOW_THREADS
642 if (socket_type == PY_SSL_CLIENT)
643 SSL_set_connect_state(self->ssl);
644 else
645 SSL_set_accept_state(self->ssl);
646 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000647
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500648 self->socket_type = socket_type;
649 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000650 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400651 if (ssl_sock != Py_None) {
652 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
653 if (self->ssl_sock == NULL) {
654 Py_DECREF(self);
655 return NULL;
656 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500657 }
658 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000659}
660
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000661
662/* SSL object methods */
663
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500664static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000665{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000666 int ret;
667 int err;
668 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500669 PySocketSockObject *sock = self->Socket;
670
671 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000672
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000673 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500674 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000675 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
676 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000677
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000678 /* Actually negotiate SSL connection */
679 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
680 do {
681 PySSL_BEGIN_ALLOW_THREADS
682 ret = SSL_do_handshake(self->ssl);
683 err = SSL_get_error(self->ssl, ret);
684 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500685 if (PyErr_CheckSignals())
686 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000687 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500688 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000689 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500690 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000691 } else {
692 sockstate = SOCKET_OPERATION_OK;
693 }
694 if (sockstate == SOCKET_HAS_TIMED_OUT) {
695 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000696 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500697 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000698 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
699 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000700 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500701 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000702 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
703 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000704 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500705 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000706 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
707 break;
708 }
709 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500710 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000711 if (ret < 1)
712 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000713
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000714 if (self->peer_cert)
715 X509_free (self->peer_cert);
716 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500717 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000718 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500719 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000720
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000721 Py_INCREF(Py_None);
722 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000723
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500724error:
725 Py_DECREF(sock);
726 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000727}
728
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000729static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200730_asn1obj2py(const ASN1_OBJECT *name, int no_name)
731{
732 char buf[X509_NAME_MAXLEN];
733 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000734 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200735 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000736
Christian Heimesc9d668c2017-09-05 19:13:07 +0200737 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000738 if (buflen < 0) {
739 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200740 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000741 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200742 /* initial buffer is too small for oid + terminating null byte */
743 if (buflen > X509_NAME_MAXLEN - 1) {
744 /* make OBJ_obj2txt() calculate the required buflen */
745 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
746 /* allocate len + 1 for terminating NULL byte */
747 namebuf = PyMem_Malloc(buflen + 1);
748 if (namebuf == NULL) {
749 PyErr_NoMemory();
750 return NULL;
751 }
752 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
753 if (buflen < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto done;
756 }
757 }
758 if (!buflen && no_name) {
759 Py_INCREF(Py_None);
760 name_obj = Py_None;
761 }
762 else {
763 name_obj = PyString_FromStringAndSize(namebuf, buflen);
764 }
765
766 done:
767 if (buf != namebuf) {
768 PyMem_Free(namebuf);
769 }
770 return name_obj;
771}
772
773static PyObject *
774_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
775{
776 Py_ssize_t buflen;
777 unsigned char *valuebuf = NULL;
778 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000779
780 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
781 if (buflen < 0) {
782 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200783 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000784 }
785 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000786 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000787
Christian Heimesc9d668c2017-09-05 19:13:07 +0200788 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
789 OPENSSL_free(valuebuf);
790 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000791}
792
793static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000794_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000795{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000796 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
797 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
798 PyObject *rdnt;
799 PyObject *attr = NULL; /* tuple to hold an attribute */
800 int entry_count = X509_NAME_entry_count(xname);
801 X509_NAME_ENTRY *entry;
802 ASN1_OBJECT *name;
803 ASN1_STRING *value;
804 int index_counter;
805 int rdn_level = -1;
806 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000807
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000808 dn = PyList_New(0);
809 if (dn == NULL)
810 return NULL;
811 /* now create another tuple to hold the top-level RDN */
812 rdn = PyList_New(0);
813 if (rdn == NULL)
814 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000815
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000816 for (index_counter = 0;
817 index_counter < entry_count;
818 index_counter++)
819 {
820 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000821
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000822 /* check to see if we've gotten to a new RDN */
823 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200824 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000825 /* yes, new RDN */
826 /* add old RDN to DN */
827 rdnt = PyList_AsTuple(rdn);
828 Py_DECREF(rdn);
829 if (rdnt == NULL)
830 goto fail0;
831 retcode = PyList_Append(dn, rdnt);
832 Py_DECREF(rdnt);
833 if (retcode < 0)
834 goto fail0;
835 /* create new RDN */
836 rdn = PyList_New(0);
837 if (rdn == NULL)
838 goto fail0;
839 }
840 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200841 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000842
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000843 /* now add this attribute to the current RDN */
844 name = X509_NAME_ENTRY_get_object(entry);
845 value = X509_NAME_ENTRY_get_data(entry);
846 attr = _create_tuple_for_attribute(name, value);
847 /*
848 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
849 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500850 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
851 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000852 */
853 if (attr == NULL)
854 goto fail1;
855 retcode = PyList_Append(rdn, attr);
856 Py_DECREF(attr);
857 if (retcode < 0)
858 goto fail1;
859 }
860 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100861 if (rdn != NULL) {
862 if (PyList_GET_SIZE(rdn) > 0) {
863 rdnt = PyList_AsTuple(rdn);
864 Py_DECREF(rdn);
865 if (rdnt == NULL)
866 goto fail0;
867 retcode = PyList_Append(dn, rdnt);
868 Py_DECREF(rdnt);
869 if (retcode < 0)
870 goto fail0;
871 }
872 else {
873 Py_DECREF(rdn);
874 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000875 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000876
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000877 /* convert list to tuple */
878 rdnt = PyList_AsTuple(dn);
879 Py_DECREF(dn);
880 if (rdnt == NULL)
881 return NULL;
882 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000883
884 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000885 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000886
887 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000888 Py_XDECREF(dn);
889 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000890}
891
892static PyObject *
893_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000894
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000895 /* this code follows the procedure outlined in
896 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
897 function to extract the STACK_OF(GENERAL_NAME),
898 then iterates through the stack to add the
899 names. */
900
901 int i, j;
902 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200903 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000904 X509_EXTENSION *ext = NULL;
905 GENERAL_NAMES *names = NULL;
906 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000907 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000908 BIO *biobuf = NULL;
909 char buf[2048];
910 char *vptr;
911 int len;
912 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000913#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000914 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000915#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000916 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000917#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000918
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000919 if (certificate == NULL)
920 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000921
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000922 /* get a memory buffer */
923 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000924
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200925 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000926 while ((i = X509_get_ext_by_NID(
927 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000928
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000929 if (peer_alt_names == Py_None) {
930 peer_alt_names = PyList_New(0);
931 if (peer_alt_names == NULL)
932 goto fail;
933 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000934
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000935 /* now decode the altName */
936 ext = X509_get_ext(certificate, i);
937 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500938 PyErr_SetString
939 (PySSLErrorObject,
940 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000941 goto fail;
942 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000943
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200944 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000945 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500946 names = (GENERAL_NAMES*)
947 (ASN1_item_d2i(NULL,
948 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200949 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500950 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000951 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500952 names = (GENERAL_NAMES*)
953 (method->d2i(NULL,
954 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200955 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000956
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000957 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000958 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200959 int gntype;
960 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000961
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000962 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200963 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200964 switch (gntype) {
965 case GEN_DIRNAME:
966 /* we special-case DirName as a tuple of
967 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000968
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000969 t = PyTuple_New(2);
970 if (t == NULL) {
971 goto fail;
972 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000973
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000974 v = PyString_FromString("DirName");
975 if (v == NULL) {
976 Py_DECREF(t);
977 goto fail;
978 }
979 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000980
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000981 v = _create_tuple_for_X509_NAME (name->d.dirn);
982 if (v == NULL) {
983 Py_DECREF(t);
984 goto fail;
985 }
986 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200987 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000988
Christian Heimes88b174c2013-08-17 00:54:47 +0200989 case GEN_EMAIL:
990 case GEN_DNS:
991 case GEN_URI:
992 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
993 correctly, CVE-2013-4238 */
994 t = PyTuple_New(2);
995 if (t == NULL)
996 goto fail;
997 switch (gntype) {
998 case GEN_EMAIL:
999 v = PyString_FromString("email");
1000 as = name->d.rfc822Name;
1001 break;
1002 case GEN_DNS:
1003 v = PyString_FromString("DNS");
1004 as = name->d.dNSName;
1005 break;
1006 case GEN_URI:
1007 v = PyString_FromString("URI");
1008 as = name->d.uniformResourceIdentifier;
1009 break;
1010 }
1011 if (v == NULL) {
1012 Py_DECREF(t);
1013 goto fail;
1014 }
1015 PyTuple_SET_ITEM(t, 0, v);
1016 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1017 ASN1_STRING_length(as));
1018 if (v == NULL) {
1019 Py_DECREF(t);
1020 goto fail;
1021 }
1022 PyTuple_SET_ITEM(t, 1, v);
1023 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001024
Christian Heimes6663eb62016-09-06 23:25:35 +02001025 case GEN_RID:
1026 t = PyTuple_New(2);
1027 if (t == NULL)
1028 goto fail;
1029
1030 v = PyUnicode_FromString("Registered ID");
1031 if (v == NULL) {
1032 Py_DECREF(t);
1033 goto fail;
1034 }
1035 PyTuple_SET_ITEM(t, 0, v);
1036
1037 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1038 if (len < 0) {
1039 Py_DECREF(t);
1040 _setSSLError(NULL, 0, __FILE__, __LINE__);
1041 goto fail;
1042 } else if (len >= (int)sizeof(buf)) {
1043 v = PyUnicode_FromString("<INVALID>");
1044 } else {
1045 v = PyUnicode_FromStringAndSize(buf, len);
1046 }
1047 if (v == NULL) {
1048 Py_DECREF(t);
1049 goto fail;
1050 }
1051 PyTuple_SET_ITEM(t, 1, v);
1052 break;
1053
Christian Heimes88b174c2013-08-17 00:54:47 +02001054 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001055 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001056 switch (gntype) {
1057 /* check for new general name type */
1058 case GEN_OTHERNAME:
1059 case GEN_X400:
1060 case GEN_EDIPARTY:
1061 case GEN_IPADD:
1062 case GEN_RID:
1063 break;
1064 default:
1065 if (PyErr_Warn(PyExc_RuntimeWarning,
1066 "Unknown general name type") == -1) {
1067 goto fail;
1068 }
1069 break;
1070 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001071 (void) BIO_reset(biobuf);
1072 GENERAL_NAME_print(biobuf, name);
1073 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1074 if (len < 0) {
1075 _setSSLError(NULL, 0, __FILE__, __LINE__);
1076 goto fail;
1077 }
1078 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001079 if (vptr == NULL) {
1080 PyErr_Format(PyExc_ValueError,
1081 "Invalid value %.200s",
1082 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001083 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001084 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001085 t = PyTuple_New(2);
1086 if (t == NULL)
1087 goto fail;
1088 v = PyString_FromStringAndSize(buf, (vptr - buf));
1089 if (v == NULL) {
1090 Py_DECREF(t);
1091 goto fail;
1092 }
1093 PyTuple_SET_ITEM(t, 0, v);
1094 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1095 if (v == NULL) {
1096 Py_DECREF(t);
1097 goto fail;
1098 }
1099 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001100 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001101 }
1102
1103 /* and add that rendering to the list */
1104
1105 if (PyList_Append(peer_alt_names, t) < 0) {
1106 Py_DECREF(t);
1107 goto fail;
1108 }
1109 Py_DECREF(t);
1110 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001111 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001112 }
1113 BIO_free(biobuf);
1114 if (peer_alt_names != Py_None) {
1115 v = PyList_AsTuple(peer_alt_names);
1116 Py_DECREF(peer_alt_names);
1117 return v;
1118 } else {
1119 return peer_alt_names;
1120 }
1121
Bill Janssen98d19da2007-09-10 21:51:02 +00001122
1123 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001124 if (biobuf != NULL)
1125 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001126
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001127 if (peer_alt_names != Py_None) {
1128 Py_XDECREF(peer_alt_names);
1129 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001130
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001131 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001132}
1133
1134static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001135_get_aia_uri(X509 *certificate, int nid) {
1136 PyObject *lst = NULL, *ostr = NULL;
1137 int i, result;
1138 AUTHORITY_INFO_ACCESS *info;
1139
1140 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001141 if (info == NULL)
1142 return Py_None;
1143 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1144 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001145 return Py_None;
1146 }
1147
1148 if ((lst = PyList_New(0)) == NULL) {
1149 goto fail;
1150 }
1151
1152 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1153 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1154 ASN1_IA5STRING *uri;
1155
1156 if ((OBJ_obj2nid(ad->method) != nid) ||
1157 (ad->location->type != GEN_URI)) {
1158 continue;
1159 }
1160 uri = ad->location->d.uniformResourceIdentifier;
1161 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1162 uri->length);
1163 if (ostr == NULL) {
1164 goto fail;
1165 }
1166 result = PyList_Append(lst, ostr);
1167 Py_DECREF(ostr);
1168 if (result < 0) {
1169 goto fail;
1170 }
1171 }
1172 AUTHORITY_INFO_ACCESS_free(info);
1173
1174 /* convert to tuple or None */
1175 if (PyList_Size(lst) == 0) {
1176 Py_DECREF(lst);
1177 return Py_None;
1178 } else {
1179 PyObject *tup;
1180 tup = PyList_AsTuple(lst);
1181 Py_DECREF(lst);
1182 return tup;
1183 }
1184
1185 fail:
1186 AUTHORITY_INFO_ACCESS_free(info);
1187 Py_XDECREF(lst);
1188 return NULL;
1189}
1190
1191static PyObject *
1192_get_crl_dp(X509 *certificate) {
1193 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001194 int i, j;
1195 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001196
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001197 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001198
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001199 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001200 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001201
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001202 lst = PyList_New(0);
1203 if (lst == NULL)
1204 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001205
1206 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1207 DIST_POINT *dp;
1208 STACK_OF(GENERAL_NAME) *gns;
1209
1210 dp = sk_DIST_POINT_value(dps, i);
1211 gns = dp->distpoint->name.fullname;
1212
1213 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1214 GENERAL_NAME *gn;
1215 ASN1_IA5STRING *uri;
1216 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001217 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001218
1219 gn = sk_GENERAL_NAME_value(gns, j);
1220 if (gn->type != GEN_URI) {
1221 continue;
1222 }
1223 uri = gn->d.uniformResourceIdentifier;
1224 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1225 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001226 if (ouri == NULL)
1227 goto done;
1228
1229 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001230 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001231 if (err < 0)
1232 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001233 }
1234 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001235
1236 /* Convert to tuple. */
1237 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1238
1239 done:
1240 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001241 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001242 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001243}
1244
1245static PyObject *
1246_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001247
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001248 PyObject *retval = NULL;
1249 BIO *biobuf = NULL;
1250 PyObject *peer;
1251 PyObject *peer_alt_names = NULL;
1252 PyObject *issuer;
1253 PyObject *version;
1254 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001255 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001256 ASN1_INTEGER *serialNumber;
1257 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001258 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001259 ASN1_TIME *notBefore, *notAfter;
1260 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001261
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001262 retval = PyDict_New();
1263 if (retval == NULL)
1264 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001265
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001266 peer = _create_tuple_for_X509_NAME(
1267 X509_get_subject_name(certificate));
1268 if (peer == NULL)
1269 goto fail0;
1270 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1271 Py_DECREF(peer);
1272 goto fail0;
1273 }
1274 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001275
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001276 issuer = _create_tuple_for_X509_NAME(
1277 X509_get_issuer_name(certificate));
1278 if (issuer == NULL)
1279 goto fail0;
1280 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001281 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001282 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001283 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001284 Py_DECREF(issuer);
1285
1286 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1287 if (version == NULL)
1288 goto fail0;
1289 if (PyDict_SetItemString(retval, "version", version) < 0) {
1290 Py_DECREF(version);
1291 goto fail0;
1292 }
1293 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001294
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001295 /* get a memory buffer */
1296 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001297
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001298 (void) BIO_reset(biobuf);
1299 serialNumber = X509_get_serialNumber(certificate);
1300 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1301 i2a_ASN1_INTEGER(biobuf, serialNumber);
1302 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1303 if (len < 0) {
1304 _setSSLError(NULL, 0, __FILE__, __LINE__);
1305 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001306 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001307 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1308 if (sn_obj == NULL)
1309 goto fail1;
1310 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1311 Py_DECREF(sn_obj);
1312 goto fail1;
1313 }
1314 Py_DECREF(sn_obj);
1315
1316 (void) BIO_reset(biobuf);
1317 notBefore = X509_get_notBefore(certificate);
1318 ASN1_TIME_print(biobuf, notBefore);
1319 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1320 if (len < 0) {
1321 _setSSLError(NULL, 0, __FILE__, __LINE__);
1322 goto fail1;
1323 }
1324 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1325 if (pnotBefore == NULL)
1326 goto fail1;
1327 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1328 Py_DECREF(pnotBefore);
1329 goto fail1;
1330 }
1331 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001332
1333 (void) BIO_reset(biobuf);
1334 notAfter = X509_get_notAfter(certificate);
1335 ASN1_TIME_print(biobuf, notAfter);
1336 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1337 if (len < 0) {
1338 _setSSLError(NULL, 0, __FILE__, __LINE__);
1339 goto fail1;
1340 }
1341 pnotAfter = PyString_FromStringAndSize(buf, len);
1342 if (pnotAfter == NULL)
1343 goto fail1;
1344 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1345 Py_DECREF(pnotAfter);
1346 goto fail1;
1347 }
1348 Py_DECREF(pnotAfter);
1349
1350 /* Now look for subjectAltName */
1351
1352 peer_alt_names = _get_peer_alt_names(certificate);
1353 if (peer_alt_names == NULL)
1354 goto fail1;
1355 else if (peer_alt_names != Py_None) {
1356 if (PyDict_SetItemString(retval, "subjectAltName",
1357 peer_alt_names) < 0) {
1358 Py_DECREF(peer_alt_names);
1359 goto fail1;
1360 }
1361 Py_DECREF(peer_alt_names);
1362 }
1363
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001364 /* Authority Information Access: OCSP URIs */
1365 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1366 if (obj == NULL) {
1367 goto fail1;
1368 } else if (obj != Py_None) {
1369 result = PyDict_SetItemString(retval, "OCSP", obj);
1370 Py_DECREF(obj);
1371 if (result < 0) {
1372 goto fail1;
1373 }
1374 }
1375
1376 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1377 if (obj == NULL) {
1378 goto fail1;
1379 } else if (obj != Py_None) {
1380 result = PyDict_SetItemString(retval, "caIssuers", obj);
1381 Py_DECREF(obj);
1382 if (result < 0) {
1383 goto fail1;
1384 }
1385 }
1386
1387 /* CDP (CRL distribution points) */
1388 obj = _get_crl_dp(certificate);
1389 if (obj == NULL) {
1390 goto fail1;
1391 } else if (obj != Py_None) {
1392 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1393 Py_DECREF(obj);
1394 if (result < 0) {
1395 goto fail1;
1396 }
1397 }
1398
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001399 BIO_free(biobuf);
1400 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001401
1402 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001403 if (biobuf != NULL)
1404 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001405 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001406 Py_XDECREF(retval);
1407 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001408}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001409
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001410static PyObject *
1411_certificate_to_der(X509 *certificate)
1412{
1413 unsigned char *bytes_buf = NULL;
1414 int len;
1415 PyObject *retval;
1416
1417 bytes_buf = NULL;
1418 len = i2d_X509(certificate, &bytes_buf);
1419 if (len < 0) {
1420 _setSSLError(NULL, 0, __FILE__, __LINE__);
1421 return NULL;
1422 }
1423 /* this is actually an immutable bytes sequence */
1424 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1425 OPENSSL_free(bytes_buf);
1426 return retval;
1427}
Bill Janssen98d19da2007-09-10 21:51:02 +00001428
1429static PyObject *
1430PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1431
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001432 PyObject *retval = NULL;
1433 char *filename = NULL;
1434 X509 *x=NULL;
1435 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001436
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001437 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001438 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001439
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001440 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001441 PyErr_SetString(PySSLErrorObject,
1442 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001443 goto fail0;
1444 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001445
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001446 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001447 PyErr_SetString(PySSLErrorObject,
1448 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001449 goto fail0;
1450 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1453 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001454 PyErr_SetString(PySSLErrorObject,
1455 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001456 goto fail0;
1457 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001458
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001459 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001460 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001461
1462 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001463
1464 if (cert != NULL) BIO_free(cert);
1465 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001466}
1467
1468
1469static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001470PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001471{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001472 int verification;
1473 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001474 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001475
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001476 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1477 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001478
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001479 if (!self->handshake_done) {
1480 PyErr_SetString(PyExc_ValueError,
1481 "handshake not done yet");
1482 return NULL;
1483 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001484 if (!self->peer_cert)
1485 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001486
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001487 b = PyObject_IsTrue(binary_mode);
1488 if (b < 0)
1489 return NULL;
1490 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001491 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001492 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001493 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001494 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001495 if ((verification & SSL_VERIFY_PEER) == 0)
1496 return PyDict_New();
1497 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001498 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001499 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001500}
1501
1502PyDoc_STRVAR(PySSL_peercert_doc,
1503"peer_certificate([der=False]) -> certificate\n\
1504\n\
1505Returns the certificate for the peer. If no certificate was provided,\n\
1506returns None. If a certificate was provided, but not validated, returns\n\
1507an empty dictionary. Otherwise returns a dict containing information\n\
1508about the peer certificate.\n\
1509\n\
1510If the optional argument is True, returns a DER-encoded copy of the\n\
1511peer certificate, or None if no certificate was provided. This will\n\
1512return the certificate even if it wasn't validated.");
1513
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001514static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001515
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001516 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001517 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001518 char *cipher_name;
1519 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001520
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001521 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001522 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001523 current = SSL_get_current_cipher(self->ssl);
1524 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001525 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001526
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001527 retval = PyTuple_New(3);
1528 if (retval == NULL)
1529 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001530
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001531 cipher_name = (char *) SSL_CIPHER_get_name(current);
1532 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001533 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001534 PyTuple_SET_ITEM(retval, 0, Py_None);
1535 } else {
1536 v = PyString_FromString(cipher_name);
1537 if (v == NULL)
1538 goto fail0;
1539 PyTuple_SET_ITEM(retval, 0, v);
1540 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001541 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001542 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001543 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001544 PyTuple_SET_ITEM(retval, 1, Py_None);
1545 } else {
1546 v = PyString_FromString(cipher_protocol);
1547 if (v == NULL)
1548 goto fail0;
1549 PyTuple_SET_ITEM(retval, 1, v);
1550 }
1551 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1552 if (v == NULL)
1553 goto fail0;
1554 PyTuple_SET_ITEM(retval, 2, v);
1555 return retval;
1556
Bill Janssen98d19da2007-09-10 21:51:02 +00001557 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001558 Py_DECREF(retval);
1559 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001560}
1561
Alex Gaynore98205d2014-09-04 13:33:22 -07001562static PyObject *PySSL_version(PySSLSocket *self)
1563{
1564 const char *version;
1565
1566 if (self->ssl == NULL)
1567 Py_RETURN_NONE;
1568 version = SSL_get_version(self->ssl);
1569 if (!strcmp(version, "unknown"))
1570 Py_RETURN_NONE;
1571 return PyUnicode_FromString(version);
1572}
1573
Christian Heimes72ed2332017-09-05 01:11:40 +02001574#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001575static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1576 const unsigned char *out;
1577 unsigned int outlen;
1578
1579 SSL_get0_next_proto_negotiated(self->ssl,
1580 &out, &outlen);
1581
1582 if (out == NULL)
1583 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001584 return PyString_FromStringAndSize((char *)out, outlen);
1585}
1586#endif
1587
1588#ifdef HAVE_ALPN
1589static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1590 const unsigned char *out;
1591 unsigned int outlen;
1592
1593 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1594
1595 if (out == NULL)
1596 Py_RETURN_NONE;
1597 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001598}
1599#endif
1600
1601static PyObject *PySSL_compression(PySSLSocket *self) {
1602#ifdef OPENSSL_NO_COMP
1603 Py_RETURN_NONE;
1604#else
1605 const COMP_METHOD *comp_method;
1606 const char *short_name;
1607
1608 if (self->ssl == NULL)
1609 Py_RETURN_NONE;
1610 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001611 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001612 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001613 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001614 if (short_name == NULL)
1615 Py_RETURN_NONE;
1616 return PyBytes_FromString(short_name);
1617#endif
1618}
1619
1620static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1621 Py_INCREF(self->ctx);
1622 return self->ctx;
1623}
1624
1625static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1626 void *closure) {
1627
1628 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1629#if !HAVE_SNI
1630 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1631 "context is not supported by your OpenSSL library");
1632 return -1;
1633#else
1634 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001635 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001636 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1637#endif
1638 } else {
1639 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1640 return -1;
1641 }
1642
1643 return 0;
1644}
1645
1646PyDoc_STRVAR(PySSL_set_context_doc,
1647"_setter_context(ctx)\n\
1648\
1649This changes the context associated with the SSLSocket. This is typically\n\
1650used from within a callback function set by the set_servername_callback\n\
1651on the SSLContext to change the certificate information associated with the\n\
1652SSLSocket before the cryptographic exchange handshake messages\n");
1653
1654
1655
1656static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001657{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001658 if (self->peer_cert) /* Possible not to have one? */
1659 X509_free (self->peer_cert);
1660 if (self->ssl)
1661 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001662 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001663 Py_XDECREF(self->ssl_sock);
1664 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001665 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001666}
1667
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001668/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001669 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001670 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001671 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001672
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001673static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001674check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001675{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001676 fd_set fds;
1677 struct timeval tv;
1678 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001679
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001680 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1681 if (s->sock_timeout < 0.0)
1682 return SOCKET_IS_BLOCKING;
1683 else if (s->sock_timeout == 0.0)
1684 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001685
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001686 /* Guard against closed socket */
1687 if (s->sock_fd < 0)
1688 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001689
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001690 /* Prefer poll, if available, since you can poll() any fd
1691 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001692#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001693 {
1694 struct pollfd pollfd;
1695 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001696
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001697 pollfd.fd = s->sock_fd;
1698 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001699
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001700 /* s->sock_timeout is in seconds, timeout in ms */
1701 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1702 PySSL_BEGIN_ALLOW_THREADS
1703 rc = poll(&pollfd, 1, timeout);
1704 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001705
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001706 goto normal_return;
1707 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001708#endif
1709
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001710 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001711 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001712 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001713
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001714 /* Construct the arguments to select */
1715 tv.tv_sec = (int)s->sock_timeout;
1716 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1717 FD_ZERO(&fds);
1718 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001719
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 /* See if the socket is ready */
1721 PySSL_BEGIN_ALLOW_THREADS
1722 if (writing)
1723 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1724 else
1725 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1726 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001727
Bill Janssen934b16d2008-06-28 22:19:33 +00001728#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001729normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001730#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001731 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1732 (when we are able to write or when there's something to read) */
1733 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001734}
1735
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001736static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001737{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001738 Py_buffer buf;
1739 int len;
1740 int sockstate;
1741 int err;
1742 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001743 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001744
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001745 Py_INCREF(sock);
1746
1747 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1748 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001749 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001750 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001751
Victor Stinnerc1a44262013-06-25 00:48:02 +02001752 if (buf.len > INT_MAX) {
1753 PyErr_Format(PyExc_OverflowError,
1754 "string longer than %d bytes", INT_MAX);
1755 goto error;
1756 }
1757
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001758 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001759 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001760 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1761 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001762
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001763 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001764 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1765 PyErr_SetString(PySSLErrorObject,
1766 "The write operation timed out");
1767 goto error;
1768 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1769 PyErr_SetString(PySSLErrorObject,
1770 "Underlying socket has been closed.");
1771 goto error;
1772 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1773 PyErr_SetString(PySSLErrorObject,
1774 "Underlying socket too large for select().");
1775 goto error;
1776 }
1777 do {
1778 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001779 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001780 err = SSL_get_error(self->ssl, len);
1781 PySSL_END_ALLOW_THREADS
1782 if (PyErr_CheckSignals()) {
1783 goto error;
1784 }
1785 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001786 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001787 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001788 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001789 } else {
1790 sockstate = SOCKET_OPERATION_OK;
1791 }
1792 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1793 PyErr_SetString(PySSLErrorObject,
1794 "The write operation timed out");
1795 goto error;
1796 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1797 PyErr_SetString(PySSLErrorObject,
1798 "Underlying socket has been closed.");
1799 goto error;
1800 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1801 break;
1802 }
1803 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001804
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001805 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001806 PyBuffer_Release(&buf);
1807 if (len > 0)
1808 return PyInt_FromLong(len);
1809 else
1810 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001811
1812error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001813 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001814 PyBuffer_Release(&buf);
1815 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001816}
1817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001818PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001819"write(s) -> len\n\
1820\n\
1821Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001822of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001823
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001824static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001825{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001826 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001827
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001828 PySSL_BEGIN_ALLOW_THREADS
1829 count = SSL_pending(self->ssl);
1830 PySSL_END_ALLOW_THREADS
1831 if (count < 0)
1832 return PySSL_SetError(self, count, __FILE__, __LINE__);
1833 else
1834 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001835}
1836
1837PyDoc_STRVAR(PySSL_SSLpending_doc,
1838"pending() -> count\n\
1839\n\
1840Returns the number of already decrypted bytes available for read,\n\
1841pending on the connection.\n");
1842
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001843static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001844{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001845 PyObject *dest = NULL;
1846 Py_buffer buf;
1847 char *mem;
1848 int len, count;
1849 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001850 int sockstate;
1851 int err;
1852 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001853 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001854
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001855 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001856
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001857 buf.obj = NULL;
1858 buf.buf = NULL;
1859 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1860 goto error;
1861
1862 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001863 if (len < 0) {
1864 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1865 goto error;
1866 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001867 dest = PyBytes_FromStringAndSize(NULL, len);
1868 if (dest == NULL)
1869 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001870 if (len == 0) {
1871 Py_XDECREF(sock);
1872 return dest;
1873 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001874 mem = PyBytes_AS_STRING(dest);
1875 }
1876 else {
1877 buf_passed = 1;
1878 mem = buf.buf;
1879 if (len <= 0 || len > buf.len) {
1880 len = (int) buf.len;
1881 if (buf.len != len) {
1882 PyErr_SetString(PyExc_OverflowError,
1883 "maximum length can't fit in a C 'int'");
1884 goto error;
1885 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001886 if (len == 0) {
1887 count = 0;
1888 goto done;
1889 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001890 }
1891 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001893 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001894 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001895 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1896 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001897
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001898 do {
1899 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001900 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001901 err = SSL_get_error(self->ssl, count);
1902 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001903 if (PyErr_CheckSignals())
1904 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001905 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001906 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001908 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001909 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1910 (SSL_get_shutdown(self->ssl) ==
1911 SSL_RECEIVED_SHUTDOWN))
1912 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001913 count = 0;
1914 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001915 } else {
1916 sockstate = SOCKET_OPERATION_OK;
1917 }
1918 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1919 PyErr_SetString(PySSLErrorObject,
1920 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001921 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001922 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1923 break;
1924 }
1925 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1926 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001927 PySSL_SetError(self, count, __FILE__, __LINE__);
1928 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001929 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001930
1931done:
1932 Py_DECREF(sock);
1933 if (!buf_passed) {
1934 _PyBytes_Resize(&dest, count);
1935 return dest;
1936 }
1937 else {
1938 PyBuffer_Release(&buf);
1939 return PyLong_FromLong(count);
1940 }
1941
1942error:
1943 Py_DECREF(sock);
1944 if (!buf_passed)
1945 Py_XDECREF(dest);
1946 else
1947 PyBuffer_Release(&buf);
1948 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001949}
1950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001951PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001952"read([len]) -> string\n\
1953\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001954Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001955
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001956static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001957{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001958 int err, ssl_err, sockstate, nonblocking;
1959 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001960 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001961
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001962 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001963 if (sock->sock_fd < 0) {
1964 _setSSLError("Underlying socket connection gone",
1965 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001966 return NULL;
1967 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001968 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001969
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001970 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001971 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001972 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1973 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001974
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001975 while (1) {
1976 PySSL_BEGIN_ALLOW_THREADS
1977 /* Disable read-ahead so that unwrap can work correctly.
1978 * Otherwise OpenSSL might read in too much data,
1979 * eating clear text data that happens to be
1980 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001981 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001982 * function is used and the shutdown_seen_zero != 0
1983 * condition is met.
1984 */
1985 if (self->shutdown_seen_zero)
1986 SSL_set_read_ahead(self->ssl, 0);
1987 err = SSL_shutdown(self->ssl);
1988 PySSL_END_ALLOW_THREADS
1989 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1990 if (err > 0)
1991 break;
1992 if (err == 0) {
1993 /* Don't loop endlessly; instead preserve legacy
1994 behaviour of trying SSL_shutdown() only twice.
1995 This looks necessary for OpenSSL < 0.9.8m */
1996 if (++zeros > 1)
1997 break;
1998 /* Shutdown was sent, now try receiving */
1999 self->shutdown_seen_zero = 1;
2000 continue;
2001 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00002002
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002003 /* Possibly retry shutdown until timeout or failure */
2004 ssl_err = SSL_get_error(self->ssl, err);
2005 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002006 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002007 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002008 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002009 else
2010 break;
2011 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2012 if (ssl_err == SSL_ERROR_WANT_READ)
2013 PyErr_SetString(PySSLErrorObject,
2014 "The read operation timed out");
2015 else
2016 PyErr_SetString(PySSLErrorObject,
2017 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002018 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002019 }
2020 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2021 PyErr_SetString(PySSLErrorObject,
2022 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002023 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002024 }
2025 else if (sockstate != SOCKET_OPERATION_OK)
2026 /* Retain the SSL error code */
2027 break;
2028 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002029
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002030 if (err < 0) {
2031 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002032 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002033 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002034 else
2035 /* It's already INCREF'ed */
2036 return (PyObject *) sock;
2037
2038error:
2039 Py_DECREF(sock);
2040 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002041}
2042
2043PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2044"shutdown(s) -> socket\n\
2045\n\
2046Does the SSL shutdown handshake with the remote end, and returns\n\
2047the underlying socket object.");
2048
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002049#if HAVE_OPENSSL_FINISHED
2050static PyObject *
2051PySSL_tls_unique_cb(PySSLSocket *self)
2052{
2053 PyObject *retval = NULL;
2054 char buf[PySSL_CB_MAXLEN];
2055 size_t len;
2056
2057 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2058 /* if session is resumed XOR we are the client */
2059 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2060 }
2061 else {
2062 /* if a new session XOR we are the server */
2063 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2064 }
2065
2066 /* It cannot be negative in current OpenSSL version as of July 2011 */
2067 if (len == 0)
2068 Py_RETURN_NONE;
2069
2070 retval = PyBytes_FromStringAndSize(buf, len);
2071
2072 return retval;
2073}
2074
2075PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2076"tls_unique_cb() -> bytes\n\
2077\n\
2078Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2079\n\
2080If the TLS handshake is not yet complete, None is returned");
2081
2082#endif /* HAVE_OPENSSL_FINISHED */
2083
2084static PyGetSetDef ssl_getsetlist[] = {
2085 {"context", (getter) PySSL_get_context,
2086 (setter) PySSL_set_context, PySSL_set_context_doc},
2087 {NULL}, /* sentinel */
2088};
2089
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002090static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002091 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2092 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2093 PySSL_SSLwrite_doc},
2094 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2095 PySSL_SSLread_doc},
2096 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2097 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002098 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2099 PySSL_peercert_doc},
2100 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002101 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002102#ifdef OPENSSL_NPN_NEGOTIATED
2103 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2104#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002105#ifdef HAVE_ALPN
2106 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2107#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002108 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002109 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2110 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002111#if HAVE_OPENSSL_FINISHED
2112 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2113 PySSL_tls_unique_cb_doc},
2114#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002115 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002116};
2117
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002118static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002119 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002120 "_ssl._SSLSocket", /*tp_name*/
2121 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002122 0, /*tp_itemsize*/
2123 /* methods */
2124 (destructor)PySSL_dealloc, /*tp_dealloc*/
2125 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002126 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002127 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002128 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002129 0, /*tp_repr*/
2130 0, /*tp_as_number*/
2131 0, /*tp_as_sequence*/
2132 0, /*tp_as_mapping*/
2133 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002134 0, /*tp_call*/
2135 0, /*tp_str*/
2136 0, /*tp_getattro*/
2137 0, /*tp_setattro*/
2138 0, /*tp_as_buffer*/
2139 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2140 0, /*tp_doc*/
2141 0, /*tp_traverse*/
2142 0, /*tp_clear*/
2143 0, /*tp_richcompare*/
2144 0, /*tp_weaklistoffset*/
2145 0, /*tp_iter*/
2146 0, /*tp_iternext*/
2147 PySSLMethods, /*tp_methods*/
2148 0, /*tp_members*/
2149 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002150};
2151
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002152
2153/*
2154 * _SSLContext objects
2155 */
2156
2157static PyObject *
2158context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2159{
2160 char *kwlist[] = {"protocol", NULL};
2161 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002162 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002163 long options;
2164 SSL_CTX *ctx = NULL;
2165
2166 if (!PyArg_ParseTupleAndKeywords(
2167 args, kwds, "i:_SSLContext", kwlist,
2168 &proto_version))
2169 return NULL;
2170
2171 PySSL_BEGIN_ALLOW_THREADS
2172 if (proto_version == PY_SSL_VERSION_TLS1)
2173 ctx = SSL_CTX_new(TLSv1_method());
2174#if HAVE_TLSv1_2
2175 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2176 ctx = SSL_CTX_new(TLSv1_1_method());
2177 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2178 ctx = SSL_CTX_new(TLSv1_2_method());
2179#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002180#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002181 else if (proto_version == PY_SSL_VERSION_SSL3)
2182 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002183#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002184#ifndef OPENSSL_NO_SSL2
2185 else if (proto_version == PY_SSL_VERSION_SSL2)
2186 ctx = SSL_CTX_new(SSLv2_method());
2187#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002188 else if (proto_version == PY_SSL_VERSION_TLS)
2189 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002190 else
2191 proto_version = -1;
2192 PySSL_END_ALLOW_THREADS
2193
2194 if (proto_version == -1) {
2195 PyErr_SetString(PyExc_ValueError,
2196 "invalid protocol version");
2197 return NULL;
2198 }
2199 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002200 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002201 return NULL;
2202 }
2203
2204 assert(type != NULL && type->tp_alloc != NULL);
2205 self = (PySSLContext *) type->tp_alloc(type, 0);
2206 if (self == NULL) {
2207 SSL_CTX_free(ctx);
2208 return NULL;
2209 }
2210 self->ctx = ctx;
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002211#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002212 self->npn_protocols = NULL;
2213#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002214#ifdef HAVE_ALPN
2215 self->alpn_protocols = NULL;
2216#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002217#ifndef OPENSSL_NO_TLSEXT
2218 self->set_hostname = NULL;
2219#endif
2220 /* Don't check host name by default */
2221 self->check_hostname = 0;
2222 /* Defaults */
2223 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2224 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2225 if (proto_version != PY_SSL_VERSION_SSL2)
2226 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002227 if (proto_version != PY_SSL_VERSION_SSL3)
2228 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002229 SSL_CTX_set_options(self->ctx, options);
2230
Donald Stufftf1a696e2017-03-02 12:37:07 -05002231#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002232 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2233 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002234 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2235 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002236#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002237 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2238#else
2239 {
2240 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2241 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2242 EC_KEY_free(key);
2243 }
2244#endif
2245#endif
2246
2247#define SID_CTX "Python"
2248 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2249 sizeof(SID_CTX));
2250#undef SID_CTX
2251
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002252#ifdef X509_V_FLAG_TRUSTED_FIRST
2253 {
2254 /* Improve trust chain building when cross-signed intermediate
2255 certificates are present. See https://bugs.python.org/issue23476. */
2256 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2257 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2258 }
2259#endif
2260
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002261 return (PyObject *)self;
2262}
2263
2264static int
2265context_traverse(PySSLContext *self, visitproc visit, void *arg)
2266{
2267#ifndef OPENSSL_NO_TLSEXT
2268 Py_VISIT(self->set_hostname);
2269#endif
2270 return 0;
2271}
2272
2273static int
2274context_clear(PySSLContext *self)
2275{
2276#ifndef OPENSSL_NO_TLSEXT
2277 Py_CLEAR(self->set_hostname);
2278#endif
2279 return 0;
2280}
2281
2282static void
2283context_dealloc(PySSLContext *self)
2284{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002285 /* bpo-31095: UnTrack is needed before calling any callbacks */
2286 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002287 context_clear(self);
2288 SSL_CTX_free(self->ctx);
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002289#ifdef HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002290 PyMem_FREE(self->npn_protocols);
2291#endif
2292#ifdef HAVE_ALPN
2293 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002294#endif
2295 Py_TYPE(self)->tp_free(self);
2296}
2297
2298static PyObject *
2299set_ciphers(PySSLContext *self, PyObject *args)
2300{
2301 int ret;
2302 const char *cipherlist;
2303
2304 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2305 return NULL;
2306 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2307 if (ret == 0) {
2308 /* Clearing the error queue is necessary on some OpenSSL versions,
2309 otherwise the error will be reported again when another SSL call
2310 is done. */
2311 ERR_clear_error();
2312 PyErr_SetString(PySSLErrorObject,
2313 "No cipher can be selected.");
2314 return NULL;
2315 }
2316 Py_RETURN_NONE;
2317}
2318
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002319#if defined(HAVE_NPN) || defined(HAVE_ALPN)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002320static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002321do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2322 const unsigned char *server_protocols, unsigned int server_protocols_len,
2323 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002324{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002325 int ret;
2326 if (client_protocols == NULL) {
2327 client_protocols = (unsigned char *)"";
2328 client_protocols_len = 0;
2329 }
2330 if (server_protocols == NULL) {
2331 server_protocols = (unsigned char *)"";
2332 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002333 }
2334
Benjamin Petersonaa707582015-01-23 17:30:26 -05002335 ret = SSL_select_next_proto(out, outlen,
2336 server_protocols, server_protocols_len,
2337 client_protocols, client_protocols_len);
2338 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2339 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002340
2341 return SSL_TLSEXT_ERR_OK;
2342}
Christian Heimes72ed2332017-09-05 01:11:40 +02002343#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002344
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002345#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002346/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2347static int
2348_advertiseNPN_cb(SSL *s,
2349 const unsigned char **data, unsigned int *len,
2350 void *args)
2351{
2352 PySSLContext *ssl_ctx = (PySSLContext *) args;
2353
2354 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002355 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002356 *len = 0;
2357 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002358 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002359 *len = ssl_ctx->npn_protocols_len;
2360 }
2361
2362 return SSL_TLSEXT_ERR_OK;
2363}
2364/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2365static int
2366_selectNPN_cb(SSL *s,
2367 unsigned char **out, unsigned char *outlen,
2368 const unsigned char *server, unsigned int server_len,
2369 void *args)
2370{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002371 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002372 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002373 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002374}
2375#endif
2376
2377static PyObject *
2378_set_npn_protocols(PySSLContext *self, PyObject *args)
2379{
Christian Heimes3d87f4c2018-02-25 10:21:03 +01002380#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002381 Py_buffer protos;
2382
2383 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2384 return NULL;
2385
2386 if (self->npn_protocols != NULL) {
2387 PyMem_Free(self->npn_protocols);
2388 }
2389
2390 self->npn_protocols = PyMem_Malloc(protos.len);
2391 if (self->npn_protocols == NULL) {
2392 PyBuffer_Release(&protos);
2393 return PyErr_NoMemory();
2394 }
2395 memcpy(self->npn_protocols, protos.buf, protos.len);
2396 self->npn_protocols_len = (int) protos.len;
2397
2398 /* set both server and client callbacks, because the context can
2399 * be used to create both types of sockets */
2400 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2401 _advertiseNPN_cb,
2402 self);
2403 SSL_CTX_set_next_proto_select_cb(self->ctx,
2404 _selectNPN_cb,
2405 self);
2406
2407 PyBuffer_Release(&protos);
2408 Py_RETURN_NONE;
2409#else
2410 PyErr_SetString(PyExc_NotImplementedError,
2411 "The NPN extension requires OpenSSL 1.0.1 or later.");
2412 return NULL;
2413#endif
2414}
2415
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002416#ifdef HAVE_ALPN
2417static int
2418_selectALPN_cb(SSL *s,
2419 const unsigned char **out, unsigned char *outlen,
2420 const unsigned char *client_protocols, unsigned int client_protocols_len,
2421 void *args)
2422{
2423 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002424 return do_protocol_selection(1, (unsigned char **)out, outlen,
2425 ctx->alpn_protocols, ctx->alpn_protocols_len,
2426 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002427}
2428#endif
2429
2430static PyObject *
2431_set_alpn_protocols(PySSLContext *self, PyObject *args)
2432{
2433#ifdef HAVE_ALPN
2434 Py_buffer protos;
2435
2436 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2437 return NULL;
2438
2439 PyMem_FREE(self->alpn_protocols);
2440 self->alpn_protocols = PyMem_Malloc(protos.len);
2441 if (!self->alpn_protocols)
2442 return PyErr_NoMemory();
2443 memcpy(self->alpn_protocols, protos.buf, protos.len);
2444 self->alpn_protocols_len = protos.len;
2445 PyBuffer_Release(&protos);
2446
2447 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2448 return PyErr_NoMemory();
2449 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2450
2451 PyBuffer_Release(&protos);
2452 Py_RETURN_NONE;
2453#else
2454 PyErr_SetString(PyExc_NotImplementedError,
2455 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2456 return NULL;
2457#endif
2458}
2459
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002460static PyObject *
2461get_verify_mode(PySSLContext *self, void *c)
2462{
2463 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2464 case SSL_VERIFY_NONE:
2465 return PyLong_FromLong(PY_SSL_CERT_NONE);
2466 case SSL_VERIFY_PEER:
2467 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2468 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2469 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2470 }
2471 PyErr_SetString(PySSLErrorObject,
2472 "invalid return value from SSL_CTX_get_verify_mode");
2473 return NULL;
2474}
2475
2476static int
2477set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2478{
2479 int n, mode;
2480 if (!PyArg_Parse(arg, "i", &n))
2481 return -1;
2482 if (n == PY_SSL_CERT_NONE)
2483 mode = SSL_VERIFY_NONE;
2484 else if (n == PY_SSL_CERT_OPTIONAL)
2485 mode = SSL_VERIFY_PEER;
2486 else if (n == PY_SSL_CERT_REQUIRED)
2487 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2488 else {
2489 PyErr_SetString(PyExc_ValueError,
2490 "invalid value for verify_mode");
2491 return -1;
2492 }
2493 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2494 PyErr_SetString(PyExc_ValueError,
2495 "Cannot set verify_mode to CERT_NONE when "
2496 "check_hostname is enabled.");
2497 return -1;
2498 }
2499 SSL_CTX_set_verify(self->ctx, mode, NULL);
2500 return 0;
2501}
2502
2503#ifdef HAVE_OPENSSL_VERIFY_PARAM
2504static PyObject *
2505get_verify_flags(PySSLContext *self, void *c)
2506{
2507 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002508 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002509 unsigned long flags;
2510
2511 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002512 param = X509_STORE_get0_param(store);
2513 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002514 return PyLong_FromUnsignedLong(flags);
2515}
2516
2517static int
2518set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2519{
2520 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002521 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002522 unsigned long new_flags, flags, set, clear;
2523
2524 if (!PyArg_Parse(arg, "k", &new_flags))
2525 return -1;
2526 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002527 param = X509_STORE_get0_param(store);
2528 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002529 clear = flags & ~new_flags;
2530 set = ~flags & new_flags;
2531 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002532 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002533 _setSSLError(NULL, 0, __FILE__, __LINE__);
2534 return -1;
2535 }
2536 }
2537 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002538 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002539 _setSSLError(NULL, 0, __FILE__, __LINE__);
2540 return -1;
2541 }
2542 }
2543 return 0;
2544}
2545#endif
2546
2547static PyObject *
2548get_options(PySSLContext *self, void *c)
2549{
2550 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2551}
2552
2553static int
2554set_options(PySSLContext *self, PyObject *arg, void *c)
2555{
2556 long new_opts, opts, set, clear;
2557 if (!PyArg_Parse(arg, "l", &new_opts))
2558 return -1;
2559 opts = SSL_CTX_get_options(self->ctx);
2560 clear = opts & ~new_opts;
2561 set = ~opts & new_opts;
2562 if (clear) {
2563#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2564 SSL_CTX_clear_options(self->ctx, clear);
2565#else
2566 PyErr_SetString(PyExc_ValueError,
2567 "can't clear options before OpenSSL 0.9.8m");
2568 return -1;
2569#endif
2570 }
2571 if (set)
2572 SSL_CTX_set_options(self->ctx, set);
2573 return 0;
2574}
2575
2576static PyObject *
2577get_check_hostname(PySSLContext *self, void *c)
2578{
2579 return PyBool_FromLong(self->check_hostname);
2580}
2581
2582static int
2583set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2584{
2585 PyObject *py_check_hostname;
2586 int check_hostname;
2587 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2588 return -1;
2589
2590 check_hostname = PyObject_IsTrue(py_check_hostname);
2591 if (check_hostname < 0)
2592 return -1;
2593 if (check_hostname &&
2594 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2595 PyErr_SetString(PyExc_ValueError,
2596 "check_hostname needs a SSL context with either "
2597 "CERT_OPTIONAL or CERT_REQUIRED");
2598 return -1;
2599 }
2600 self->check_hostname = check_hostname;
2601 return 0;
2602}
2603
2604
2605typedef struct {
2606 PyThreadState *thread_state;
2607 PyObject *callable;
2608 char *password;
2609 int size;
2610 int error;
2611} _PySSLPasswordInfo;
2612
2613static int
2614_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2615 const char *bad_type_error)
2616{
2617 /* Set the password and size fields of a _PySSLPasswordInfo struct
2618 from a unicode, bytes, or byte array object.
2619 The password field will be dynamically allocated and must be freed
2620 by the caller */
2621 PyObject *password_bytes = NULL;
2622 const char *data = NULL;
2623 Py_ssize_t size;
2624
2625 if (PyUnicode_Check(password)) {
2626 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2627 if (!password_bytes) {
2628 goto error;
2629 }
2630 data = PyBytes_AS_STRING(password_bytes);
2631 size = PyBytes_GET_SIZE(password_bytes);
2632 } else if (PyBytes_Check(password)) {
2633 data = PyBytes_AS_STRING(password);
2634 size = PyBytes_GET_SIZE(password);
2635 } else if (PyByteArray_Check(password)) {
2636 data = PyByteArray_AS_STRING(password);
2637 size = PyByteArray_GET_SIZE(password);
2638 } else {
2639 PyErr_SetString(PyExc_TypeError, bad_type_error);
2640 goto error;
2641 }
2642
2643 if (size > (Py_ssize_t)INT_MAX) {
2644 PyErr_Format(PyExc_ValueError,
2645 "password cannot be longer than %d bytes", INT_MAX);
2646 goto error;
2647 }
2648
2649 PyMem_Free(pw_info->password);
2650 pw_info->password = PyMem_Malloc(size);
2651 if (!pw_info->password) {
2652 PyErr_SetString(PyExc_MemoryError,
2653 "unable to allocate password buffer");
2654 goto error;
2655 }
2656 memcpy(pw_info->password, data, size);
2657 pw_info->size = (int)size;
2658
2659 Py_XDECREF(password_bytes);
2660 return 1;
2661
2662error:
2663 Py_XDECREF(password_bytes);
2664 return 0;
2665}
2666
2667static int
2668_password_callback(char *buf, int size, int rwflag, void *userdata)
2669{
2670 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2671 PyObject *fn_ret = NULL;
2672
2673 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2674
2675 if (pw_info->callable) {
2676 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2677 if (!fn_ret) {
2678 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2679 core python API, so we could use it to add a frame here */
2680 goto error;
2681 }
2682
2683 if (!_pwinfo_set(pw_info, fn_ret,
2684 "password callback must return a string")) {
2685 goto error;
2686 }
2687 Py_CLEAR(fn_ret);
2688 }
2689
2690 if (pw_info->size > size) {
2691 PyErr_Format(PyExc_ValueError,
2692 "password cannot be longer than %d bytes", size);
2693 goto error;
2694 }
2695
2696 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2697 memcpy(buf, pw_info->password, pw_info->size);
2698 return pw_info->size;
2699
2700error:
2701 Py_XDECREF(fn_ret);
2702 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2703 pw_info->error = 1;
2704 return -1;
2705}
2706
2707static PyObject *
2708load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2709{
2710 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002711 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2712 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002713 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2714 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002715 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2716 int r;
2717
2718 errno = 0;
2719 ERR_clear_error();
2720 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002721 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002722 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002723 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002724 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002725
2726 if (keyfile && keyfile != Py_None) {
2727 if (PyString_Check(keyfile)) {
2728 Py_INCREF(keyfile);
2729 keyfile_bytes = keyfile;
2730 } else {
2731 PyObject *u = PyUnicode_FromObject(keyfile);
2732 if (!u)
2733 goto error;
2734 keyfile_bytes = PyUnicode_AsEncodedString(
2735 u, Py_FileSystemDefaultEncoding, NULL);
2736 Py_DECREF(u);
2737 if (!keyfile_bytes)
2738 goto error;
2739 }
2740 }
2741
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002742 if (password && password != Py_None) {
2743 if (PyCallable_Check(password)) {
2744 pw_info.callable = password;
2745 } else if (!_pwinfo_set(&pw_info, password,
2746 "password should be a string or callable")) {
2747 goto error;
2748 }
2749 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2750 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2751 }
2752 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2753 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2754 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2755 if (r != 1) {
2756 if (pw_info.error) {
2757 ERR_clear_error();
2758 /* the password callback has already set the error information */
2759 }
2760 else if (errno != 0) {
2761 ERR_clear_error();
2762 PyErr_SetFromErrno(PyExc_IOError);
2763 }
2764 else {
2765 _setSSLError(NULL, 0, __FILE__, __LINE__);
2766 }
2767 goto error;
2768 }
2769 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2770 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002771 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002772 SSL_FILETYPE_PEM);
2773 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2774 if (r != 1) {
2775 if (pw_info.error) {
2776 ERR_clear_error();
2777 /* the password callback has already set the error information */
2778 }
2779 else if (errno != 0) {
2780 ERR_clear_error();
2781 PyErr_SetFromErrno(PyExc_IOError);
2782 }
2783 else {
2784 _setSSLError(NULL, 0, __FILE__, __LINE__);
2785 }
2786 goto error;
2787 }
2788 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2789 r = SSL_CTX_check_private_key(self->ctx);
2790 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2791 if (r != 1) {
2792 _setSSLError(NULL, 0, __FILE__, __LINE__);
2793 goto error;
2794 }
2795 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2796 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002797 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002798 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002799 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002800 Py_RETURN_NONE;
2801
2802error:
2803 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2804 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002805 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002806 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002807 PyMem_Free(certfile_bytes);
2808 return NULL;
2809}
2810
2811/* internal helper function, returns -1 on error
2812 */
2813static int
2814_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2815 int filetype)
2816{
2817 BIO *biobuf = NULL;
2818 X509_STORE *store;
2819 int retval = 0, err, loaded = 0;
2820
2821 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2822
2823 if (len <= 0) {
2824 PyErr_SetString(PyExc_ValueError,
2825 "Empty certificate data");
2826 return -1;
2827 } else if (len > INT_MAX) {
2828 PyErr_SetString(PyExc_OverflowError,
2829 "Certificate data is too long.");
2830 return -1;
2831 }
2832
2833 biobuf = BIO_new_mem_buf(data, (int)len);
2834 if (biobuf == NULL) {
2835 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2836 return -1;
2837 }
2838
2839 store = SSL_CTX_get_cert_store(self->ctx);
2840 assert(store != NULL);
2841
2842 while (1) {
2843 X509 *cert = NULL;
2844 int r;
2845
2846 if (filetype == SSL_FILETYPE_ASN1) {
2847 cert = d2i_X509_bio(biobuf, NULL);
2848 } else {
2849 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002850 SSL_CTX_get_default_passwd_cb(self->ctx),
2851 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2852 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002853 }
2854 if (cert == NULL) {
2855 break;
2856 }
2857 r = X509_STORE_add_cert(store, cert);
2858 X509_free(cert);
2859 if (!r) {
2860 err = ERR_peek_last_error();
2861 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2862 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2863 /* cert already in hash table, not an error */
2864 ERR_clear_error();
2865 } else {
2866 break;
2867 }
2868 }
2869 loaded++;
2870 }
2871
2872 err = ERR_peek_last_error();
2873 if ((filetype == SSL_FILETYPE_ASN1) &&
2874 (loaded > 0) &&
2875 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2876 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2877 /* EOF ASN1 file, not an error */
2878 ERR_clear_error();
2879 retval = 0;
2880 } else if ((filetype == SSL_FILETYPE_PEM) &&
2881 (loaded > 0) &&
2882 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2883 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2884 /* EOF PEM file, not an error */
2885 ERR_clear_error();
2886 retval = 0;
2887 } else {
2888 _setSSLError(NULL, 0, __FILE__, __LINE__);
2889 retval = -1;
2890 }
2891
2892 BIO_free(biobuf);
2893 return retval;
2894}
2895
2896
2897static PyObject *
2898load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2899{
2900 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2901 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2902 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2903 const char *cafile_buf = NULL, *capath_buf = NULL;
2904 int r = 0, ok = 1;
2905
2906 errno = 0;
2907 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2908 "|OOO:load_verify_locations", kwlist,
2909 &cafile, &capath, &cadata))
2910 return NULL;
2911
2912 if (cafile == Py_None)
2913 cafile = NULL;
2914 if (capath == Py_None)
2915 capath = NULL;
2916 if (cadata == Py_None)
2917 cadata = NULL;
2918
2919 if (cafile == NULL && capath == NULL && cadata == NULL) {
2920 PyErr_SetString(PyExc_TypeError,
2921 "cafile, capath and cadata cannot be all omitted");
2922 goto error;
2923 }
2924
2925 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002926 if (PyString_Check(cafile)) {
2927 Py_INCREF(cafile);
2928 cafile_bytes = cafile;
2929 } else {
2930 PyObject *u = PyUnicode_FromObject(cafile);
2931 if (!u)
2932 goto error;
2933 cafile_bytes = PyUnicode_AsEncodedString(
2934 u, Py_FileSystemDefaultEncoding, NULL);
2935 Py_DECREF(u);
2936 if (!cafile_bytes)
2937 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002938 }
2939 }
2940 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002941 if (PyString_Check(capath)) {
2942 Py_INCREF(capath);
2943 capath_bytes = capath;
2944 } else {
2945 PyObject *u = PyUnicode_FromObject(capath);
2946 if (!u)
2947 goto error;
2948 capath_bytes = PyUnicode_AsEncodedString(
2949 u, Py_FileSystemDefaultEncoding, NULL);
2950 Py_DECREF(u);
2951 if (!capath_bytes)
2952 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002953 }
2954 }
2955
2956 /* validata cadata type and load cadata */
2957 if (cadata) {
2958 Py_buffer buf;
2959 PyObject *cadata_ascii = NULL;
2960
2961 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2962 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2963 PyBuffer_Release(&buf);
2964 PyErr_SetString(PyExc_TypeError,
2965 "cadata should be a contiguous buffer with "
2966 "a single dimension");
2967 goto error;
2968 }
2969 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2970 PyBuffer_Release(&buf);
2971 if (r == -1) {
2972 goto error;
2973 }
2974 } else {
2975 PyErr_Clear();
2976 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2977 if (cadata_ascii == NULL) {
2978 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002979 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002980 "bytes-like object");
2981 goto error;
2982 }
2983 r = _add_ca_certs(self,
2984 PyBytes_AS_STRING(cadata_ascii),
2985 PyBytes_GET_SIZE(cadata_ascii),
2986 SSL_FILETYPE_PEM);
2987 Py_DECREF(cadata_ascii);
2988 if (r == -1) {
2989 goto error;
2990 }
2991 }
2992 }
2993
2994 /* load cafile or capath */
2995 if (cafile_bytes || capath_bytes) {
2996 if (cafile)
2997 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2998 if (capath)
2999 capath_buf = PyBytes_AS_STRING(capath_bytes);
3000 PySSL_BEGIN_ALLOW_THREADS
3001 r = SSL_CTX_load_verify_locations(
3002 self->ctx,
3003 cafile_buf,
3004 capath_buf);
3005 PySSL_END_ALLOW_THREADS
3006 if (r != 1) {
3007 ok = 0;
3008 if (errno != 0) {
3009 ERR_clear_error();
3010 PyErr_SetFromErrno(PyExc_IOError);
3011 }
3012 else {
3013 _setSSLError(NULL, 0, __FILE__, __LINE__);
3014 }
3015 goto error;
3016 }
3017 }
3018 goto end;
3019
3020 error:
3021 ok = 0;
3022 end:
3023 Py_XDECREF(cafile_bytes);
3024 Py_XDECREF(capath_bytes);
3025 if (ok) {
3026 Py_RETURN_NONE;
3027 } else {
3028 return NULL;
3029 }
3030}
3031
3032static PyObject *
3033load_dh_params(PySSLContext *self, PyObject *filepath)
3034{
3035 BIO *bio;
3036 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003037 PyObject *filepath_bytes = NULL;
3038
3039 if (PyString_Check(filepath)) {
3040 Py_INCREF(filepath);
3041 filepath_bytes = filepath;
3042 } else {
3043 PyObject *u = PyUnicode_FromObject(filepath);
3044 if (!u)
3045 return NULL;
3046 filepath_bytes = PyUnicode_AsEncodedString(
3047 u, Py_FileSystemDefaultEncoding, NULL);
3048 Py_DECREF(u);
3049 if (!filepath_bytes)
3050 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003051 }
3052
Christian Heimes6e8f3952018-02-25 09:48:02 +01003053 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003054 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003055 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003056 ERR_clear_error();
3057 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3058 return NULL;
3059 }
3060 errno = 0;
3061 PySSL_BEGIN_ALLOW_THREADS
3062 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3063 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003064 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003065 PySSL_END_ALLOW_THREADS
3066 if (dh == NULL) {
3067 if (errno != 0) {
3068 ERR_clear_error();
3069 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3070 }
3071 else {
3072 _setSSLError(NULL, 0, __FILE__, __LINE__);
3073 }
3074 return NULL;
3075 }
3076 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3077 _setSSLError(NULL, 0, __FILE__, __LINE__);
3078 DH_free(dh);
3079 Py_RETURN_NONE;
3080}
3081
3082static PyObject *
3083context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3084{
3085 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3086 PySocketSockObject *sock;
3087 int server_side = 0;
3088 char *hostname = NULL;
3089 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3090
3091 /* server_hostname is either None (or absent), or to be encoded
3092 using the idna encoding. */
3093 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3094 PySocketModule.Sock_Type,
3095 &sock, &server_side,
3096 Py_TYPE(Py_None), &hostname_obj,
3097 &ssl_sock)) {
3098 PyErr_Clear();
3099 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3100 PySocketModule.Sock_Type,
3101 &sock, &server_side,
3102 "idna", &hostname, &ssl_sock))
3103 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003104 }
3105
3106 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3107 hostname, ssl_sock);
3108 if (hostname != NULL)
3109 PyMem_Free(hostname);
3110 return res;
3111}
3112
3113static PyObject *
3114session_stats(PySSLContext *self, PyObject *unused)
3115{
3116 int r;
3117 PyObject *value, *stats = PyDict_New();
3118 if (!stats)
3119 return NULL;
3120
3121#define ADD_STATS(SSL_NAME, KEY_NAME) \
3122 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3123 if (value == NULL) \
3124 goto error; \
3125 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3126 Py_DECREF(value); \
3127 if (r < 0) \
3128 goto error;
3129
3130 ADD_STATS(number, "number");
3131 ADD_STATS(connect, "connect");
3132 ADD_STATS(connect_good, "connect_good");
3133 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3134 ADD_STATS(accept, "accept");
3135 ADD_STATS(accept_good, "accept_good");
3136 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3137 ADD_STATS(accept, "accept");
3138 ADD_STATS(hits, "hits");
3139 ADD_STATS(misses, "misses");
3140 ADD_STATS(timeouts, "timeouts");
3141 ADD_STATS(cache_full, "cache_full");
3142
3143#undef ADD_STATS
3144
3145 return stats;
3146
3147error:
3148 Py_DECREF(stats);
3149 return NULL;
3150}
3151
3152static PyObject *
3153set_default_verify_paths(PySSLContext *self, PyObject *unused)
3154{
3155 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3156 _setSSLError(NULL, 0, __FILE__, __LINE__);
3157 return NULL;
3158 }
3159 Py_RETURN_NONE;
3160}
3161
3162#ifndef OPENSSL_NO_ECDH
3163static PyObject *
3164set_ecdh_curve(PySSLContext *self, PyObject *name)
3165{
3166 char *name_bytes;
3167 int nid;
3168 EC_KEY *key;
3169
3170 name_bytes = PyBytes_AsString(name);
3171 if (!name_bytes) {
3172 return NULL;
3173 }
3174 nid = OBJ_sn2nid(name_bytes);
3175 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003176 PyObject *r = PyObject_Repr(name);
3177 if (!r)
3178 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003179 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003180 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3181 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003182 return NULL;
3183 }
3184 key = EC_KEY_new_by_curve_name(nid);
3185 if (key == NULL) {
3186 _setSSLError(NULL, 0, __FILE__, __LINE__);
3187 return NULL;
3188 }
3189 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3190 EC_KEY_free(key);
3191 Py_RETURN_NONE;
3192}
3193#endif
3194
3195#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3196static int
3197_servername_callback(SSL *s, int *al, void *args)
3198{
3199 int ret;
3200 PySSLContext *ssl_ctx = (PySSLContext *) args;
3201 PySSLSocket *ssl;
3202 PyObject *servername_o;
3203 PyObject *servername_idna;
3204 PyObject *result;
3205 /* The high-level ssl.SSLSocket object */
3206 PyObject *ssl_socket;
3207 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3208#ifdef WITH_THREAD
3209 PyGILState_STATE gstate = PyGILState_Ensure();
3210#endif
3211
3212 if (ssl_ctx->set_hostname == NULL) {
3213 /* remove race condition in this the call back while if removing the
3214 * callback is in progress */
3215#ifdef WITH_THREAD
3216 PyGILState_Release(gstate);
3217#endif
3218 return SSL_TLSEXT_ERR_OK;
3219 }
3220
3221 ssl = SSL_get_app_data(s);
3222 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003223 if (ssl->ssl_sock == NULL) {
3224 ssl_socket = Py_None;
3225 } else {
3226 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3227 Py_INCREF(ssl_socket);
3228 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003229 if (ssl_socket == Py_None) {
3230 goto error;
3231 }
3232
3233 if (servername == NULL) {
3234 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3235 Py_None, ssl_ctx, NULL);
3236 }
3237 else {
3238 servername_o = PyBytes_FromString(servername);
3239 if (servername_o == NULL) {
3240 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3241 goto error;
3242 }
3243 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3244 if (servername_idna == NULL) {
3245 PyErr_WriteUnraisable(servername_o);
3246 Py_DECREF(servername_o);
3247 goto error;
3248 }
3249 Py_DECREF(servername_o);
3250 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3251 servername_idna, ssl_ctx, NULL);
3252 Py_DECREF(servername_idna);
3253 }
3254 Py_DECREF(ssl_socket);
3255
3256 if (result == NULL) {
3257 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3258 *al = SSL_AD_HANDSHAKE_FAILURE;
3259 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3260 }
3261 else {
3262 if (result != Py_None) {
3263 *al = (int) PyLong_AsLong(result);
3264 if (PyErr_Occurred()) {
3265 PyErr_WriteUnraisable(result);
3266 *al = SSL_AD_INTERNAL_ERROR;
3267 }
3268 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3269 }
3270 else {
3271 ret = SSL_TLSEXT_ERR_OK;
3272 }
3273 Py_DECREF(result);
3274 }
3275
3276#ifdef WITH_THREAD
3277 PyGILState_Release(gstate);
3278#endif
3279 return ret;
3280
3281error:
3282 Py_DECREF(ssl_socket);
3283 *al = SSL_AD_INTERNAL_ERROR;
3284 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3285#ifdef WITH_THREAD
3286 PyGILState_Release(gstate);
3287#endif
3288 return ret;
3289}
3290#endif
3291
3292PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3293"set_servername_callback(method)\n\
3294\n\
3295This sets a callback that will be called when a server name is provided by\n\
3296the SSL/TLS client in the SNI extension.\n\
3297\n\
3298If the argument is None then the callback is disabled. The method is called\n\
3299with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3300See RFC 6066 for details of the SNI extension.");
3301
3302static PyObject *
3303set_servername_callback(PySSLContext *self, PyObject *args)
3304{
3305#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3306 PyObject *cb;
3307
3308 if (!PyArg_ParseTuple(args, "O", &cb))
3309 return NULL;
3310
3311 Py_CLEAR(self->set_hostname);
3312 if (cb == Py_None) {
3313 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3314 }
3315 else {
3316 if (!PyCallable_Check(cb)) {
3317 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3318 PyErr_SetString(PyExc_TypeError,
3319 "not a callable object");
3320 return NULL;
3321 }
3322 Py_INCREF(cb);
3323 self->set_hostname = cb;
3324 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3325 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3326 }
3327 Py_RETURN_NONE;
3328#else
3329 PyErr_SetString(PyExc_NotImplementedError,
3330 "The TLS extension servername callback, "
3331 "SSL_CTX_set_tlsext_servername_callback, "
3332 "is not in the current OpenSSL library.");
3333 return NULL;
3334#endif
3335}
3336
3337PyDoc_STRVAR(PySSL_get_stats_doc,
3338"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3339\n\
3340Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3341CA extension and certificate revocation lists inside the context's cert\n\
3342store.\n\
3343NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3344been used at least once.");
3345
3346static PyObject *
3347cert_store_stats(PySSLContext *self)
3348{
3349 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003350 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003351 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003352 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003353
3354 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003355 objs = X509_STORE_get0_objects(store);
3356 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3357 obj = sk_X509_OBJECT_value(objs, i);
3358 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003359 case X509_LU_X509:
3360 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003361 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003362 ca++;
3363 }
3364 break;
3365 case X509_LU_CRL:
3366 crl++;
3367 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003368 default:
3369 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3370 * As far as I can tell they are internal states and never
3371 * stored in a cert store */
3372 break;
3373 }
3374 }
3375 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3376 "x509_ca", ca);
3377}
3378
3379PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3380"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3381\n\
3382Returns a list of dicts with information of loaded CA certs. If the\n\
3383optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3384NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3385been used at least once.");
3386
3387static PyObject *
3388get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3389{
3390 char *kwlist[] = {"binary_form", NULL};
3391 X509_STORE *store;
3392 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003393 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003394 int i;
3395 int binary_mode = 0;
3396
3397 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3398 kwlist, &py_binary_mode)) {
3399 return NULL;
3400 }
3401 binary_mode = PyObject_IsTrue(py_binary_mode);
3402 if (binary_mode < 0) {
3403 return NULL;
3404 }
3405
3406 if ((rlist = PyList_New(0)) == NULL) {
3407 return NULL;
3408 }
3409
3410 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003411 objs = X509_STORE_get0_objects(store);
3412 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003413 X509_OBJECT *obj;
3414 X509 *cert;
3415
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003416 obj = sk_X509_OBJECT_value(objs, i);
3417 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003418 /* not a x509 cert */
3419 continue;
3420 }
3421 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003422 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003423 if (!X509_check_ca(cert)) {
3424 continue;
3425 }
3426 if (binary_mode) {
3427 ci = _certificate_to_der(cert);
3428 } else {
3429 ci = _decode_certificate(cert);
3430 }
3431 if (ci == NULL) {
3432 goto error;
3433 }
3434 if (PyList_Append(rlist, ci) == -1) {
3435 goto error;
3436 }
3437 Py_CLEAR(ci);
3438 }
3439 return rlist;
3440
3441 error:
3442 Py_XDECREF(ci);
3443 Py_XDECREF(rlist);
3444 return NULL;
3445}
3446
3447
3448static PyGetSetDef context_getsetlist[] = {
3449 {"check_hostname", (getter) get_check_hostname,
3450 (setter) set_check_hostname, NULL},
3451 {"options", (getter) get_options,
3452 (setter) set_options, NULL},
3453#ifdef HAVE_OPENSSL_VERIFY_PARAM
3454 {"verify_flags", (getter) get_verify_flags,
3455 (setter) set_verify_flags, NULL},
3456#endif
3457 {"verify_mode", (getter) get_verify_mode,
3458 (setter) set_verify_mode, NULL},
3459 {NULL}, /* sentinel */
3460};
3461
3462static struct PyMethodDef context_methods[] = {
3463 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3464 METH_VARARGS | METH_KEYWORDS, NULL},
3465 {"set_ciphers", (PyCFunction) set_ciphers,
3466 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003467 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3468 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003469 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3470 METH_VARARGS, NULL},
3471 {"load_cert_chain", (PyCFunction) load_cert_chain,
3472 METH_VARARGS | METH_KEYWORDS, NULL},
3473 {"load_dh_params", (PyCFunction) load_dh_params,
3474 METH_O, NULL},
3475 {"load_verify_locations", (PyCFunction) load_verify_locations,
3476 METH_VARARGS | METH_KEYWORDS, NULL},
3477 {"session_stats", (PyCFunction) session_stats,
3478 METH_NOARGS, NULL},
3479 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3480 METH_NOARGS, NULL},
3481#ifndef OPENSSL_NO_ECDH
3482 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3483 METH_O, NULL},
3484#endif
3485 {"set_servername_callback", (PyCFunction) set_servername_callback,
3486 METH_VARARGS, PySSL_set_servername_callback_doc},
3487 {"cert_store_stats", (PyCFunction) cert_store_stats,
3488 METH_NOARGS, PySSL_get_stats_doc},
3489 {"get_ca_certs", (PyCFunction) get_ca_certs,
3490 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3491 {NULL, NULL} /* sentinel */
3492};
3493
3494static PyTypeObject PySSLContext_Type = {
3495 PyVarObject_HEAD_INIT(NULL, 0)
3496 "_ssl._SSLContext", /*tp_name*/
3497 sizeof(PySSLContext), /*tp_basicsize*/
3498 0, /*tp_itemsize*/
3499 (destructor)context_dealloc, /*tp_dealloc*/
3500 0, /*tp_print*/
3501 0, /*tp_getattr*/
3502 0, /*tp_setattr*/
3503 0, /*tp_reserved*/
3504 0, /*tp_repr*/
3505 0, /*tp_as_number*/
3506 0, /*tp_as_sequence*/
3507 0, /*tp_as_mapping*/
3508 0, /*tp_hash*/
3509 0, /*tp_call*/
3510 0, /*tp_str*/
3511 0, /*tp_getattro*/
3512 0, /*tp_setattro*/
3513 0, /*tp_as_buffer*/
3514 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3515 0, /*tp_doc*/
3516 (traverseproc) context_traverse, /*tp_traverse*/
3517 (inquiry) context_clear, /*tp_clear*/
3518 0, /*tp_richcompare*/
3519 0, /*tp_weaklistoffset*/
3520 0, /*tp_iter*/
3521 0, /*tp_iternext*/
3522 context_methods, /*tp_methods*/
3523 0, /*tp_members*/
3524 context_getsetlist, /*tp_getset*/
3525 0, /*tp_base*/
3526 0, /*tp_dict*/
3527 0, /*tp_descr_get*/
3528 0, /*tp_descr_set*/
3529 0, /*tp_dictoffset*/
3530 0, /*tp_init*/
3531 0, /*tp_alloc*/
3532 context_new, /*tp_new*/
3533};
3534
3535
3536
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003537#ifdef HAVE_OPENSSL_RAND
3538
3539/* helper routines for seeding the SSL PRNG */
3540static PyObject *
3541PySSL_RAND_add(PyObject *self, PyObject *args)
3542{
3543 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003544 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003545 double entropy;
3546
3547 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003548 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003549 do {
3550 if (len >= INT_MAX) {
3551 written = INT_MAX;
3552 } else {
3553 written = len;
3554 }
3555 RAND_add(buf, (int)written, entropy);
3556 buf += written;
3557 len -= written;
3558 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003559 Py_INCREF(Py_None);
3560 return Py_None;
3561}
3562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003564"RAND_add(string, entropy)\n\
3565\n\
3566Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003567bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003568
3569static PyObject *
3570PySSL_RAND_status(PyObject *self)
3571{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003572 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003573}
3574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003575PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003576"RAND_status() -> 0 or 1\n\
3577\n\
3578Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3579It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003580using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003581
Victor Stinner7c906672015-01-06 13:53:37 +01003582#endif /* HAVE_OPENSSL_RAND */
3583
3584
Benjamin Peterson42e10292016-07-07 00:02:31 -07003585#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003586
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003587static PyObject *
3588PySSL_RAND_egd(PyObject *self, PyObject *arg)
3589{
3590 int bytes;
3591
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003592 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003593 return PyErr_Format(PyExc_TypeError,
3594 "RAND_egd() expected string, found %s",
3595 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003596 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003597 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003598 PyErr_SetString(PySSLErrorObject,
3599 "EGD connection failed or EGD did not return "
3600 "enough data to seed the PRNG");
3601 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003602 }
3603 return PyInt_FromLong(bytes);
3604}
3605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003606PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003607"RAND_egd(path) -> bytes\n\
3608\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003609Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3610Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003611fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003612
Benjamin Peterson42e10292016-07-07 00:02:31 -07003613#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003614
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003615
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003616PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3617"get_default_verify_paths() -> tuple\n\
3618\n\
3619Return search paths and environment vars that are used by SSLContext's\n\
3620set_default_verify_paths() to load default CAs. The values are\n\
3621'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3622
3623static PyObject *
3624PySSL_get_default_verify_paths(PyObject *self)
3625{
3626 PyObject *ofile_env = NULL;
3627 PyObject *ofile = NULL;
3628 PyObject *odir_env = NULL;
3629 PyObject *odir = NULL;
3630
Benjamin Peterson65192c12015-07-18 10:59:13 -07003631#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003632 const char *tmp = (info); \
3633 target = NULL; \
3634 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3635 else { target = PyBytes_FromString(tmp); } \
3636 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003637 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003638
Benjamin Peterson65192c12015-07-18 10:59:13 -07003639 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3640 CONVERT(X509_get_default_cert_file(), ofile);
3641 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3642 CONVERT(X509_get_default_cert_dir(), odir);
3643#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003644
3645 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3646
3647 error:
3648 Py_XDECREF(ofile_env);
3649 Py_XDECREF(ofile);
3650 Py_XDECREF(odir_env);
3651 Py_XDECREF(odir);
3652 return NULL;
3653}
3654
3655static PyObject*
3656asn1obj2py(ASN1_OBJECT *obj)
3657{
3658 int nid;
3659 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003660
3661 nid = OBJ_obj2nid(obj);
3662 if (nid == NID_undef) {
3663 PyErr_Format(PyExc_ValueError, "Unknown object");
3664 return NULL;
3665 }
3666 sn = OBJ_nid2sn(nid);
3667 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003668 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003669}
3670
3671PyDoc_STRVAR(PySSL_txt2obj_doc,
3672"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3673\n\
3674Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3675objects are looked up by OID. With name=True short and long name are also\n\
3676matched.");
3677
3678static PyObject*
3679PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3680{
3681 char *kwlist[] = {"txt", "name", NULL};
3682 PyObject *result = NULL;
3683 char *txt;
3684 PyObject *pyname = Py_None;
3685 int name = 0;
3686 ASN1_OBJECT *obj;
3687
3688 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3689 kwlist, &txt, &pyname)) {
3690 return NULL;
3691 }
3692 name = PyObject_IsTrue(pyname);
3693 if (name < 0)
3694 return NULL;
3695 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3696 if (obj == NULL) {
3697 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3698 return NULL;
3699 }
3700 result = asn1obj2py(obj);
3701 ASN1_OBJECT_free(obj);
3702 return result;
3703}
3704
3705PyDoc_STRVAR(PySSL_nid2obj_doc,
3706"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3707\n\
3708Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3709
3710static PyObject*
3711PySSL_nid2obj(PyObject *self, PyObject *args)
3712{
3713 PyObject *result = NULL;
3714 int nid;
3715 ASN1_OBJECT *obj;
3716
3717 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3718 return NULL;
3719 }
3720 if (nid < NID_undef) {
3721 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3722 return NULL;
3723 }
3724 obj = OBJ_nid2obj(nid);
3725 if (obj == NULL) {
3726 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3727 return NULL;
3728 }
3729 result = asn1obj2py(obj);
3730 ASN1_OBJECT_free(obj);
3731 return result;
3732}
3733
3734#ifdef _MSC_VER
3735
3736static PyObject*
3737certEncodingType(DWORD encodingType)
3738{
3739 static PyObject *x509_asn = NULL;
3740 static PyObject *pkcs_7_asn = NULL;
3741
3742 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003743 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003744 if (x509_asn == NULL)
3745 return NULL;
3746 }
3747 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003748 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003749 if (pkcs_7_asn == NULL)
3750 return NULL;
3751 }
3752 switch(encodingType) {
3753 case X509_ASN_ENCODING:
3754 Py_INCREF(x509_asn);
3755 return x509_asn;
3756 case PKCS_7_ASN_ENCODING:
3757 Py_INCREF(pkcs_7_asn);
3758 return pkcs_7_asn;
3759 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003760 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003761 }
3762}
3763
3764static PyObject*
3765parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3766{
3767 CERT_ENHKEY_USAGE *usage;
3768 DWORD size, error, i;
3769 PyObject *retval;
3770
3771 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3772 error = GetLastError();
3773 if (error == CRYPT_E_NOT_FOUND) {
3774 Py_RETURN_TRUE;
3775 }
3776 return PyErr_SetFromWindowsErr(error);
3777 }
3778
3779 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3780 if (usage == NULL) {
3781 return PyErr_NoMemory();
3782 }
3783
3784 /* Now get the actual enhanced usage property */
3785 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3786 PyMem_Free(usage);
3787 error = GetLastError();
3788 if (error == CRYPT_E_NOT_FOUND) {
3789 Py_RETURN_TRUE;
3790 }
3791 return PyErr_SetFromWindowsErr(error);
3792 }
3793 retval = PySet_New(NULL);
3794 if (retval == NULL) {
3795 goto error;
3796 }
3797 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3798 if (usage->rgpszUsageIdentifier[i]) {
3799 PyObject *oid;
3800 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003801 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003802 if (oid == NULL) {
3803 Py_CLEAR(retval);
3804 goto error;
3805 }
3806 err = PySet_Add(retval, oid);
3807 Py_DECREF(oid);
3808 if (err == -1) {
3809 Py_CLEAR(retval);
3810 goto error;
3811 }
3812 }
3813 }
3814 error:
3815 PyMem_Free(usage);
3816 return retval;
3817}
3818
3819PyDoc_STRVAR(PySSL_enum_certificates_doc,
3820"enum_certificates(store_name) -> []\n\
3821\n\
3822Retrieve certificates from Windows' cert store. store_name may be one of\n\
3823'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3824The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3825encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3826PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3827boolean True.");
3828
3829static PyObject *
3830PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3831{
3832 char *kwlist[] = {"store_name", NULL};
3833 char *store_name;
3834 HCERTSTORE hStore = NULL;
3835 PCCERT_CONTEXT pCertCtx = NULL;
3836 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3837 PyObject *result = NULL;
3838
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003839 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003840 kwlist, &store_name)) {
3841 return NULL;
3842 }
3843 result = PyList_New(0);
3844 if (result == NULL) {
3845 return NULL;
3846 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003847 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3848 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3849 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003850 if (hStore == NULL) {
3851 Py_DECREF(result);
3852 return PyErr_SetFromWindowsErr(GetLastError());
3853 }
3854
3855 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3856 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3857 pCertCtx->cbCertEncoded);
3858 if (!cert) {
3859 Py_CLEAR(result);
3860 break;
3861 }
3862 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3863 Py_CLEAR(result);
3864 break;
3865 }
3866 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3867 if (keyusage == Py_True) {
3868 Py_DECREF(keyusage);
3869 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3870 }
3871 if (keyusage == NULL) {
3872 Py_CLEAR(result);
3873 break;
3874 }
3875 if ((tup = PyTuple_New(3)) == NULL) {
3876 Py_CLEAR(result);
3877 break;
3878 }
3879 PyTuple_SET_ITEM(tup, 0, cert);
3880 cert = NULL;
3881 PyTuple_SET_ITEM(tup, 1, enc);
3882 enc = NULL;
3883 PyTuple_SET_ITEM(tup, 2, keyusage);
3884 keyusage = NULL;
3885 if (PyList_Append(result, tup) < 0) {
3886 Py_CLEAR(result);
3887 break;
3888 }
3889 Py_CLEAR(tup);
3890 }
3891 if (pCertCtx) {
3892 /* loop ended with an error, need to clean up context manually */
3893 CertFreeCertificateContext(pCertCtx);
3894 }
3895
3896 /* In error cases cert, enc and tup may not be NULL */
3897 Py_XDECREF(cert);
3898 Py_XDECREF(enc);
3899 Py_XDECREF(keyusage);
3900 Py_XDECREF(tup);
3901
3902 if (!CertCloseStore(hStore, 0)) {
3903 /* This error case might shadow another exception.*/
3904 Py_XDECREF(result);
3905 return PyErr_SetFromWindowsErr(GetLastError());
3906 }
3907 return result;
3908}
3909
3910PyDoc_STRVAR(PySSL_enum_crls_doc,
3911"enum_crls(store_name) -> []\n\
3912\n\
3913Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3914'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3915The function returns a list of (bytes, encoding_type) tuples. The\n\
3916encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3917PKCS_7_ASN_ENCODING.");
3918
3919static PyObject *
3920PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3921{
3922 char *kwlist[] = {"store_name", NULL};
3923 char *store_name;
3924 HCERTSTORE hStore = NULL;
3925 PCCRL_CONTEXT pCrlCtx = NULL;
3926 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3927 PyObject *result = NULL;
3928
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003929 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003930 kwlist, &store_name)) {
3931 return NULL;
3932 }
3933 result = PyList_New(0);
3934 if (result == NULL) {
3935 return NULL;
3936 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003937 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3938 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3939 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003940 if (hStore == NULL) {
3941 Py_DECREF(result);
3942 return PyErr_SetFromWindowsErr(GetLastError());
3943 }
3944
3945 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3946 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3947 pCrlCtx->cbCrlEncoded);
3948 if (!crl) {
3949 Py_CLEAR(result);
3950 break;
3951 }
3952 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3953 Py_CLEAR(result);
3954 break;
3955 }
3956 if ((tup = PyTuple_New(2)) == NULL) {
3957 Py_CLEAR(result);
3958 break;
3959 }
3960 PyTuple_SET_ITEM(tup, 0, crl);
3961 crl = NULL;
3962 PyTuple_SET_ITEM(tup, 1, enc);
3963 enc = NULL;
3964
3965 if (PyList_Append(result, tup) < 0) {
3966 Py_CLEAR(result);
3967 break;
3968 }
3969 Py_CLEAR(tup);
3970 }
3971 if (pCrlCtx) {
3972 /* loop ended with an error, need to clean up context manually */
3973 CertFreeCRLContext(pCrlCtx);
3974 }
3975
3976 /* In error cases cert, enc and tup may not be NULL */
3977 Py_XDECREF(crl);
3978 Py_XDECREF(enc);
3979 Py_XDECREF(tup);
3980
3981 if (!CertCloseStore(hStore, 0)) {
3982 /* This error case might shadow another exception.*/
3983 Py_XDECREF(result);
3984 return PyErr_SetFromWindowsErr(GetLastError());
3985 }
3986 return result;
3987}
3988
3989#endif /* _MSC_VER */
3990
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003991/* List of functions exported by this module. */
3992
3993static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003994 {"_test_decode_cert", PySSL_test_decode_certificate,
3995 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003996#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003997 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3998 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003999 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4000 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004001#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07004002#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01004003 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
4004 PySSL_RAND_egd_doc},
4005#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004006 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
4007 METH_NOARGS, PySSL_get_default_verify_paths_doc},
4008#ifdef _MSC_VER
4009 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4010 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4011 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4012 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4013#endif
4014 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4015 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4016 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4017 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004018 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004019};
4020
4021
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004022#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004023
4024/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004025 * of the Python C thread library
4026 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4027 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004028
4029static PyThread_type_lock *_ssl_locks = NULL;
4030
Christian Heimes10107812013-08-19 17:36:29 +02004031#if OPENSSL_VERSION_NUMBER >= 0x10000000
4032/* use new CRYPTO_THREADID API. */
4033static void
4034_ssl_threadid_callback(CRYPTO_THREADID *id)
4035{
4036 CRYPTO_THREADID_set_numeric(id,
4037 (unsigned long)PyThread_get_thread_ident());
4038}
4039#else
4040/* deprecated CRYPTO_set_id_callback() API. */
4041static unsigned long
4042_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004043 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004044}
Christian Heimes10107812013-08-19 17:36:29 +02004045#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004046
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004047static void _ssl_thread_locking_function
4048 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004049 /* this function is needed to perform locking on shared data
4050 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004051 structures that will be implicitly shared whenever multiple
4052 threads use OpenSSL.) Multi-threaded applications will
4053 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004054
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004055 locking_function() must be able to handle up to
4056 CRYPTO_num_locks() different mutex locks. It sets the n-th
4057 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004058
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004059 file and line are the file number of the function setting the
4060 lock. They can be useful for debugging.
4061 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004062
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004063 if ((_ssl_locks == NULL) ||
4064 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4065 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004066
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004067 if (mode & CRYPTO_LOCK) {
4068 PyThread_acquire_lock(_ssl_locks[n], 1);
4069 } else {
4070 PyThread_release_lock(_ssl_locks[n]);
4071 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004072}
4073
4074static int _setup_ssl_threads(void) {
4075
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004076 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004077
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004078 if (_ssl_locks == NULL) {
4079 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004080 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4081 if (_ssl_locks == NULL) {
4082 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004083 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004084 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004085 memset(_ssl_locks, 0,
4086 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004087 for (i = 0; i < _ssl_locks_count; i++) {
4088 _ssl_locks[i] = PyThread_allocate_lock();
4089 if (_ssl_locks[i] == NULL) {
4090 unsigned int j;
4091 for (j = 0; j < i; j++) {
4092 PyThread_free_lock(_ssl_locks[j]);
4093 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004094 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004095 return 0;
4096 }
4097 }
4098 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004099#if OPENSSL_VERSION_NUMBER >= 0x10000000
4100 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4101#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004102 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004103#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004104 }
4105 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004106}
4107
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004108#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004110PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004111"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004112for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004113
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004114
4115
4116
4117static void
4118parse_openssl_version(unsigned long libver,
4119 unsigned int *major, unsigned int *minor,
4120 unsigned int *fix, unsigned int *patch,
4121 unsigned int *status)
4122{
4123 *status = libver & 0xF;
4124 libver >>= 4;
4125 *patch = libver & 0xFF;
4126 libver >>= 8;
4127 *fix = libver & 0xFF;
4128 libver >>= 8;
4129 *minor = libver & 0xFF;
4130 libver >>= 8;
4131 *major = libver & 0xFF;
4132}
4133
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004134PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004135init_ssl(void)
4136{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004137 PyObject *m, *d, *r;
4138 unsigned long libver;
4139 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004140 struct py_ssl_error_code *errcode;
4141 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004142
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004143 if (PyType_Ready(&PySSLContext_Type) < 0)
4144 return;
4145 if (PyType_Ready(&PySSLSocket_Type) < 0)
4146 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004147
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004148 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4149 if (m == NULL)
4150 return;
4151 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004152
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004153 /* Load _socket module and its C API */
4154 if (PySocketModule_ImportModuleAndAPI())
4155 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004156
Christian Heimes7daa45d2017-09-05 17:12:12 +02004157#ifndef OPENSSL_VERSION_1_1
4158 /* Load all algorithms and initialize cpuid */
4159 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004160 /* Init OpenSSL */
4161 SSL_load_error_strings();
4162 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004163#endif
4164
Bill Janssen98d19da2007-09-10 21:51:02 +00004165#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004166#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004167 /* note that this will start threading if not already started */
4168 if (!_setup_ssl_threads()) {
4169 return;
4170 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004171#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4172 /* OpenSSL 1.1.0 builtin thread support is enabled */
4173 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004174#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004175#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004176
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004177 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004178 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4179 "ssl.SSLError", SSLError_doc,
4180 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004181 if (PySSLErrorObject == NULL)
4182 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004183 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4184
4185 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4186 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4187 PySSLErrorObject, NULL);
4188 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4189 "ssl.SSLWantReadError", SSLWantReadError_doc,
4190 PySSLErrorObject, NULL);
4191 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4192 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4193 PySSLErrorObject, NULL);
4194 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4195 "ssl.SSLSyscallError", SSLSyscallError_doc,
4196 PySSLErrorObject, NULL);
4197 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4198 "ssl.SSLEOFError", SSLEOFError_doc,
4199 PySSLErrorObject, NULL);
4200 if (PySSLZeroReturnErrorObject == NULL
4201 || PySSLWantReadErrorObject == NULL
4202 || PySSLWantWriteErrorObject == NULL
4203 || PySSLSyscallErrorObject == NULL
4204 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004205 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004206
4207 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4208 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4209 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4210 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4211 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4212
4213 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4214 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4215 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4216 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4217 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4218 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4219 return;
4220 if (PyDict_SetItemString(d, "_SSLContext",
4221 (PyObject *)&PySSLContext_Type) != 0)
4222 return;
4223 if (PyDict_SetItemString(d, "_SSLSocket",
4224 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004225 return;
4226 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4227 PY_SSL_ERROR_ZERO_RETURN);
4228 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4229 PY_SSL_ERROR_WANT_READ);
4230 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4231 PY_SSL_ERROR_WANT_WRITE);
4232 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4233 PY_SSL_ERROR_WANT_X509_LOOKUP);
4234 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4235 PY_SSL_ERROR_SYSCALL);
4236 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4237 PY_SSL_ERROR_SSL);
4238 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4239 PY_SSL_ERROR_WANT_CONNECT);
4240 /* non ssl.h errorcodes */
4241 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4242 PY_SSL_ERROR_EOF);
4243 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4244 PY_SSL_ERROR_INVALID_ERROR_CODE);
4245 /* cert requirements */
4246 PyModule_AddIntConstant(m, "CERT_NONE",
4247 PY_SSL_CERT_NONE);
4248 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4249 PY_SSL_CERT_OPTIONAL);
4250 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4251 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004252 /* CRL verification for verification_flags */
4253 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4254 0);
4255 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4256 X509_V_FLAG_CRL_CHECK);
4257 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4258 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4259 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4260 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004261#ifdef X509_V_FLAG_TRUSTED_FIRST
4262 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4263 X509_V_FLAG_TRUSTED_FIRST);
4264#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004265
4266 /* Alert Descriptions from ssl.h */
4267 /* note RESERVED constants no longer intended for use have been removed */
4268 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4269
4270#define ADD_AD_CONSTANT(s) \
4271 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4272 SSL_AD_##s)
4273
4274 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4275 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4276 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4277 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4278 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4279 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4280 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4281 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4282 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4283 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4284 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4285 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4286 ADD_AD_CONSTANT(UNKNOWN_CA);
4287 ADD_AD_CONSTANT(ACCESS_DENIED);
4288 ADD_AD_CONSTANT(DECODE_ERROR);
4289 ADD_AD_CONSTANT(DECRYPT_ERROR);
4290 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4291 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4292 ADD_AD_CONSTANT(INTERNAL_ERROR);
4293 ADD_AD_CONSTANT(USER_CANCELLED);
4294 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4295 /* Not all constants are in old OpenSSL versions */
4296#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4297 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4298#endif
4299#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4300 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4301#endif
4302#ifdef SSL_AD_UNRECOGNIZED_NAME
4303 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4304#endif
4305#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4306 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4307#endif
4308#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4309 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4310#endif
4311#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4312 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4313#endif
4314
4315#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004316
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004317 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004318#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004319 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4320 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004321#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004322#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004323 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4324 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004325#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004326 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004327 PY_SSL_VERSION_TLS);
4328 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4329 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004330 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4331 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004332#if HAVE_TLSv1_2
4333 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4334 PY_SSL_VERSION_TLS1_1);
4335 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4336 PY_SSL_VERSION_TLS1_2);
4337#endif
4338
4339 /* protocol options */
4340 PyModule_AddIntConstant(m, "OP_ALL",
4341 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4342 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4343 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4344 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4345#if HAVE_TLSv1_2
4346 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4347 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4348#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004349#ifdef SSL_OP_NO_TLSv1_3
4350 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4351#else
4352 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4353#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004354 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4355 SSL_OP_CIPHER_SERVER_PREFERENCE);
4356 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4357#ifdef SSL_OP_SINGLE_ECDH_USE
4358 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4359#endif
4360#ifdef SSL_OP_NO_COMPRESSION
4361 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4362 SSL_OP_NO_COMPRESSION);
4363#endif
4364
4365#if HAVE_SNI
4366 r = Py_True;
4367#else
4368 r = Py_False;
4369#endif
4370 Py_INCREF(r);
4371 PyModule_AddObject(m, "HAS_SNI", r);
4372
4373#if HAVE_OPENSSL_FINISHED
4374 r = Py_True;
4375#else
4376 r = Py_False;
4377#endif
4378 Py_INCREF(r);
4379 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4380
4381#ifdef OPENSSL_NO_ECDH
4382 r = Py_False;
4383#else
4384 r = Py_True;
4385#endif
4386 Py_INCREF(r);
4387 PyModule_AddObject(m, "HAS_ECDH", r);
4388
Christian Heimes3d87f4c2018-02-25 10:21:03 +01004389#ifdef HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004390 r = Py_True;
4391#else
4392 r = Py_False;
4393#endif
4394 Py_INCREF(r);
4395 PyModule_AddObject(m, "HAS_NPN", r);
4396
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004397#ifdef HAVE_ALPN
4398 r = Py_True;
4399#else
4400 r = Py_False;
4401#endif
4402 Py_INCREF(r);
4403 PyModule_AddObject(m, "HAS_ALPN", r);
4404
Christian Heimesb9a860f2017-09-07 22:31:17 -07004405#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4406 r = Py_True;
4407#else
4408 r = Py_False;
4409#endif
4410 Py_INCREF(r);
4411 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4412
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004413 /* Mappings for error codes */
4414 err_codes_to_names = PyDict_New();
4415 err_names_to_codes = PyDict_New();
4416 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4417 return;
4418 errcode = error_codes;
4419 while (errcode->mnemonic != NULL) {
4420 PyObject *mnemo, *key;
4421 mnemo = PyUnicode_FromString(errcode->mnemonic);
4422 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4423 if (mnemo == NULL || key == NULL)
4424 return;
4425 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4426 return;
4427 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4428 return;
4429 Py_DECREF(key);
4430 Py_DECREF(mnemo);
4431 errcode++;
4432 }
4433 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4434 return;
4435 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4436 return;
4437
4438 lib_codes_to_names = PyDict_New();
4439 if (lib_codes_to_names == NULL)
4440 return;
4441 libcode = library_codes;
4442 while (libcode->library != NULL) {
4443 PyObject *mnemo, *key;
4444 key = PyLong_FromLong(libcode->code);
4445 mnemo = PyUnicode_FromString(libcode->library);
4446 if (key == NULL || mnemo == NULL)
4447 return;
4448 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4449 return;
4450 Py_DECREF(key);
4451 Py_DECREF(mnemo);
4452 libcode++;
4453 }
4454 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4455 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004456
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004457 /* OpenSSL version */
4458 /* SSLeay() gives us the version of the library linked against,
4459 which could be different from the headers version.
4460 */
4461 libver = SSLeay();
4462 r = PyLong_FromUnsignedLong(libver);
4463 if (r == NULL)
4464 return;
4465 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4466 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004467 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004468 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4469 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4470 return;
4471 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4472 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4473 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004474
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004475 libver = OPENSSL_VERSION_NUMBER;
4476 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4477 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4478 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4479 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004480}