blob: d0ce913d3d899282709da55774e571ca9811274d [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
Christian Heimesedd54182018-03-24 19:34:15 +0100105# define PY_OPENSSL_1_1_API 1
106#endif
107
108/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
109#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
110# define PY_OPENSSL_1_1_API 1
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200111#endif
112
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500113/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
114 http://www.openssl.org/news/changelog.html
115 */
116#if OPENSSL_VERSION_NUMBER >= 0x10001000L
117# define HAVE_TLSv1_2 1
118#else
119# define HAVE_TLSv1_2 0
120#endif
121
122/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
123 * This includes the SSL_set_SSL_CTX() function.
124 */
125#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
126# define HAVE_SNI 1
127#else
128# define HAVE_SNI 0
129#endif
130
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500131/* ALPN added in OpenSSL 1.0.2 */
Christian Heimesdf1732a2018-02-25 14:28:55 +0100132#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
133# define HAVE_ALPN 1
134#else
135# define HAVE_ALPN 0
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500136#endif
137
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100138/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
139 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
140 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
141 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimesdf1732a2018-02-25 14:28:55 +0100142 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100143 */
144#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimesdf1732a2018-02-25 14:28:55 +0100145# define HAVE_NPN 0
146#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
147# define HAVE_NPN 0
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100148#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimesdf1732a2018-02-25 14:28:55 +0100149# define HAVE_NPN 1
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100150#else
Christian Heimesdf1732a2018-02-25 14:28:55 +0100151# define HAVE_NPN 0
152#endif
Christian Heimes3d87f4c2018-02-25 10:21:03 +0100153
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200154#ifndef INVALID_SOCKET /* MS defines this */
155#define INVALID_SOCKET (-1)
156#endif
157
Christian Heimesedd54182018-03-24 19:34:15 +0100158/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
159#if !defined(OPENSSL_VERSION_1_1) && defined(WITH_THREAD)
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200160#define HAVE_OPENSSL_CRYPTO_LOCK
161#endif
162
Christian Heimesedd54182018-03-24 19:34:15 +0100163#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
164#define OPENSSL_NO_SSL2
165#endif
166
167#ifndef PY_OPENSSL_1_1_API
168/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
169
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200170#define TLS_method SSLv23_method
171
172static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
173{
174 return ne->set;
175}
176
177#ifndef OPENSSL_NO_COMP
178static int COMP_get_type(const COMP_METHOD *meth)
179{
180 return meth->type;
181}
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200182#endif
183
184static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
185{
186 return ctx->default_passwd_callback;
187}
188
189static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
190{
191 return ctx->default_passwd_callback_userdata;
192}
193
194static int X509_OBJECT_get_type(X509_OBJECT *x)
195{
196 return x->type;
197}
198
199static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
200{
201 return x->data.x509;
202}
203
204static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
205 return store->objs;
206}
207
208static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
209{
210 return store->param;
211}
Christian Heimesedd54182018-03-24 19:34:15 +0100212#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200213
214
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500215enum py_ssl_error {
216 /* these mirror ssl.h */
217 PY_SSL_ERROR_NONE,
218 PY_SSL_ERROR_SSL,
219 PY_SSL_ERROR_WANT_READ,
220 PY_SSL_ERROR_WANT_WRITE,
221 PY_SSL_ERROR_WANT_X509_LOOKUP,
222 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
223 PY_SSL_ERROR_ZERO_RETURN,
224 PY_SSL_ERROR_WANT_CONNECT,
225 /* start of non ssl.h errorcodes */
226 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
227 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
228 PY_SSL_ERROR_INVALID_ERROR_CODE
229};
230
231enum py_ssl_server_or_client {
232 PY_SSL_CLIENT,
233 PY_SSL_SERVER
234};
235
236enum py_ssl_cert_requirements {
237 PY_SSL_CERT_NONE,
238 PY_SSL_CERT_OPTIONAL,
239 PY_SSL_CERT_REQUIRED
240};
241
242enum py_ssl_version {
243 PY_SSL_VERSION_SSL2,
244 PY_SSL_VERSION_SSL3=1,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200245 PY_SSL_VERSION_TLS,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500246#if HAVE_TLSv1_2
247 PY_SSL_VERSION_TLS1,
248 PY_SSL_VERSION_TLS1_1,
249 PY_SSL_VERSION_TLS1_2
250#else
251 PY_SSL_VERSION_TLS1
252#endif
253};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000254
Bill Janssen98d19da2007-09-10 21:51:02 +0000255#ifdef WITH_THREAD
256
257/* serves as a flag to see whether we've initialized the SSL thread support. */
258/* 0 means no, greater than 0 means yes */
259
260static unsigned int _ssl_locks_count = 0;
261
262#endif /* def WITH_THREAD */
263
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000264/* SSL socket object */
265
266#define X509_NAME_MAXLEN 256
267
268/* RAND_* APIs got added to OpenSSL in 0.9.5 */
269#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
270# define HAVE_OPENSSL_RAND 1
271#else
272# undef HAVE_OPENSSL_RAND
273#endif
274
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500275/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
276 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
277 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
278#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
279# define HAVE_SSL_CTX_CLEAR_OPTIONS
280#else
281# undef HAVE_SSL_CTX_CLEAR_OPTIONS
282#endif
283
284/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
285 * older SSL, but let's be safe */
286#define PySSL_CB_MAXLEN 128
287
288/* SSL_get_finished got added to OpenSSL in 0.9.5 */
289#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
290# define HAVE_OPENSSL_FINISHED 1
291#else
292# define HAVE_OPENSSL_FINISHED 0
293#endif
294
295/* ECDH support got added to OpenSSL in 0.9.8 */
296#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
297# define OPENSSL_NO_ECDH
298#endif
299
300/* compression support got added to OpenSSL in 0.9.8 */
301#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
302# define OPENSSL_NO_COMP
303#endif
304
305/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
306#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
307# define HAVE_OPENSSL_VERIFY_PARAM
308#endif
309
310
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000312 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500313 SSL_CTX *ctx;
Christian Heimesdf1732a2018-02-25 14:28:55 +0100314#if HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500315 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500316 int npn_protocols_len;
317#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +0100318#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500319 unsigned char *alpn_protocols;
320 int alpn_protocols_len;
321#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500322#ifndef OPENSSL_NO_TLSEXT
323 PyObject *set_hostname;
324#endif
325 int check_hostname;
326} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000327
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500328typedef struct {
329 PyObject_HEAD
330 PySocketSockObject *Socket;
331 PyObject *ssl_sock;
332 SSL *ssl;
333 PySSLContext *ctx; /* weakref to SSL context */
334 X509 *peer_cert;
335 char shutdown_seen_zero;
336 char handshake_done;
337 enum py_ssl_server_or_client socket_type;
338} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000339
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500340static PyTypeObject PySSLContext_Type;
341static PyTypeObject PySSLSocket_Type;
342
343static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
344static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000345static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000346 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500347static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
348static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000349
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500350#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
351#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000352
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000353typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000354 SOCKET_IS_NONBLOCKING,
355 SOCKET_IS_BLOCKING,
356 SOCKET_HAS_TIMED_OUT,
357 SOCKET_HAS_BEEN_CLOSED,
358 SOCKET_TOO_LARGE_FOR_SELECT,
359 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000360} timeout_state;
361
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000362/* Wrap error strings with filename and line # */
363#define STRINGIFY1(x) #x
364#define STRINGIFY2(x) STRINGIFY1(x)
365#define ERRSTR1(x,y,z) (x ":" y ": " z)
366#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
367
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500368
369/*
370 * SSL errors.
371 */
372
373PyDoc_STRVAR(SSLError_doc,
374"An error occurred in the SSL implementation.");
375
376PyDoc_STRVAR(SSLZeroReturnError_doc,
377"SSL/TLS session closed cleanly.");
378
379PyDoc_STRVAR(SSLWantReadError_doc,
380"Non-blocking SSL socket needs to read more data\n"
381"before the requested operation can be completed.");
382
383PyDoc_STRVAR(SSLWantWriteError_doc,
384"Non-blocking SSL socket needs to write more data\n"
385"before the requested operation can be completed.");
386
387PyDoc_STRVAR(SSLSyscallError_doc,
388"System error when attempting SSL operation.");
389
390PyDoc_STRVAR(SSLEOFError_doc,
391"SSL/TLS connection terminated abruptly.");
392
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000393
394static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500395SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000396{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500397 if (self->strerror != NULL) {
398 Py_INCREF(self->strerror);
399 return self->strerror;
400 }
401 else
402 return PyObject_Str(self->args);
403}
404
405static void
406fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
407 int lineno, unsigned long errcode)
408{
409 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
410 PyObject *init_value, *msg, *key;
411
412 if (errcode != 0) {
413 int lib, reason;
414
415 lib = ERR_GET_LIB(errcode);
416 reason = ERR_GET_REASON(errcode);
417 key = Py_BuildValue("ii", lib, reason);
418 if (key == NULL)
419 goto fail;
420 reason_obj = PyDict_GetItem(err_codes_to_names, key);
421 Py_DECREF(key);
422 if (reason_obj == NULL) {
423 /* XXX if reason < 100, it might reflect a library number (!!) */
424 PyErr_Clear();
425 }
426 key = PyLong_FromLong(lib);
427 if (key == NULL)
428 goto fail;
429 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
430 Py_DECREF(key);
431 if (lib_obj == NULL) {
432 PyErr_Clear();
433 }
434 if (errstr == NULL)
435 errstr = ERR_reason_error_string(errcode);
436 }
437 if (errstr == NULL)
438 errstr = "unknown error";
439
440 if (reason_obj && lib_obj)
441 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
442 lib_obj, reason_obj, errstr, lineno);
443 else if (lib_obj)
444 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
445 lib_obj, errstr, lineno);
446 else
447 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
448 if (msg == NULL)
449 goto fail;
450
451 init_value = Py_BuildValue("iN", ssl_errno, msg);
452 if (init_value == NULL)
453 goto fail;
454
455 err_value = PyObject_CallObject(type, init_value);
456 Py_DECREF(init_value);
457 if (err_value == NULL)
458 goto fail;
459
460 if (reason_obj == NULL)
461 reason_obj = Py_None;
462 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
463 goto fail;
464 if (lib_obj == NULL)
465 lib_obj = Py_None;
466 if (PyObject_SetAttrString(err_value, "library", lib_obj))
467 goto fail;
468 PyErr_SetObject(type, err_value);
469fail:
470 Py_XDECREF(err_value);
471}
472
473static PyObject *
474PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
475{
476 PyObject *type = PySSLErrorObject;
477 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000478 int err;
479 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500480 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000482 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500483 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000484
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000485 if (obj->ssl != NULL) {
486 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000487
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000488 switch (err) {
489 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500490 errstr = "TLS/SSL connection has been closed (EOF)";
491 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000492 p = PY_SSL_ERROR_ZERO_RETURN;
493 break;
494 case SSL_ERROR_WANT_READ:
495 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500496 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000497 p = PY_SSL_ERROR_WANT_READ;
498 break;
499 case SSL_ERROR_WANT_WRITE:
500 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500501 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000502 errstr = "The operation did not complete (write)";
503 break;
504 case SSL_ERROR_WANT_X509_LOOKUP:
505 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000506 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000507 break;
508 case SSL_ERROR_WANT_CONNECT:
509 p = PY_SSL_ERROR_WANT_CONNECT;
510 errstr = "The operation did not complete (connect)";
511 break;
512 case SSL_ERROR_SYSCALL:
513 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000514 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500515 PySocketSockObject *s = obj->Socket;
516 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000517 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500518 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000519 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000520 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000521 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500522 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000523 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500524 s->errorhandler();
525 Py_DECREF(s);
526 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000527 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000528 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500529 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000530 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000531 }
532 } else {
533 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000534 }
535 break;
536 }
537 case SSL_ERROR_SSL:
538 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000539 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500540 if (e == 0)
541 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000542 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000543 break;
544 }
545 default:
546 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
547 errstr = "Invalid error code";
548 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000549 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500550 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000551 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000552 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000553}
554
Bill Janssen98d19da2007-09-10 21:51:02 +0000555static PyObject *
556_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
557
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500558 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000559 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500560 else
561 errcode = 0;
562 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000563 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000564 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000565}
566
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500567/*
568 * SSL objects
569 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000570
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500571static PySSLSocket *
572newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
573 enum py_ssl_server_or_client socket_type,
574 char *server_hostname, PyObject *ssl_sock)
575{
576 PySSLSocket *self;
577 SSL_CTX *ctx = sslctx->ctx;
578 long mode;
579
580 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000581 if (self == NULL)
582 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500583
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000584 self->peer_cert = NULL;
585 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000586 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500587 self->ssl_sock = NULL;
588 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200589 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500590 self->handshake_done = 0;
591 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000592
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000593 /* Make sure the SSL error state is initialized */
594 (void) ERR_get_state();
595 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000596
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000597 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500598 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500600 SSL_set_app_data(self->ssl,self);
601 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
602 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000603#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500604 mode |= SSL_MODE_AUTO_RETRY;
605#endif
606 SSL_set_mode(self->ssl, mode);
607
608#if HAVE_SNI
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800609 if (server_hostname != NULL) {
610/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
611 * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
612 * available on all platforms. Use OpenSSL's IP address parser. It's
613 * available since 1.0.2 and LibreSSL since at least 2.3.0. */
614 int send_sni = 1;
615#if OPENSSL_VERSION_NUMBER >= 0x10200000L
616 ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
617 if (ip == NULL) {
618 send_sni = 1;
619 ERR_clear_error();
620 } else {
621 send_sni = 0;
622 ASN1_OCTET_STRING_free(ip);
623 }
624#elif defined(HAVE_INET_PTON)
625#ifdef ENABLE_IPV6
Christian Heimes439956a2018-02-25 13:08:05 +0100626 #define PySSL_MAX(x, y) (((x) > (y)) ? (x) : (y))
627 char packed[PySSL_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800628#else
629 char packed[sizeof(struct in_addr)];
630#endif /* ENABLE_IPV6 */
631 if (inet_pton(AF_INET, server_hostname, packed)) {
632 send_sni = 0;
633#ifdef ENABLE_IPV6
634 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
635 send_sni = 0;
636#endif /* ENABLE_IPV6 */
637 } else {
638 send_sni = 1;
639 }
640#endif /* HAVE_INET_PTON */
641 if (send_sni) {
642 SSL_set_tlsext_host_name(self->ssl, server_hostname);
643 }
644 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000645#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000646
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000647 /* If the socket is in non-blocking mode or timeout mode, set the BIO
648 * to non-blocking mode (blocking is the default)
649 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500650 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000651 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
652 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
653 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000654
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000655 PySSL_BEGIN_ALLOW_THREADS
656 if (socket_type == PY_SSL_CLIENT)
657 SSL_set_connect_state(self->ssl);
658 else
659 SSL_set_accept_state(self->ssl);
660 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000661
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500662 self->socket_type = socket_type;
663 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000664 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400665 if (ssl_sock != Py_None) {
666 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
667 if (self->ssl_sock == NULL) {
668 Py_DECREF(self);
669 return NULL;
670 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500671 }
672 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000673}
674
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000675
676/* SSL object methods */
677
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500678static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000679{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000680 int ret;
681 int err;
682 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500683 PySocketSockObject *sock = self->Socket;
684
685 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000686
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000687 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500688 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000689 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
690 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000691
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000692 /* Actually negotiate SSL connection */
693 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
694 do {
695 PySSL_BEGIN_ALLOW_THREADS
696 ret = SSL_do_handshake(self->ssl);
697 err = SSL_get_error(self->ssl, ret);
698 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500699 if (PyErr_CheckSignals())
700 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000701 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500702 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000703 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500704 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 } else {
706 sockstate = SOCKET_OPERATION_OK;
707 }
708 if (sockstate == SOCKET_HAS_TIMED_OUT) {
709 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000710 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500711 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000712 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
713 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000714 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500715 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000716 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
717 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000718 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500719 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000720 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
721 break;
722 }
723 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500724 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000725 if (ret < 1)
726 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000727
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000728 if (self->peer_cert)
729 X509_free (self->peer_cert);
730 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500731 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000732 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500733 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000734
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000735 Py_INCREF(Py_None);
736 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000737
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500738error:
739 Py_DECREF(sock);
740 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000741}
742
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000743static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200744_asn1obj2py(const ASN1_OBJECT *name, int no_name)
745{
746 char buf[X509_NAME_MAXLEN];
747 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000748 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200749 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000750
Christian Heimesc9d668c2017-09-05 19:13:07 +0200751 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000752 if (buflen < 0) {
753 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200754 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000755 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200756 /* initial buffer is too small for oid + terminating null byte */
757 if (buflen > X509_NAME_MAXLEN - 1) {
758 /* make OBJ_obj2txt() calculate the required buflen */
759 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
760 /* allocate len + 1 for terminating NULL byte */
761 namebuf = PyMem_Malloc(buflen + 1);
762 if (namebuf == NULL) {
763 PyErr_NoMemory();
764 return NULL;
765 }
766 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
767 if (buflen < 0) {
768 _setSSLError(NULL, 0, __FILE__, __LINE__);
769 goto done;
770 }
771 }
772 if (!buflen && no_name) {
773 Py_INCREF(Py_None);
774 name_obj = Py_None;
775 }
776 else {
777 name_obj = PyString_FromStringAndSize(namebuf, buflen);
778 }
779
780 done:
781 if (buf != namebuf) {
782 PyMem_Free(namebuf);
783 }
784 return name_obj;
785}
786
787static PyObject *
788_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
789{
790 Py_ssize_t buflen;
791 unsigned char *valuebuf = NULL;
792 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000793
794 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
795 if (buflen < 0) {
796 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200797 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000798 }
799 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000800 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000801
Christian Heimesc9d668c2017-09-05 19:13:07 +0200802 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
803 OPENSSL_free(valuebuf);
804 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000805}
806
807static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000808_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000809{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000810 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
811 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
812 PyObject *rdnt;
813 PyObject *attr = NULL; /* tuple to hold an attribute */
814 int entry_count = X509_NAME_entry_count(xname);
815 X509_NAME_ENTRY *entry;
816 ASN1_OBJECT *name;
817 ASN1_STRING *value;
818 int index_counter;
819 int rdn_level = -1;
820 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000822 dn = PyList_New(0);
823 if (dn == NULL)
824 return NULL;
825 /* now create another tuple to hold the top-level RDN */
826 rdn = PyList_New(0);
827 if (rdn == NULL)
828 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000829
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000830 for (index_counter = 0;
831 index_counter < entry_count;
832 index_counter++)
833 {
834 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000835
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000836 /* check to see if we've gotten to a new RDN */
837 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200838 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000839 /* yes, new RDN */
840 /* add old RDN to DN */
841 rdnt = PyList_AsTuple(rdn);
842 Py_DECREF(rdn);
843 if (rdnt == NULL)
844 goto fail0;
845 retcode = PyList_Append(dn, rdnt);
846 Py_DECREF(rdnt);
847 if (retcode < 0)
848 goto fail0;
849 /* create new RDN */
850 rdn = PyList_New(0);
851 if (rdn == NULL)
852 goto fail0;
853 }
854 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200855 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000856
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000857 /* now add this attribute to the current RDN */
858 name = X509_NAME_ENTRY_get_object(entry);
859 value = X509_NAME_ENTRY_get_data(entry);
860 attr = _create_tuple_for_attribute(name, value);
861 /*
862 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
863 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500864 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
865 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000866 */
867 if (attr == NULL)
868 goto fail1;
869 retcode = PyList_Append(rdn, attr);
870 Py_DECREF(attr);
871 if (retcode < 0)
872 goto fail1;
873 }
874 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100875 if (rdn != NULL) {
876 if (PyList_GET_SIZE(rdn) > 0) {
877 rdnt = PyList_AsTuple(rdn);
878 Py_DECREF(rdn);
879 if (rdnt == NULL)
880 goto fail0;
881 retcode = PyList_Append(dn, rdnt);
882 Py_DECREF(rdnt);
883 if (retcode < 0)
884 goto fail0;
885 }
886 else {
887 Py_DECREF(rdn);
888 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000889 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000890
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000891 /* convert list to tuple */
892 rdnt = PyList_AsTuple(dn);
893 Py_DECREF(dn);
894 if (rdnt == NULL)
895 return NULL;
896 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000897
898 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000899 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000900
901 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000902 Py_XDECREF(dn);
903 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000904}
905
906static PyObject *
907_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000908
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000909 /* this code follows the procedure outlined in
910 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
911 function to extract the STACK_OF(GENERAL_NAME),
912 then iterates through the stack to add the
913 names. */
914
915 int i, j;
916 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200917 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000918 X509_EXTENSION *ext = NULL;
919 GENERAL_NAMES *names = NULL;
920 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000921 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000922 BIO *biobuf = NULL;
923 char buf[2048];
924 char *vptr;
925 int len;
926 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000927#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000929#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000930 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000931#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000932
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000933 if (certificate == NULL)
934 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000935
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000936 /* get a memory buffer */
937 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000938
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200939 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000940 while ((i = X509_get_ext_by_NID(
941 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000942
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000943 if (peer_alt_names == Py_None) {
944 peer_alt_names = PyList_New(0);
945 if (peer_alt_names == NULL)
946 goto fail;
947 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000948
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000949 /* now decode the altName */
950 ext = X509_get_ext(certificate, i);
951 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500952 PyErr_SetString
953 (PySSLErrorObject,
954 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000955 goto fail;
956 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000957
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200958 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000959 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500960 names = (GENERAL_NAMES*)
961 (ASN1_item_d2i(NULL,
962 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200963 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500964 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000965 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500966 names = (GENERAL_NAMES*)
967 (method->d2i(NULL,
968 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200969 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000970
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000971 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000972 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200973 int gntype;
974 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000975
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000976 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200977 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200978 switch (gntype) {
979 case GEN_DIRNAME:
980 /* we special-case DirName as a tuple of
981 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000982
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000983 t = PyTuple_New(2);
984 if (t == NULL) {
985 goto fail;
986 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000987
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000988 v = PyString_FromString("DirName");
989 if (v == NULL) {
990 Py_DECREF(t);
991 goto fail;
992 }
993 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000994
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000995 v = _create_tuple_for_X509_NAME (name->d.dirn);
996 if (v == NULL) {
997 Py_DECREF(t);
998 goto fail;
999 }
1000 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001001 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001002
Christian Heimes88b174c2013-08-17 00:54:47 +02001003 case GEN_EMAIL:
1004 case GEN_DNS:
1005 case GEN_URI:
1006 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1007 correctly, CVE-2013-4238 */
1008 t = PyTuple_New(2);
1009 if (t == NULL)
1010 goto fail;
1011 switch (gntype) {
1012 case GEN_EMAIL:
1013 v = PyString_FromString("email");
1014 as = name->d.rfc822Name;
1015 break;
1016 case GEN_DNS:
1017 v = PyString_FromString("DNS");
1018 as = name->d.dNSName;
1019 break;
1020 case GEN_URI:
1021 v = PyString_FromString("URI");
1022 as = name->d.uniformResourceIdentifier;
1023 break;
1024 }
1025 if (v == NULL) {
1026 Py_DECREF(t);
1027 goto fail;
1028 }
1029 PyTuple_SET_ITEM(t, 0, v);
1030 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1031 ASN1_STRING_length(as));
1032 if (v == NULL) {
1033 Py_DECREF(t);
1034 goto fail;
1035 }
1036 PyTuple_SET_ITEM(t, 1, v);
1037 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001038
Christian Heimes6663eb62016-09-06 23:25:35 +02001039 case GEN_RID:
1040 t = PyTuple_New(2);
1041 if (t == NULL)
1042 goto fail;
1043
1044 v = PyUnicode_FromString("Registered ID");
1045 if (v == NULL) {
1046 Py_DECREF(t);
1047 goto fail;
1048 }
1049 PyTuple_SET_ITEM(t, 0, v);
1050
1051 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1052 if (len < 0) {
1053 Py_DECREF(t);
1054 _setSSLError(NULL, 0, __FILE__, __LINE__);
1055 goto fail;
1056 } else if (len >= (int)sizeof(buf)) {
1057 v = PyUnicode_FromString("<INVALID>");
1058 } else {
1059 v = PyUnicode_FromStringAndSize(buf, len);
1060 }
1061 if (v == NULL) {
1062 Py_DECREF(t);
1063 goto fail;
1064 }
1065 PyTuple_SET_ITEM(t, 1, v);
1066 break;
1067
Christian Heimes88b174c2013-08-17 00:54:47 +02001068 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001069 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001070 switch (gntype) {
1071 /* check for new general name type */
1072 case GEN_OTHERNAME:
1073 case GEN_X400:
1074 case GEN_EDIPARTY:
1075 case GEN_IPADD:
1076 case GEN_RID:
1077 break;
1078 default:
1079 if (PyErr_Warn(PyExc_RuntimeWarning,
1080 "Unknown general name type") == -1) {
1081 goto fail;
1082 }
1083 break;
1084 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001085 (void) BIO_reset(biobuf);
1086 GENERAL_NAME_print(biobuf, name);
1087 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1088 if (len < 0) {
1089 _setSSLError(NULL, 0, __FILE__, __LINE__);
1090 goto fail;
1091 }
1092 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001093 if (vptr == NULL) {
1094 PyErr_Format(PyExc_ValueError,
1095 "Invalid value %.200s",
1096 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001097 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001098 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001099 t = PyTuple_New(2);
1100 if (t == NULL)
1101 goto fail;
1102 v = PyString_FromStringAndSize(buf, (vptr - buf));
1103 if (v == NULL) {
1104 Py_DECREF(t);
1105 goto fail;
1106 }
1107 PyTuple_SET_ITEM(t, 0, v);
1108 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1109 if (v == NULL) {
1110 Py_DECREF(t);
1111 goto fail;
1112 }
1113 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001114 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001115 }
1116
1117 /* and add that rendering to the list */
1118
1119 if (PyList_Append(peer_alt_names, t) < 0) {
1120 Py_DECREF(t);
1121 goto fail;
1122 }
1123 Py_DECREF(t);
1124 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001125 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001126 }
1127 BIO_free(biobuf);
1128 if (peer_alt_names != Py_None) {
1129 v = PyList_AsTuple(peer_alt_names);
1130 Py_DECREF(peer_alt_names);
1131 return v;
1132 } else {
1133 return peer_alt_names;
1134 }
1135
Bill Janssen98d19da2007-09-10 21:51:02 +00001136
1137 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001138 if (biobuf != NULL)
1139 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001140
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001141 if (peer_alt_names != Py_None) {
1142 Py_XDECREF(peer_alt_names);
1143 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001144
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001145 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001146}
1147
1148static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001149_get_aia_uri(X509 *certificate, int nid) {
1150 PyObject *lst = NULL, *ostr = NULL;
1151 int i, result;
1152 AUTHORITY_INFO_ACCESS *info;
1153
1154 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001155 if (info == NULL)
1156 return Py_None;
1157 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1158 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001159 return Py_None;
1160 }
1161
1162 if ((lst = PyList_New(0)) == NULL) {
1163 goto fail;
1164 }
1165
1166 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1167 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1168 ASN1_IA5STRING *uri;
1169
1170 if ((OBJ_obj2nid(ad->method) != nid) ||
1171 (ad->location->type != GEN_URI)) {
1172 continue;
1173 }
1174 uri = ad->location->d.uniformResourceIdentifier;
1175 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1176 uri->length);
1177 if (ostr == NULL) {
1178 goto fail;
1179 }
1180 result = PyList_Append(lst, ostr);
1181 Py_DECREF(ostr);
1182 if (result < 0) {
1183 goto fail;
1184 }
1185 }
1186 AUTHORITY_INFO_ACCESS_free(info);
1187
1188 /* convert to tuple or None */
1189 if (PyList_Size(lst) == 0) {
1190 Py_DECREF(lst);
1191 return Py_None;
1192 } else {
1193 PyObject *tup;
1194 tup = PyList_AsTuple(lst);
1195 Py_DECREF(lst);
1196 return tup;
1197 }
1198
1199 fail:
1200 AUTHORITY_INFO_ACCESS_free(info);
1201 Py_XDECREF(lst);
1202 return NULL;
1203}
1204
1205static PyObject *
1206_get_crl_dp(X509 *certificate) {
1207 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001208 int i, j;
1209 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001210
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001211 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001212
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001213 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001214 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001215
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001216 lst = PyList_New(0);
1217 if (lst == NULL)
1218 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001219
1220 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1221 DIST_POINT *dp;
1222 STACK_OF(GENERAL_NAME) *gns;
1223
1224 dp = sk_DIST_POINT_value(dps, i);
1225 gns = dp->distpoint->name.fullname;
1226
1227 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1228 GENERAL_NAME *gn;
1229 ASN1_IA5STRING *uri;
1230 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001231 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001232
1233 gn = sk_GENERAL_NAME_value(gns, j);
1234 if (gn->type != GEN_URI) {
1235 continue;
1236 }
1237 uri = gn->d.uniformResourceIdentifier;
1238 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1239 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001240 if (ouri == NULL)
1241 goto done;
1242
1243 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001244 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001245 if (err < 0)
1246 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001247 }
1248 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001249
1250 /* Convert to tuple. */
1251 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1252
1253 done:
1254 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001255 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001256 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001257}
1258
1259static PyObject *
1260_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001261
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001262 PyObject *retval = NULL;
1263 BIO *biobuf = NULL;
1264 PyObject *peer;
1265 PyObject *peer_alt_names = NULL;
1266 PyObject *issuer;
1267 PyObject *version;
1268 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001269 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001270 ASN1_INTEGER *serialNumber;
1271 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001272 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001273 ASN1_TIME *notBefore, *notAfter;
1274 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001275
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001276 retval = PyDict_New();
1277 if (retval == NULL)
1278 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001279
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001280 peer = _create_tuple_for_X509_NAME(
1281 X509_get_subject_name(certificate));
1282 if (peer == NULL)
1283 goto fail0;
1284 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1285 Py_DECREF(peer);
1286 goto fail0;
1287 }
1288 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001289
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001290 issuer = _create_tuple_for_X509_NAME(
1291 X509_get_issuer_name(certificate));
1292 if (issuer == NULL)
1293 goto fail0;
1294 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001295 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001296 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001297 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001298 Py_DECREF(issuer);
1299
1300 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1301 if (version == NULL)
1302 goto fail0;
1303 if (PyDict_SetItemString(retval, "version", version) < 0) {
1304 Py_DECREF(version);
1305 goto fail0;
1306 }
1307 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001308
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001309 /* get a memory buffer */
1310 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001311
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001312 (void) BIO_reset(biobuf);
1313 serialNumber = X509_get_serialNumber(certificate);
1314 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1315 i2a_ASN1_INTEGER(biobuf, serialNumber);
1316 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1317 if (len < 0) {
1318 _setSSLError(NULL, 0, __FILE__, __LINE__);
1319 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001320 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001321 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1322 if (sn_obj == NULL)
1323 goto fail1;
1324 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1325 Py_DECREF(sn_obj);
1326 goto fail1;
1327 }
1328 Py_DECREF(sn_obj);
1329
1330 (void) BIO_reset(biobuf);
1331 notBefore = X509_get_notBefore(certificate);
1332 ASN1_TIME_print(biobuf, notBefore);
1333 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1334 if (len < 0) {
1335 _setSSLError(NULL, 0, __FILE__, __LINE__);
1336 goto fail1;
1337 }
1338 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1339 if (pnotBefore == NULL)
1340 goto fail1;
1341 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1342 Py_DECREF(pnotBefore);
1343 goto fail1;
1344 }
1345 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001346
1347 (void) BIO_reset(biobuf);
1348 notAfter = X509_get_notAfter(certificate);
1349 ASN1_TIME_print(biobuf, notAfter);
1350 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1351 if (len < 0) {
1352 _setSSLError(NULL, 0, __FILE__, __LINE__);
1353 goto fail1;
1354 }
1355 pnotAfter = PyString_FromStringAndSize(buf, len);
1356 if (pnotAfter == NULL)
1357 goto fail1;
1358 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1359 Py_DECREF(pnotAfter);
1360 goto fail1;
1361 }
1362 Py_DECREF(pnotAfter);
1363
1364 /* Now look for subjectAltName */
1365
1366 peer_alt_names = _get_peer_alt_names(certificate);
1367 if (peer_alt_names == NULL)
1368 goto fail1;
1369 else if (peer_alt_names != Py_None) {
1370 if (PyDict_SetItemString(retval, "subjectAltName",
1371 peer_alt_names) < 0) {
1372 Py_DECREF(peer_alt_names);
1373 goto fail1;
1374 }
1375 Py_DECREF(peer_alt_names);
1376 }
1377
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001378 /* Authority Information Access: OCSP URIs */
1379 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1380 if (obj == NULL) {
1381 goto fail1;
1382 } else if (obj != Py_None) {
1383 result = PyDict_SetItemString(retval, "OCSP", obj);
1384 Py_DECREF(obj);
1385 if (result < 0) {
1386 goto fail1;
1387 }
1388 }
1389
1390 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1391 if (obj == NULL) {
1392 goto fail1;
1393 } else if (obj != Py_None) {
1394 result = PyDict_SetItemString(retval, "caIssuers", obj);
1395 Py_DECREF(obj);
1396 if (result < 0) {
1397 goto fail1;
1398 }
1399 }
1400
1401 /* CDP (CRL distribution points) */
1402 obj = _get_crl_dp(certificate);
1403 if (obj == NULL) {
1404 goto fail1;
1405 } else if (obj != Py_None) {
1406 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1407 Py_DECREF(obj);
1408 if (result < 0) {
1409 goto fail1;
1410 }
1411 }
1412
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001413 BIO_free(biobuf);
1414 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001415
1416 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001417 if (biobuf != NULL)
1418 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001419 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001420 Py_XDECREF(retval);
1421 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001422}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001423
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001424static PyObject *
1425_certificate_to_der(X509 *certificate)
1426{
1427 unsigned char *bytes_buf = NULL;
1428 int len;
1429 PyObject *retval;
1430
1431 bytes_buf = NULL;
1432 len = i2d_X509(certificate, &bytes_buf);
1433 if (len < 0) {
1434 _setSSLError(NULL, 0, __FILE__, __LINE__);
1435 return NULL;
1436 }
1437 /* this is actually an immutable bytes sequence */
1438 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1439 OPENSSL_free(bytes_buf);
1440 return retval;
1441}
Bill Janssen98d19da2007-09-10 21:51:02 +00001442
1443static PyObject *
1444PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1445
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001446 PyObject *retval = NULL;
1447 char *filename = NULL;
1448 X509 *x=NULL;
1449 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001450
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001451 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001453
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001454 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001455 PyErr_SetString(PySSLErrorObject,
1456 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001457 goto fail0;
1458 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001459
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001460 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001461 PyErr_SetString(PySSLErrorObject,
1462 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001463 goto fail0;
1464 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001465
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001466 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1467 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001468 PyErr_SetString(PySSLErrorObject,
1469 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001470 goto fail0;
1471 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001472
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001473 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001474 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001475
1476 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001477
1478 if (cert != NULL) BIO_free(cert);
1479 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001480}
1481
1482
1483static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001484PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001485{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001486 int verification;
1487 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001488 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001489
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001490 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1491 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001492
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001493 if (!self->handshake_done) {
1494 PyErr_SetString(PyExc_ValueError,
1495 "handshake not done yet");
1496 return NULL;
1497 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001498 if (!self->peer_cert)
1499 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001500
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001501 b = PyObject_IsTrue(binary_mode);
1502 if (b < 0)
1503 return NULL;
1504 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001505 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001506 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001507 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001508 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001509 if ((verification & SSL_VERIFY_PEER) == 0)
1510 return PyDict_New();
1511 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001512 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001513 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001514}
1515
1516PyDoc_STRVAR(PySSL_peercert_doc,
1517"peer_certificate([der=False]) -> certificate\n\
1518\n\
1519Returns the certificate for the peer. If no certificate was provided,\n\
1520returns None. If a certificate was provided, but not validated, returns\n\
1521an empty dictionary. Otherwise returns a dict containing information\n\
1522about the peer certificate.\n\
1523\n\
1524If the optional argument is True, returns a DER-encoded copy of the\n\
1525peer certificate, or None if no certificate was provided. This will\n\
1526return the certificate even if it wasn't validated.");
1527
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001528static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001529
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001530 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001531 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001532 char *cipher_name;
1533 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001534
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001535 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001536 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001537 current = SSL_get_current_cipher(self->ssl);
1538 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001539 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001540
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001541 retval = PyTuple_New(3);
1542 if (retval == NULL)
1543 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001544
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001545 cipher_name = (char *) SSL_CIPHER_get_name(current);
1546 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001547 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001548 PyTuple_SET_ITEM(retval, 0, Py_None);
1549 } else {
1550 v = PyString_FromString(cipher_name);
1551 if (v == NULL)
1552 goto fail0;
1553 PyTuple_SET_ITEM(retval, 0, v);
1554 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001555 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001556 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001557 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001558 PyTuple_SET_ITEM(retval, 1, Py_None);
1559 } else {
1560 v = PyString_FromString(cipher_protocol);
1561 if (v == NULL)
1562 goto fail0;
1563 PyTuple_SET_ITEM(retval, 1, v);
1564 }
1565 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1566 if (v == NULL)
1567 goto fail0;
1568 PyTuple_SET_ITEM(retval, 2, v);
1569 return retval;
1570
Bill Janssen98d19da2007-09-10 21:51:02 +00001571 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001572 Py_DECREF(retval);
1573 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001574}
1575
Alex Gaynore98205d2014-09-04 13:33:22 -07001576static PyObject *PySSL_version(PySSLSocket *self)
1577{
1578 const char *version;
1579
1580 if (self->ssl == NULL)
1581 Py_RETURN_NONE;
1582 version = SSL_get_version(self->ssl);
1583 if (!strcmp(version, "unknown"))
1584 Py_RETURN_NONE;
1585 return PyUnicode_FromString(version);
1586}
1587
Christian Heimes72ed2332017-09-05 01:11:40 +02001588#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001589static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1590 const unsigned char *out;
1591 unsigned int outlen;
1592
1593 SSL_get0_next_proto_negotiated(self->ssl,
1594 &out, &outlen);
1595
1596 if (out == NULL)
1597 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001598 return PyString_FromStringAndSize((char *)out, outlen);
1599}
1600#endif
1601
Christian Heimesdf1732a2018-02-25 14:28:55 +01001602#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001603static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1604 const unsigned char *out;
1605 unsigned int outlen;
1606
1607 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1608
1609 if (out == NULL)
1610 Py_RETURN_NONE;
1611 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001612}
1613#endif
1614
1615static PyObject *PySSL_compression(PySSLSocket *self) {
1616#ifdef OPENSSL_NO_COMP
1617 Py_RETURN_NONE;
1618#else
1619 const COMP_METHOD *comp_method;
1620 const char *short_name;
1621
1622 if (self->ssl == NULL)
1623 Py_RETURN_NONE;
1624 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001625 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001626 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001627 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001628 if (short_name == NULL)
1629 Py_RETURN_NONE;
1630 return PyBytes_FromString(short_name);
1631#endif
1632}
1633
1634static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1635 Py_INCREF(self->ctx);
1636 return self->ctx;
1637}
1638
1639static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1640 void *closure) {
1641
1642 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1643#if !HAVE_SNI
1644 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1645 "context is not supported by your OpenSSL library");
1646 return -1;
1647#else
1648 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001649 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001650 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1651#endif
1652 } else {
1653 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1654 return -1;
1655 }
1656
1657 return 0;
1658}
1659
1660PyDoc_STRVAR(PySSL_set_context_doc,
1661"_setter_context(ctx)\n\
1662\
1663This changes the context associated with the SSLSocket. This is typically\n\
1664used from within a callback function set by the set_servername_callback\n\
1665on the SSLContext to change the certificate information associated with the\n\
1666SSLSocket before the cryptographic exchange handshake messages\n");
1667
1668
1669
1670static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001671{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001672 if (self->peer_cert) /* Possible not to have one? */
1673 X509_free (self->peer_cert);
1674 if (self->ssl)
1675 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001676 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001677 Py_XDECREF(self->ssl_sock);
1678 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001679 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001680}
1681
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001682/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001683 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001684 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001685 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001686
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001687static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001688check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001689{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001690 fd_set fds;
1691 struct timeval tv;
1692 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001693
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001694 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1695 if (s->sock_timeout < 0.0)
1696 return SOCKET_IS_BLOCKING;
1697 else if (s->sock_timeout == 0.0)
1698 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001699
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001700 /* Guard against closed socket */
1701 if (s->sock_fd < 0)
1702 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001703
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001704 /* Prefer poll, if available, since you can poll() any fd
1705 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001706#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001707 {
1708 struct pollfd pollfd;
1709 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001710
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001711 pollfd.fd = s->sock_fd;
1712 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001713
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001714 /* s->sock_timeout is in seconds, timeout in ms */
1715 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1716 PySSL_BEGIN_ALLOW_THREADS
1717 rc = poll(&pollfd, 1, timeout);
1718 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001719
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 goto normal_return;
1721 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001722#endif
1723
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001724 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001725 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001726 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001727
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 /* Construct the arguments to select */
1729 tv.tv_sec = (int)s->sock_timeout;
1730 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1731 FD_ZERO(&fds);
1732 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001733
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001734 /* See if the socket is ready */
1735 PySSL_BEGIN_ALLOW_THREADS
1736 if (writing)
1737 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1738 else
1739 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1740 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001741
Bill Janssen934b16d2008-06-28 22:19:33 +00001742#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001743normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001744#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001745 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1746 (when we are able to write or when there's something to read) */
1747 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001748}
1749
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001750static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001751{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001752 Py_buffer buf;
1753 int len;
1754 int sockstate;
1755 int err;
1756 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001757 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001759 Py_INCREF(sock);
1760
1761 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1762 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001763 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001764 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001765
Victor Stinnerc1a44262013-06-25 00:48:02 +02001766 if (buf.len > INT_MAX) {
1767 PyErr_Format(PyExc_OverflowError,
1768 "string longer than %d bytes", INT_MAX);
1769 goto error;
1770 }
1771
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001772 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001773 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001774 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1775 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001776
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001777 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001778 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1779 PyErr_SetString(PySSLErrorObject,
1780 "The write operation timed out");
1781 goto error;
1782 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1783 PyErr_SetString(PySSLErrorObject,
1784 "Underlying socket has been closed.");
1785 goto error;
1786 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1787 PyErr_SetString(PySSLErrorObject,
1788 "Underlying socket too large for select().");
1789 goto error;
1790 }
1791 do {
1792 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001793 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001794 err = SSL_get_error(self->ssl, len);
1795 PySSL_END_ALLOW_THREADS
1796 if (PyErr_CheckSignals()) {
1797 goto error;
1798 }
1799 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001800 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001801 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001802 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001803 } else {
1804 sockstate = SOCKET_OPERATION_OK;
1805 }
1806 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1807 PyErr_SetString(PySSLErrorObject,
1808 "The write operation timed out");
1809 goto error;
1810 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1811 PyErr_SetString(PySSLErrorObject,
1812 "Underlying socket has been closed.");
1813 goto error;
1814 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1815 break;
1816 }
1817 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001818
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001819 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001820 PyBuffer_Release(&buf);
1821 if (len > 0)
1822 return PyInt_FromLong(len);
1823 else
1824 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001825
1826error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001827 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001828 PyBuffer_Release(&buf);
1829 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001830}
1831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001832PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001833"write(s) -> len\n\
1834\n\
1835Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001836of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001837
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001838static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001839{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001840 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001841
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 PySSL_BEGIN_ALLOW_THREADS
1843 count = SSL_pending(self->ssl);
1844 PySSL_END_ALLOW_THREADS
1845 if (count < 0)
1846 return PySSL_SetError(self, count, __FILE__, __LINE__);
1847 else
1848 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001849}
1850
1851PyDoc_STRVAR(PySSL_SSLpending_doc,
1852"pending() -> count\n\
1853\n\
1854Returns the number of already decrypted bytes available for read,\n\
1855pending on the connection.\n");
1856
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001857static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001858{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001859 PyObject *dest = NULL;
1860 Py_buffer buf;
1861 char *mem;
1862 int len, count;
1863 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001864 int sockstate;
1865 int err;
1866 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001867 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001868
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001869 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001870
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001871 buf.obj = NULL;
1872 buf.buf = NULL;
1873 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1874 goto error;
1875
1876 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001877 if (len < 0) {
1878 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1879 goto error;
1880 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001881 dest = PyBytes_FromStringAndSize(NULL, len);
1882 if (dest == NULL)
1883 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001884 if (len == 0) {
1885 Py_XDECREF(sock);
1886 return dest;
1887 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001888 mem = PyBytes_AS_STRING(dest);
1889 }
1890 else {
1891 buf_passed = 1;
1892 mem = buf.buf;
1893 if (len <= 0 || len > buf.len) {
1894 len = (int) buf.len;
1895 if (buf.len != len) {
1896 PyErr_SetString(PyExc_OverflowError,
1897 "maximum length can't fit in a C 'int'");
1898 goto error;
1899 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001900 if (len == 0) {
1901 count = 0;
1902 goto done;
1903 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001904 }
1905 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001906
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001908 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001909 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1910 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001911
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001912 do {
1913 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001914 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001915 err = SSL_get_error(self->ssl, count);
1916 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001917 if (PyErr_CheckSignals())
1918 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001919 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001920 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001921 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001922 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001923 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1924 (SSL_get_shutdown(self->ssl) ==
1925 SSL_RECEIVED_SHUTDOWN))
1926 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001927 count = 0;
1928 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001929 } else {
1930 sockstate = SOCKET_OPERATION_OK;
1931 }
1932 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1933 PyErr_SetString(PySSLErrorObject,
1934 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001935 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001936 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1937 break;
1938 }
1939 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1940 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001941 PySSL_SetError(self, count, __FILE__, __LINE__);
1942 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001943 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001944
1945done:
1946 Py_DECREF(sock);
1947 if (!buf_passed) {
1948 _PyBytes_Resize(&dest, count);
1949 return dest;
1950 }
1951 else {
1952 PyBuffer_Release(&buf);
1953 return PyLong_FromLong(count);
1954 }
1955
1956error:
1957 Py_DECREF(sock);
1958 if (!buf_passed)
1959 Py_XDECREF(dest);
1960 else
1961 PyBuffer_Release(&buf);
1962 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001963}
1964
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001965PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001966"read([len]) -> string\n\
1967\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001968Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001969
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001970static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001971{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001972 int err, ssl_err, sockstate, nonblocking;
1973 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001974 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001975
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001976 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001977 if (sock->sock_fd < 0) {
1978 _setSSLError("Underlying socket connection gone",
1979 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001980 return NULL;
1981 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001982 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001983
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001984 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001985 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001986 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1987 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001988
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001989 while (1) {
1990 PySSL_BEGIN_ALLOW_THREADS
1991 /* Disable read-ahead so that unwrap can work correctly.
1992 * Otherwise OpenSSL might read in too much data,
1993 * eating clear text data that happens to be
1994 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001995 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001996 * function is used and the shutdown_seen_zero != 0
1997 * condition is met.
1998 */
1999 if (self->shutdown_seen_zero)
2000 SSL_set_read_ahead(self->ssl, 0);
2001 err = SSL_shutdown(self->ssl);
2002 PySSL_END_ALLOW_THREADS
2003 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2004 if (err > 0)
2005 break;
2006 if (err == 0) {
2007 /* Don't loop endlessly; instead preserve legacy
2008 behaviour of trying SSL_shutdown() only twice.
2009 This looks necessary for OpenSSL < 0.9.8m */
2010 if (++zeros > 1)
2011 break;
2012 /* Shutdown was sent, now try receiving */
2013 self->shutdown_seen_zero = 1;
2014 continue;
2015 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00002016
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002017 /* Possibly retry shutdown until timeout or failure */
2018 ssl_err = SSL_get_error(self->ssl, err);
2019 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002020 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002021 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002022 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002023 else
2024 break;
2025 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2026 if (ssl_err == SSL_ERROR_WANT_READ)
2027 PyErr_SetString(PySSLErrorObject,
2028 "The read operation timed out");
2029 else
2030 PyErr_SetString(PySSLErrorObject,
2031 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002032 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002033 }
2034 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2035 PyErr_SetString(PySSLErrorObject,
2036 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002037 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002038 }
2039 else if (sockstate != SOCKET_OPERATION_OK)
2040 /* Retain the SSL error code */
2041 break;
2042 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002043
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002044 if (err < 0) {
2045 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002046 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002047 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002048 else
2049 /* It's already INCREF'ed */
2050 return (PyObject *) sock;
2051
2052error:
2053 Py_DECREF(sock);
2054 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002055}
2056
2057PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2058"shutdown(s) -> socket\n\
2059\n\
2060Does the SSL shutdown handshake with the remote end, and returns\n\
2061the underlying socket object.");
2062
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002063#if HAVE_OPENSSL_FINISHED
2064static PyObject *
2065PySSL_tls_unique_cb(PySSLSocket *self)
2066{
2067 PyObject *retval = NULL;
2068 char buf[PySSL_CB_MAXLEN];
2069 size_t len;
2070
2071 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2072 /* if session is resumed XOR we are the client */
2073 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2074 }
2075 else {
2076 /* if a new session XOR we are the server */
2077 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2078 }
2079
2080 /* It cannot be negative in current OpenSSL version as of July 2011 */
2081 if (len == 0)
2082 Py_RETURN_NONE;
2083
2084 retval = PyBytes_FromStringAndSize(buf, len);
2085
2086 return retval;
2087}
2088
2089PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2090"tls_unique_cb() -> bytes\n\
2091\n\
2092Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2093\n\
2094If the TLS handshake is not yet complete, None is returned");
2095
2096#endif /* HAVE_OPENSSL_FINISHED */
2097
2098static PyGetSetDef ssl_getsetlist[] = {
2099 {"context", (getter) PySSL_get_context,
2100 (setter) PySSL_set_context, PySSL_set_context_doc},
2101 {NULL}, /* sentinel */
2102};
2103
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002104static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002105 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2106 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2107 PySSL_SSLwrite_doc},
2108 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2109 PySSL_SSLread_doc},
2110 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2111 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002112 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2113 PySSL_peercert_doc},
2114 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002115 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002116#ifdef OPENSSL_NPN_NEGOTIATED
2117 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2118#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002119#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002120 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2121#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002122 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002123 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2124 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002125#if HAVE_OPENSSL_FINISHED
2126 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2127 PySSL_tls_unique_cb_doc},
2128#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002129 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002130};
2131
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002132static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002133 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002134 "_ssl._SSLSocket", /*tp_name*/
2135 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002136 0, /*tp_itemsize*/
2137 /* methods */
2138 (destructor)PySSL_dealloc, /*tp_dealloc*/
2139 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002140 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002141 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002142 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002143 0, /*tp_repr*/
2144 0, /*tp_as_number*/
2145 0, /*tp_as_sequence*/
2146 0, /*tp_as_mapping*/
2147 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002148 0, /*tp_call*/
2149 0, /*tp_str*/
2150 0, /*tp_getattro*/
2151 0, /*tp_setattro*/
2152 0, /*tp_as_buffer*/
2153 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2154 0, /*tp_doc*/
2155 0, /*tp_traverse*/
2156 0, /*tp_clear*/
2157 0, /*tp_richcompare*/
2158 0, /*tp_weaklistoffset*/
2159 0, /*tp_iter*/
2160 0, /*tp_iternext*/
2161 PySSLMethods, /*tp_methods*/
2162 0, /*tp_members*/
2163 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002164};
2165
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002166
2167/*
2168 * _SSLContext objects
2169 */
2170
2171static PyObject *
2172context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2173{
2174 char *kwlist[] = {"protocol", NULL};
2175 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002176 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002177 long options;
2178 SSL_CTX *ctx = NULL;
2179
2180 if (!PyArg_ParseTupleAndKeywords(
2181 args, kwds, "i:_SSLContext", kwlist,
2182 &proto_version))
2183 return NULL;
2184
2185 PySSL_BEGIN_ALLOW_THREADS
2186 if (proto_version == PY_SSL_VERSION_TLS1)
2187 ctx = SSL_CTX_new(TLSv1_method());
2188#if HAVE_TLSv1_2
2189 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2190 ctx = SSL_CTX_new(TLSv1_1_method());
2191 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2192 ctx = SSL_CTX_new(TLSv1_2_method());
2193#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002194#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002195 else if (proto_version == PY_SSL_VERSION_SSL3)
2196 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002197#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002198#ifndef OPENSSL_NO_SSL2
2199 else if (proto_version == PY_SSL_VERSION_SSL2)
2200 ctx = SSL_CTX_new(SSLv2_method());
2201#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002202 else if (proto_version == PY_SSL_VERSION_TLS)
2203 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002204 else
2205 proto_version = -1;
2206 PySSL_END_ALLOW_THREADS
2207
2208 if (proto_version == -1) {
2209 PyErr_SetString(PyExc_ValueError,
2210 "invalid protocol version");
2211 return NULL;
2212 }
2213 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002214 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002215 return NULL;
2216 }
2217
2218 assert(type != NULL && type->tp_alloc != NULL);
2219 self = (PySSLContext *) type->tp_alloc(type, 0);
2220 if (self == NULL) {
2221 SSL_CTX_free(ctx);
2222 return NULL;
2223 }
2224 self->ctx = ctx;
Christian Heimesdf1732a2018-02-25 14:28:55 +01002225#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002226 self->npn_protocols = NULL;
2227#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002228#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002229 self->alpn_protocols = NULL;
2230#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002231#ifndef OPENSSL_NO_TLSEXT
2232 self->set_hostname = NULL;
2233#endif
2234 /* Don't check host name by default */
2235 self->check_hostname = 0;
2236 /* Defaults */
2237 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2238 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2239 if (proto_version != PY_SSL_VERSION_SSL2)
2240 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002241 if (proto_version != PY_SSL_VERSION_SSL3)
2242 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002243 SSL_CTX_set_options(self->ctx, options);
2244
Donald Stufftf1a696e2017-03-02 12:37:07 -05002245#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002246 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2247 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002248 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2249 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002250#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002251 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2252#else
2253 {
2254 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2255 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2256 EC_KEY_free(key);
2257 }
2258#endif
2259#endif
2260
2261#define SID_CTX "Python"
2262 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2263 sizeof(SID_CTX));
2264#undef SID_CTX
2265
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002266#ifdef X509_V_FLAG_TRUSTED_FIRST
2267 {
2268 /* Improve trust chain building when cross-signed intermediate
2269 certificates are present. See https://bugs.python.org/issue23476. */
2270 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2271 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2272 }
2273#endif
2274
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002275 return (PyObject *)self;
2276}
2277
2278static int
2279context_traverse(PySSLContext *self, visitproc visit, void *arg)
2280{
2281#ifndef OPENSSL_NO_TLSEXT
2282 Py_VISIT(self->set_hostname);
2283#endif
2284 return 0;
2285}
2286
2287static int
2288context_clear(PySSLContext *self)
2289{
2290#ifndef OPENSSL_NO_TLSEXT
2291 Py_CLEAR(self->set_hostname);
2292#endif
2293 return 0;
2294}
2295
2296static void
2297context_dealloc(PySSLContext *self)
2298{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002299 /* bpo-31095: UnTrack is needed before calling any callbacks */
2300 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002301 context_clear(self);
2302 SSL_CTX_free(self->ctx);
Christian Heimesdf1732a2018-02-25 14:28:55 +01002303#if HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002304 PyMem_FREE(self->npn_protocols);
2305#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002306#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002307 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002308#endif
2309 Py_TYPE(self)->tp_free(self);
2310}
2311
2312static PyObject *
2313set_ciphers(PySSLContext *self, PyObject *args)
2314{
2315 int ret;
2316 const char *cipherlist;
2317
2318 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2319 return NULL;
2320 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2321 if (ret == 0) {
2322 /* Clearing the error queue is necessary on some OpenSSL versions,
2323 otherwise the error will be reported again when another SSL call
2324 is done. */
2325 ERR_clear_error();
2326 PyErr_SetString(PySSLErrorObject,
2327 "No cipher can be selected.");
2328 return NULL;
2329 }
2330 Py_RETURN_NONE;
2331}
2332
Christian Heimesdf1732a2018-02-25 14:28:55 +01002333#if HAVE_NPN || HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002334static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002335do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2336 const unsigned char *server_protocols, unsigned int server_protocols_len,
2337 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002338{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002339 int ret;
2340 if (client_protocols == NULL) {
2341 client_protocols = (unsigned char *)"";
2342 client_protocols_len = 0;
2343 }
2344 if (server_protocols == NULL) {
2345 server_protocols = (unsigned char *)"";
2346 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002347 }
2348
Benjamin Petersonaa707582015-01-23 17:30:26 -05002349 ret = SSL_select_next_proto(out, outlen,
2350 server_protocols, server_protocols_len,
2351 client_protocols, client_protocols_len);
2352 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2353 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002354
2355 return SSL_TLSEXT_ERR_OK;
2356}
Christian Heimes72ed2332017-09-05 01:11:40 +02002357#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002358
Christian Heimesdf1732a2018-02-25 14:28:55 +01002359#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002360/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2361static int
2362_advertiseNPN_cb(SSL *s,
2363 const unsigned char **data, unsigned int *len,
2364 void *args)
2365{
2366 PySSLContext *ssl_ctx = (PySSLContext *) args;
2367
2368 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002369 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002370 *len = 0;
2371 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002372 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002373 *len = ssl_ctx->npn_protocols_len;
2374 }
2375
2376 return SSL_TLSEXT_ERR_OK;
2377}
2378/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2379static int
2380_selectNPN_cb(SSL *s,
2381 unsigned char **out, unsigned char *outlen,
2382 const unsigned char *server, unsigned int server_len,
2383 void *args)
2384{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002385 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002386 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002387 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002388}
2389#endif
2390
2391static PyObject *
2392_set_npn_protocols(PySSLContext *self, PyObject *args)
2393{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002394#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002395 Py_buffer protos;
2396
2397 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2398 return NULL;
2399
2400 if (self->npn_protocols != NULL) {
2401 PyMem_Free(self->npn_protocols);
2402 }
2403
2404 self->npn_protocols = PyMem_Malloc(protos.len);
2405 if (self->npn_protocols == NULL) {
2406 PyBuffer_Release(&protos);
2407 return PyErr_NoMemory();
2408 }
2409 memcpy(self->npn_protocols, protos.buf, protos.len);
2410 self->npn_protocols_len = (int) protos.len;
2411
2412 /* set both server and client callbacks, because the context can
2413 * be used to create both types of sockets */
2414 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2415 _advertiseNPN_cb,
2416 self);
2417 SSL_CTX_set_next_proto_select_cb(self->ctx,
2418 _selectNPN_cb,
2419 self);
2420
2421 PyBuffer_Release(&protos);
2422 Py_RETURN_NONE;
2423#else
2424 PyErr_SetString(PyExc_NotImplementedError,
2425 "The NPN extension requires OpenSSL 1.0.1 or later.");
2426 return NULL;
2427#endif
2428}
2429
Christian Heimesdf1732a2018-02-25 14:28:55 +01002430#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002431static int
2432_selectALPN_cb(SSL *s,
2433 const unsigned char **out, unsigned char *outlen,
2434 const unsigned char *client_protocols, unsigned int client_protocols_len,
2435 void *args)
2436{
2437 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002438 return do_protocol_selection(1, (unsigned char **)out, outlen,
2439 ctx->alpn_protocols, ctx->alpn_protocols_len,
2440 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002441}
2442#endif
2443
2444static PyObject *
2445_set_alpn_protocols(PySSLContext *self, PyObject *args)
2446{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002447#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002448 Py_buffer protos;
2449
2450 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2451 return NULL;
2452
2453 PyMem_FREE(self->alpn_protocols);
2454 self->alpn_protocols = PyMem_Malloc(protos.len);
2455 if (!self->alpn_protocols)
2456 return PyErr_NoMemory();
2457 memcpy(self->alpn_protocols, protos.buf, protos.len);
2458 self->alpn_protocols_len = protos.len;
2459 PyBuffer_Release(&protos);
2460
2461 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2462 return PyErr_NoMemory();
2463 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2464
2465 PyBuffer_Release(&protos);
2466 Py_RETURN_NONE;
2467#else
2468 PyErr_SetString(PyExc_NotImplementedError,
2469 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2470 return NULL;
2471#endif
2472}
2473
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002474static PyObject *
2475get_verify_mode(PySSLContext *self, void *c)
2476{
2477 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2478 case SSL_VERIFY_NONE:
2479 return PyLong_FromLong(PY_SSL_CERT_NONE);
2480 case SSL_VERIFY_PEER:
2481 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2482 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2483 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2484 }
2485 PyErr_SetString(PySSLErrorObject,
2486 "invalid return value from SSL_CTX_get_verify_mode");
2487 return NULL;
2488}
2489
2490static int
2491set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2492{
2493 int n, mode;
2494 if (!PyArg_Parse(arg, "i", &n))
2495 return -1;
2496 if (n == PY_SSL_CERT_NONE)
2497 mode = SSL_VERIFY_NONE;
2498 else if (n == PY_SSL_CERT_OPTIONAL)
2499 mode = SSL_VERIFY_PEER;
2500 else if (n == PY_SSL_CERT_REQUIRED)
2501 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2502 else {
2503 PyErr_SetString(PyExc_ValueError,
2504 "invalid value for verify_mode");
2505 return -1;
2506 }
2507 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2508 PyErr_SetString(PyExc_ValueError,
2509 "Cannot set verify_mode to CERT_NONE when "
2510 "check_hostname is enabled.");
2511 return -1;
2512 }
2513 SSL_CTX_set_verify(self->ctx, mode, NULL);
2514 return 0;
2515}
2516
2517#ifdef HAVE_OPENSSL_VERIFY_PARAM
2518static PyObject *
2519get_verify_flags(PySSLContext *self, void *c)
2520{
2521 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002522 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002523 unsigned long flags;
2524
2525 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002526 param = X509_STORE_get0_param(store);
2527 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002528 return PyLong_FromUnsignedLong(flags);
2529}
2530
2531static int
2532set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2533{
2534 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002535 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002536 unsigned long new_flags, flags, set, clear;
2537
2538 if (!PyArg_Parse(arg, "k", &new_flags))
2539 return -1;
2540 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002541 param = X509_STORE_get0_param(store);
2542 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002543 clear = flags & ~new_flags;
2544 set = ~flags & new_flags;
2545 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002546 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002547 _setSSLError(NULL, 0, __FILE__, __LINE__);
2548 return -1;
2549 }
2550 }
2551 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002552 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002553 _setSSLError(NULL, 0, __FILE__, __LINE__);
2554 return -1;
2555 }
2556 }
2557 return 0;
2558}
2559#endif
2560
2561static PyObject *
2562get_options(PySSLContext *self, void *c)
2563{
2564 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2565}
2566
2567static int
2568set_options(PySSLContext *self, PyObject *arg, void *c)
2569{
2570 long new_opts, opts, set, clear;
2571 if (!PyArg_Parse(arg, "l", &new_opts))
2572 return -1;
2573 opts = SSL_CTX_get_options(self->ctx);
2574 clear = opts & ~new_opts;
2575 set = ~opts & new_opts;
2576 if (clear) {
2577#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2578 SSL_CTX_clear_options(self->ctx, clear);
2579#else
2580 PyErr_SetString(PyExc_ValueError,
2581 "can't clear options before OpenSSL 0.9.8m");
2582 return -1;
2583#endif
2584 }
2585 if (set)
2586 SSL_CTX_set_options(self->ctx, set);
2587 return 0;
2588}
2589
2590static PyObject *
2591get_check_hostname(PySSLContext *self, void *c)
2592{
2593 return PyBool_FromLong(self->check_hostname);
2594}
2595
2596static int
2597set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2598{
2599 PyObject *py_check_hostname;
2600 int check_hostname;
2601 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2602 return -1;
2603
2604 check_hostname = PyObject_IsTrue(py_check_hostname);
2605 if (check_hostname < 0)
2606 return -1;
2607 if (check_hostname &&
2608 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2609 PyErr_SetString(PyExc_ValueError,
2610 "check_hostname needs a SSL context with either "
2611 "CERT_OPTIONAL or CERT_REQUIRED");
2612 return -1;
2613 }
2614 self->check_hostname = check_hostname;
2615 return 0;
2616}
2617
2618
2619typedef struct {
2620 PyThreadState *thread_state;
2621 PyObject *callable;
2622 char *password;
2623 int size;
2624 int error;
2625} _PySSLPasswordInfo;
2626
2627static int
2628_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2629 const char *bad_type_error)
2630{
2631 /* Set the password and size fields of a _PySSLPasswordInfo struct
2632 from a unicode, bytes, or byte array object.
2633 The password field will be dynamically allocated and must be freed
2634 by the caller */
2635 PyObject *password_bytes = NULL;
2636 const char *data = NULL;
2637 Py_ssize_t size;
2638
2639 if (PyUnicode_Check(password)) {
2640 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2641 if (!password_bytes) {
2642 goto error;
2643 }
2644 data = PyBytes_AS_STRING(password_bytes);
2645 size = PyBytes_GET_SIZE(password_bytes);
2646 } else if (PyBytes_Check(password)) {
2647 data = PyBytes_AS_STRING(password);
2648 size = PyBytes_GET_SIZE(password);
2649 } else if (PyByteArray_Check(password)) {
2650 data = PyByteArray_AS_STRING(password);
2651 size = PyByteArray_GET_SIZE(password);
2652 } else {
2653 PyErr_SetString(PyExc_TypeError, bad_type_error);
2654 goto error;
2655 }
2656
2657 if (size > (Py_ssize_t)INT_MAX) {
2658 PyErr_Format(PyExc_ValueError,
2659 "password cannot be longer than %d bytes", INT_MAX);
2660 goto error;
2661 }
2662
2663 PyMem_Free(pw_info->password);
2664 pw_info->password = PyMem_Malloc(size);
2665 if (!pw_info->password) {
2666 PyErr_SetString(PyExc_MemoryError,
2667 "unable to allocate password buffer");
2668 goto error;
2669 }
2670 memcpy(pw_info->password, data, size);
2671 pw_info->size = (int)size;
2672
2673 Py_XDECREF(password_bytes);
2674 return 1;
2675
2676error:
2677 Py_XDECREF(password_bytes);
2678 return 0;
2679}
2680
2681static int
2682_password_callback(char *buf, int size, int rwflag, void *userdata)
2683{
2684 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2685 PyObject *fn_ret = NULL;
2686
2687 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2688
2689 if (pw_info->callable) {
2690 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2691 if (!fn_ret) {
2692 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2693 core python API, so we could use it to add a frame here */
2694 goto error;
2695 }
2696
2697 if (!_pwinfo_set(pw_info, fn_ret,
2698 "password callback must return a string")) {
2699 goto error;
2700 }
2701 Py_CLEAR(fn_ret);
2702 }
2703
2704 if (pw_info->size > size) {
2705 PyErr_Format(PyExc_ValueError,
2706 "password cannot be longer than %d bytes", size);
2707 goto error;
2708 }
2709
2710 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2711 memcpy(buf, pw_info->password, pw_info->size);
2712 return pw_info->size;
2713
2714error:
2715 Py_XDECREF(fn_ret);
2716 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2717 pw_info->error = 1;
2718 return -1;
2719}
2720
2721static PyObject *
2722load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2723{
2724 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002725 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2726 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002727 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2728 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002729 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2730 int r;
2731
2732 errno = 0;
2733 ERR_clear_error();
2734 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002735 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002736 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002737 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002738 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002739
2740 if (keyfile && keyfile != Py_None) {
2741 if (PyString_Check(keyfile)) {
2742 Py_INCREF(keyfile);
2743 keyfile_bytes = keyfile;
2744 } else {
2745 PyObject *u = PyUnicode_FromObject(keyfile);
2746 if (!u)
2747 goto error;
2748 keyfile_bytes = PyUnicode_AsEncodedString(
2749 u, Py_FileSystemDefaultEncoding, NULL);
2750 Py_DECREF(u);
2751 if (!keyfile_bytes)
2752 goto error;
2753 }
2754 }
2755
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002756 if (password && password != Py_None) {
2757 if (PyCallable_Check(password)) {
2758 pw_info.callable = password;
2759 } else if (!_pwinfo_set(&pw_info, password,
2760 "password should be a string or callable")) {
2761 goto error;
2762 }
2763 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2764 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2765 }
2766 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2767 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2768 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2769 if (r != 1) {
2770 if (pw_info.error) {
2771 ERR_clear_error();
2772 /* the password callback has already set the error information */
2773 }
2774 else if (errno != 0) {
2775 ERR_clear_error();
2776 PyErr_SetFromErrno(PyExc_IOError);
2777 }
2778 else {
2779 _setSSLError(NULL, 0, __FILE__, __LINE__);
2780 }
2781 goto error;
2782 }
2783 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2784 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002785 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002786 SSL_FILETYPE_PEM);
2787 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2788 if (r != 1) {
2789 if (pw_info.error) {
2790 ERR_clear_error();
2791 /* the password callback has already set the error information */
2792 }
2793 else if (errno != 0) {
2794 ERR_clear_error();
2795 PyErr_SetFromErrno(PyExc_IOError);
2796 }
2797 else {
2798 _setSSLError(NULL, 0, __FILE__, __LINE__);
2799 }
2800 goto error;
2801 }
2802 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2803 r = SSL_CTX_check_private_key(self->ctx);
2804 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2805 if (r != 1) {
2806 _setSSLError(NULL, 0, __FILE__, __LINE__);
2807 goto error;
2808 }
2809 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2810 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002811 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002812 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002813 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002814 Py_RETURN_NONE;
2815
2816error:
2817 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2818 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002819 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002820 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002821 PyMem_Free(certfile_bytes);
2822 return NULL;
2823}
2824
2825/* internal helper function, returns -1 on error
2826 */
2827static int
2828_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2829 int filetype)
2830{
2831 BIO *biobuf = NULL;
2832 X509_STORE *store;
2833 int retval = 0, err, loaded = 0;
2834
2835 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2836
2837 if (len <= 0) {
2838 PyErr_SetString(PyExc_ValueError,
2839 "Empty certificate data");
2840 return -1;
2841 } else if (len > INT_MAX) {
2842 PyErr_SetString(PyExc_OverflowError,
2843 "Certificate data is too long.");
2844 return -1;
2845 }
2846
2847 biobuf = BIO_new_mem_buf(data, (int)len);
2848 if (biobuf == NULL) {
2849 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2850 return -1;
2851 }
2852
2853 store = SSL_CTX_get_cert_store(self->ctx);
2854 assert(store != NULL);
2855
2856 while (1) {
2857 X509 *cert = NULL;
2858 int r;
2859
2860 if (filetype == SSL_FILETYPE_ASN1) {
2861 cert = d2i_X509_bio(biobuf, NULL);
2862 } else {
2863 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002864 SSL_CTX_get_default_passwd_cb(self->ctx),
2865 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2866 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002867 }
2868 if (cert == NULL) {
2869 break;
2870 }
2871 r = X509_STORE_add_cert(store, cert);
2872 X509_free(cert);
2873 if (!r) {
2874 err = ERR_peek_last_error();
2875 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2876 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2877 /* cert already in hash table, not an error */
2878 ERR_clear_error();
2879 } else {
2880 break;
2881 }
2882 }
2883 loaded++;
2884 }
2885
2886 err = ERR_peek_last_error();
2887 if ((filetype == SSL_FILETYPE_ASN1) &&
2888 (loaded > 0) &&
2889 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2890 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2891 /* EOF ASN1 file, not an error */
2892 ERR_clear_error();
2893 retval = 0;
2894 } else if ((filetype == SSL_FILETYPE_PEM) &&
2895 (loaded > 0) &&
2896 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2897 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2898 /* EOF PEM file, not an error */
2899 ERR_clear_error();
2900 retval = 0;
2901 } else {
2902 _setSSLError(NULL, 0, __FILE__, __LINE__);
2903 retval = -1;
2904 }
2905
2906 BIO_free(biobuf);
2907 return retval;
2908}
2909
2910
2911static PyObject *
2912load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2913{
2914 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2915 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2916 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2917 const char *cafile_buf = NULL, *capath_buf = NULL;
2918 int r = 0, ok = 1;
2919
2920 errno = 0;
2921 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2922 "|OOO:load_verify_locations", kwlist,
2923 &cafile, &capath, &cadata))
2924 return NULL;
2925
2926 if (cafile == Py_None)
2927 cafile = NULL;
2928 if (capath == Py_None)
2929 capath = NULL;
2930 if (cadata == Py_None)
2931 cadata = NULL;
2932
2933 if (cafile == NULL && capath == NULL && cadata == NULL) {
2934 PyErr_SetString(PyExc_TypeError,
2935 "cafile, capath and cadata cannot be all omitted");
2936 goto error;
2937 }
2938
2939 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002940 if (PyString_Check(cafile)) {
2941 Py_INCREF(cafile);
2942 cafile_bytes = cafile;
2943 } else {
2944 PyObject *u = PyUnicode_FromObject(cafile);
2945 if (!u)
2946 goto error;
2947 cafile_bytes = PyUnicode_AsEncodedString(
2948 u, Py_FileSystemDefaultEncoding, NULL);
2949 Py_DECREF(u);
2950 if (!cafile_bytes)
2951 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002952 }
2953 }
2954 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002955 if (PyString_Check(capath)) {
2956 Py_INCREF(capath);
2957 capath_bytes = capath;
2958 } else {
2959 PyObject *u = PyUnicode_FromObject(capath);
2960 if (!u)
2961 goto error;
2962 capath_bytes = PyUnicode_AsEncodedString(
2963 u, Py_FileSystemDefaultEncoding, NULL);
2964 Py_DECREF(u);
2965 if (!capath_bytes)
2966 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002967 }
2968 }
2969
2970 /* validata cadata type and load cadata */
2971 if (cadata) {
2972 Py_buffer buf;
2973 PyObject *cadata_ascii = NULL;
2974
2975 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2976 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2977 PyBuffer_Release(&buf);
2978 PyErr_SetString(PyExc_TypeError,
2979 "cadata should be a contiguous buffer with "
2980 "a single dimension");
2981 goto error;
2982 }
2983 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2984 PyBuffer_Release(&buf);
2985 if (r == -1) {
2986 goto error;
2987 }
2988 } else {
2989 PyErr_Clear();
2990 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2991 if (cadata_ascii == NULL) {
2992 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002993 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002994 "bytes-like object");
2995 goto error;
2996 }
2997 r = _add_ca_certs(self,
2998 PyBytes_AS_STRING(cadata_ascii),
2999 PyBytes_GET_SIZE(cadata_ascii),
3000 SSL_FILETYPE_PEM);
3001 Py_DECREF(cadata_ascii);
3002 if (r == -1) {
3003 goto error;
3004 }
3005 }
3006 }
3007
3008 /* load cafile or capath */
3009 if (cafile_bytes || capath_bytes) {
3010 if (cafile)
3011 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3012 if (capath)
3013 capath_buf = PyBytes_AS_STRING(capath_bytes);
3014 PySSL_BEGIN_ALLOW_THREADS
3015 r = SSL_CTX_load_verify_locations(
3016 self->ctx,
3017 cafile_buf,
3018 capath_buf);
3019 PySSL_END_ALLOW_THREADS
3020 if (r != 1) {
3021 ok = 0;
3022 if (errno != 0) {
3023 ERR_clear_error();
3024 PyErr_SetFromErrno(PyExc_IOError);
3025 }
3026 else {
3027 _setSSLError(NULL, 0, __FILE__, __LINE__);
3028 }
3029 goto error;
3030 }
3031 }
3032 goto end;
3033
3034 error:
3035 ok = 0;
3036 end:
3037 Py_XDECREF(cafile_bytes);
3038 Py_XDECREF(capath_bytes);
3039 if (ok) {
3040 Py_RETURN_NONE;
3041 } else {
3042 return NULL;
3043 }
3044}
3045
3046static PyObject *
3047load_dh_params(PySSLContext *self, PyObject *filepath)
3048{
3049 BIO *bio;
3050 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003051 PyObject *filepath_bytes = NULL;
3052
3053 if (PyString_Check(filepath)) {
3054 Py_INCREF(filepath);
3055 filepath_bytes = filepath;
3056 } else {
3057 PyObject *u = PyUnicode_FromObject(filepath);
3058 if (!u)
3059 return NULL;
3060 filepath_bytes = PyUnicode_AsEncodedString(
3061 u, Py_FileSystemDefaultEncoding, NULL);
3062 Py_DECREF(u);
3063 if (!filepath_bytes)
3064 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003065 }
3066
Christian Heimes6e8f3952018-02-25 09:48:02 +01003067 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003068 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003069 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003070 ERR_clear_error();
3071 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3072 return NULL;
3073 }
3074 errno = 0;
3075 PySSL_BEGIN_ALLOW_THREADS
3076 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3077 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003078 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003079 PySSL_END_ALLOW_THREADS
3080 if (dh == NULL) {
3081 if (errno != 0) {
3082 ERR_clear_error();
3083 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3084 }
3085 else {
3086 _setSSLError(NULL, 0, __FILE__, __LINE__);
3087 }
3088 return NULL;
3089 }
3090 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3091 _setSSLError(NULL, 0, __FILE__, __LINE__);
3092 DH_free(dh);
3093 Py_RETURN_NONE;
3094}
3095
3096static PyObject *
3097context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3098{
3099 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3100 PySocketSockObject *sock;
3101 int server_side = 0;
3102 char *hostname = NULL;
3103 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3104
3105 /* server_hostname is either None (or absent), or to be encoded
3106 using the idna encoding. */
3107 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3108 PySocketModule.Sock_Type,
3109 &sock, &server_side,
3110 Py_TYPE(Py_None), &hostname_obj,
3111 &ssl_sock)) {
3112 PyErr_Clear();
3113 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3114 PySocketModule.Sock_Type,
3115 &sock, &server_side,
3116 "idna", &hostname, &ssl_sock))
3117 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003118 }
3119
3120 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3121 hostname, ssl_sock);
3122 if (hostname != NULL)
3123 PyMem_Free(hostname);
3124 return res;
3125}
3126
3127static PyObject *
3128session_stats(PySSLContext *self, PyObject *unused)
3129{
3130 int r;
3131 PyObject *value, *stats = PyDict_New();
3132 if (!stats)
3133 return NULL;
3134
3135#define ADD_STATS(SSL_NAME, KEY_NAME) \
3136 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3137 if (value == NULL) \
3138 goto error; \
3139 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3140 Py_DECREF(value); \
3141 if (r < 0) \
3142 goto error;
3143
3144 ADD_STATS(number, "number");
3145 ADD_STATS(connect, "connect");
3146 ADD_STATS(connect_good, "connect_good");
3147 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3148 ADD_STATS(accept, "accept");
3149 ADD_STATS(accept_good, "accept_good");
3150 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3151 ADD_STATS(accept, "accept");
3152 ADD_STATS(hits, "hits");
3153 ADD_STATS(misses, "misses");
3154 ADD_STATS(timeouts, "timeouts");
3155 ADD_STATS(cache_full, "cache_full");
3156
3157#undef ADD_STATS
3158
3159 return stats;
3160
3161error:
3162 Py_DECREF(stats);
3163 return NULL;
3164}
3165
3166static PyObject *
3167set_default_verify_paths(PySSLContext *self, PyObject *unused)
3168{
3169 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3170 _setSSLError(NULL, 0, __FILE__, __LINE__);
3171 return NULL;
3172 }
3173 Py_RETURN_NONE;
3174}
3175
3176#ifndef OPENSSL_NO_ECDH
3177static PyObject *
3178set_ecdh_curve(PySSLContext *self, PyObject *name)
3179{
3180 char *name_bytes;
3181 int nid;
3182 EC_KEY *key;
3183
3184 name_bytes = PyBytes_AsString(name);
3185 if (!name_bytes) {
3186 return NULL;
3187 }
3188 nid = OBJ_sn2nid(name_bytes);
3189 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003190 PyObject *r = PyObject_Repr(name);
3191 if (!r)
3192 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003193 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003194 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3195 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003196 return NULL;
3197 }
3198 key = EC_KEY_new_by_curve_name(nid);
3199 if (key == NULL) {
3200 _setSSLError(NULL, 0, __FILE__, __LINE__);
3201 return NULL;
3202 }
3203 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3204 EC_KEY_free(key);
3205 Py_RETURN_NONE;
3206}
3207#endif
3208
3209#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3210static int
3211_servername_callback(SSL *s, int *al, void *args)
3212{
3213 int ret;
3214 PySSLContext *ssl_ctx = (PySSLContext *) args;
3215 PySSLSocket *ssl;
3216 PyObject *servername_o;
3217 PyObject *servername_idna;
3218 PyObject *result;
3219 /* The high-level ssl.SSLSocket object */
3220 PyObject *ssl_socket;
3221 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3222#ifdef WITH_THREAD
3223 PyGILState_STATE gstate = PyGILState_Ensure();
3224#endif
3225
3226 if (ssl_ctx->set_hostname == NULL) {
3227 /* remove race condition in this the call back while if removing the
3228 * callback is in progress */
3229#ifdef WITH_THREAD
3230 PyGILState_Release(gstate);
3231#endif
3232 return SSL_TLSEXT_ERR_OK;
3233 }
3234
3235 ssl = SSL_get_app_data(s);
3236 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003237 if (ssl->ssl_sock == NULL) {
3238 ssl_socket = Py_None;
3239 } else {
3240 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3241 Py_INCREF(ssl_socket);
3242 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003243 if (ssl_socket == Py_None) {
3244 goto error;
3245 }
3246
3247 if (servername == NULL) {
3248 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3249 Py_None, ssl_ctx, NULL);
3250 }
3251 else {
3252 servername_o = PyBytes_FromString(servername);
3253 if (servername_o == NULL) {
3254 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3255 goto error;
3256 }
3257 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3258 if (servername_idna == NULL) {
3259 PyErr_WriteUnraisable(servername_o);
3260 Py_DECREF(servername_o);
3261 goto error;
3262 }
3263 Py_DECREF(servername_o);
3264 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3265 servername_idna, ssl_ctx, NULL);
3266 Py_DECREF(servername_idna);
3267 }
3268 Py_DECREF(ssl_socket);
3269
3270 if (result == NULL) {
3271 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3272 *al = SSL_AD_HANDSHAKE_FAILURE;
3273 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3274 }
3275 else {
3276 if (result != Py_None) {
3277 *al = (int) PyLong_AsLong(result);
3278 if (PyErr_Occurred()) {
3279 PyErr_WriteUnraisable(result);
3280 *al = SSL_AD_INTERNAL_ERROR;
3281 }
3282 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3283 }
3284 else {
3285 ret = SSL_TLSEXT_ERR_OK;
3286 }
3287 Py_DECREF(result);
3288 }
3289
3290#ifdef WITH_THREAD
3291 PyGILState_Release(gstate);
3292#endif
3293 return ret;
3294
3295error:
3296 Py_DECREF(ssl_socket);
3297 *al = SSL_AD_INTERNAL_ERROR;
3298 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3299#ifdef WITH_THREAD
3300 PyGILState_Release(gstate);
3301#endif
3302 return ret;
3303}
3304#endif
3305
3306PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3307"set_servername_callback(method)\n\
3308\n\
3309This sets a callback that will be called when a server name is provided by\n\
3310the SSL/TLS client in the SNI extension.\n\
3311\n\
3312If the argument is None then the callback is disabled. The method is called\n\
3313with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3314See RFC 6066 for details of the SNI extension.");
3315
3316static PyObject *
3317set_servername_callback(PySSLContext *self, PyObject *args)
3318{
3319#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3320 PyObject *cb;
3321
3322 if (!PyArg_ParseTuple(args, "O", &cb))
3323 return NULL;
3324
3325 Py_CLEAR(self->set_hostname);
3326 if (cb == Py_None) {
3327 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3328 }
3329 else {
3330 if (!PyCallable_Check(cb)) {
3331 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3332 PyErr_SetString(PyExc_TypeError,
3333 "not a callable object");
3334 return NULL;
3335 }
3336 Py_INCREF(cb);
3337 self->set_hostname = cb;
3338 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3339 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3340 }
3341 Py_RETURN_NONE;
3342#else
3343 PyErr_SetString(PyExc_NotImplementedError,
3344 "The TLS extension servername callback, "
3345 "SSL_CTX_set_tlsext_servername_callback, "
3346 "is not in the current OpenSSL library.");
3347 return NULL;
3348#endif
3349}
3350
3351PyDoc_STRVAR(PySSL_get_stats_doc,
3352"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3353\n\
3354Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3355CA extension and certificate revocation lists inside the context's cert\n\
3356store.\n\
3357NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3358been used at least once.");
3359
3360static PyObject *
3361cert_store_stats(PySSLContext *self)
3362{
3363 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003364 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003365 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003366 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003367
3368 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003369 objs = X509_STORE_get0_objects(store);
3370 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3371 obj = sk_X509_OBJECT_value(objs, i);
3372 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003373 case X509_LU_X509:
3374 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003375 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003376 ca++;
3377 }
3378 break;
3379 case X509_LU_CRL:
3380 crl++;
3381 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003382 default:
3383 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3384 * As far as I can tell they are internal states and never
3385 * stored in a cert store */
3386 break;
3387 }
3388 }
3389 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3390 "x509_ca", ca);
3391}
3392
3393PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3394"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3395\n\
3396Returns a list of dicts with information of loaded CA certs. If the\n\
3397optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3398NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3399been used at least once.");
3400
3401static PyObject *
3402get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3403{
3404 char *kwlist[] = {"binary_form", NULL};
3405 X509_STORE *store;
3406 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003407 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003408 int i;
3409 int binary_mode = 0;
3410
3411 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3412 kwlist, &py_binary_mode)) {
3413 return NULL;
3414 }
3415 binary_mode = PyObject_IsTrue(py_binary_mode);
3416 if (binary_mode < 0) {
3417 return NULL;
3418 }
3419
3420 if ((rlist = PyList_New(0)) == NULL) {
3421 return NULL;
3422 }
3423
3424 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003425 objs = X509_STORE_get0_objects(store);
3426 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003427 X509_OBJECT *obj;
3428 X509 *cert;
3429
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003430 obj = sk_X509_OBJECT_value(objs, i);
3431 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003432 /* not a x509 cert */
3433 continue;
3434 }
3435 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003436 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003437 if (!X509_check_ca(cert)) {
3438 continue;
3439 }
3440 if (binary_mode) {
3441 ci = _certificate_to_der(cert);
3442 } else {
3443 ci = _decode_certificate(cert);
3444 }
3445 if (ci == NULL) {
3446 goto error;
3447 }
3448 if (PyList_Append(rlist, ci) == -1) {
3449 goto error;
3450 }
3451 Py_CLEAR(ci);
3452 }
3453 return rlist;
3454
3455 error:
3456 Py_XDECREF(ci);
3457 Py_XDECREF(rlist);
3458 return NULL;
3459}
3460
3461
3462static PyGetSetDef context_getsetlist[] = {
3463 {"check_hostname", (getter) get_check_hostname,
3464 (setter) set_check_hostname, NULL},
3465 {"options", (getter) get_options,
3466 (setter) set_options, NULL},
3467#ifdef HAVE_OPENSSL_VERIFY_PARAM
3468 {"verify_flags", (getter) get_verify_flags,
3469 (setter) set_verify_flags, NULL},
3470#endif
3471 {"verify_mode", (getter) get_verify_mode,
3472 (setter) set_verify_mode, NULL},
3473 {NULL}, /* sentinel */
3474};
3475
3476static struct PyMethodDef context_methods[] = {
3477 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3478 METH_VARARGS | METH_KEYWORDS, NULL},
3479 {"set_ciphers", (PyCFunction) set_ciphers,
3480 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003481 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3482 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003483 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3484 METH_VARARGS, NULL},
3485 {"load_cert_chain", (PyCFunction) load_cert_chain,
3486 METH_VARARGS | METH_KEYWORDS, NULL},
3487 {"load_dh_params", (PyCFunction) load_dh_params,
3488 METH_O, NULL},
3489 {"load_verify_locations", (PyCFunction) load_verify_locations,
3490 METH_VARARGS | METH_KEYWORDS, NULL},
3491 {"session_stats", (PyCFunction) session_stats,
3492 METH_NOARGS, NULL},
3493 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3494 METH_NOARGS, NULL},
3495#ifndef OPENSSL_NO_ECDH
3496 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3497 METH_O, NULL},
3498#endif
3499 {"set_servername_callback", (PyCFunction) set_servername_callback,
3500 METH_VARARGS, PySSL_set_servername_callback_doc},
3501 {"cert_store_stats", (PyCFunction) cert_store_stats,
3502 METH_NOARGS, PySSL_get_stats_doc},
3503 {"get_ca_certs", (PyCFunction) get_ca_certs,
3504 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3505 {NULL, NULL} /* sentinel */
3506};
3507
3508static PyTypeObject PySSLContext_Type = {
3509 PyVarObject_HEAD_INIT(NULL, 0)
3510 "_ssl._SSLContext", /*tp_name*/
3511 sizeof(PySSLContext), /*tp_basicsize*/
3512 0, /*tp_itemsize*/
3513 (destructor)context_dealloc, /*tp_dealloc*/
3514 0, /*tp_print*/
3515 0, /*tp_getattr*/
3516 0, /*tp_setattr*/
3517 0, /*tp_reserved*/
3518 0, /*tp_repr*/
3519 0, /*tp_as_number*/
3520 0, /*tp_as_sequence*/
3521 0, /*tp_as_mapping*/
3522 0, /*tp_hash*/
3523 0, /*tp_call*/
3524 0, /*tp_str*/
3525 0, /*tp_getattro*/
3526 0, /*tp_setattro*/
3527 0, /*tp_as_buffer*/
3528 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3529 0, /*tp_doc*/
3530 (traverseproc) context_traverse, /*tp_traverse*/
3531 (inquiry) context_clear, /*tp_clear*/
3532 0, /*tp_richcompare*/
3533 0, /*tp_weaklistoffset*/
3534 0, /*tp_iter*/
3535 0, /*tp_iternext*/
3536 context_methods, /*tp_methods*/
3537 0, /*tp_members*/
3538 context_getsetlist, /*tp_getset*/
3539 0, /*tp_base*/
3540 0, /*tp_dict*/
3541 0, /*tp_descr_get*/
3542 0, /*tp_descr_set*/
3543 0, /*tp_dictoffset*/
3544 0, /*tp_init*/
3545 0, /*tp_alloc*/
3546 context_new, /*tp_new*/
3547};
3548
3549
3550
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003551#ifdef HAVE_OPENSSL_RAND
3552
3553/* helper routines for seeding the SSL PRNG */
3554static PyObject *
3555PySSL_RAND_add(PyObject *self, PyObject *args)
3556{
3557 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003558 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003559 double entropy;
3560
3561 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003562 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003563 do {
3564 if (len >= INT_MAX) {
3565 written = INT_MAX;
3566 } else {
3567 written = len;
3568 }
3569 RAND_add(buf, (int)written, entropy);
3570 buf += written;
3571 len -= written;
3572 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003573 Py_INCREF(Py_None);
3574 return Py_None;
3575}
3576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003577PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003578"RAND_add(string, entropy)\n\
3579\n\
3580Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003581bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003582
3583static PyObject *
3584PySSL_RAND_status(PyObject *self)
3585{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003586 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003587}
3588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003589PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003590"RAND_status() -> 0 or 1\n\
3591\n\
3592Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3593It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003594using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003595
Victor Stinner7c906672015-01-06 13:53:37 +01003596#endif /* HAVE_OPENSSL_RAND */
3597
3598
Benjamin Peterson42e10292016-07-07 00:02:31 -07003599#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003600
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003601static PyObject *
3602PySSL_RAND_egd(PyObject *self, PyObject *arg)
3603{
3604 int bytes;
3605
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003606 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003607 return PyErr_Format(PyExc_TypeError,
3608 "RAND_egd() expected string, found %s",
3609 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003610 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003611 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003612 PyErr_SetString(PySSLErrorObject,
3613 "EGD connection failed or EGD did not return "
3614 "enough data to seed the PRNG");
3615 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003616 }
3617 return PyInt_FromLong(bytes);
3618}
3619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003620PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003621"RAND_egd(path) -> bytes\n\
3622\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003623Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3624Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003625fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003626
Benjamin Peterson42e10292016-07-07 00:02:31 -07003627#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003628
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003629
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003630PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3631"get_default_verify_paths() -> tuple\n\
3632\n\
3633Return search paths and environment vars that are used by SSLContext's\n\
3634set_default_verify_paths() to load default CAs. The values are\n\
3635'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3636
3637static PyObject *
3638PySSL_get_default_verify_paths(PyObject *self)
3639{
3640 PyObject *ofile_env = NULL;
3641 PyObject *ofile = NULL;
3642 PyObject *odir_env = NULL;
3643 PyObject *odir = NULL;
3644
Benjamin Peterson65192c12015-07-18 10:59:13 -07003645#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003646 const char *tmp = (info); \
3647 target = NULL; \
3648 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3649 else { target = PyBytes_FromString(tmp); } \
3650 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003651 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003652
Benjamin Peterson65192c12015-07-18 10:59:13 -07003653 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3654 CONVERT(X509_get_default_cert_file(), ofile);
3655 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3656 CONVERT(X509_get_default_cert_dir(), odir);
3657#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003658
3659 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3660
3661 error:
3662 Py_XDECREF(ofile_env);
3663 Py_XDECREF(ofile);
3664 Py_XDECREF(odir_env);
3665 Py_XDECREF(odir);
3666 return NULL;
3667}
3668
3669static PyObject*
3670asn1obj2py(ASN1_OBJECT *obj)
3671{
3672 int nid;
3673 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003674
3675 nid = OBJ_obj2nid(obj);
3676 if (nid == NID_undef) {
3677 PyErr_Format(PyExc_ValueError, "Unknown object");
3678 return NULL;
3679 }
3680 sn = OBJ_nid2sn(nid);
3681 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003682 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003683}
3684
3685PyDoc_STRVAR(PySSL_txt2obj_doc,
3686"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3687\n\
3688Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3689objects are looked up by OID. With name=True short and long name are also\n\
3690matched.");
3691
3692static PyObject*
3693PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3694{
3695 char *kwlist[] = {"txt", "name", NULL};
3696 PyObject *result = NULL;
3697 char *txt;
3698 PyObject *pyname = Py_None;
3699 int name = 0;
3700 ASN1_OBJECT *obj;
3701
3702 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3703 kwlist, &txt, &pyname)) {
3704 return NULL;
3705 }
3706 name = PyObject_IsTrue(pyname);
3707 if (name < 0)
3708 return NULL;
3709 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3710 if (obj == NULL) {
3711 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3712 return NULL;
3713 }
3714 result = asn1obj2py(obj);
3715 ASN1_OBJECT_free(obj);
3716 return result;
3717}
3718
3719PyDoc_STRVAR(PySSL_nid2obj_doc,
3720"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3721\n\
3722Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3723
3724static PyObject*
3725PySSL_nid2obj(PyObject *self, PyObject *args)
3726{
3727 PyObject *result = NULL;
3728 int nid;
3729 ASN1_OBJECT *obj;
3730
3731 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3732 return NULL;
3733 }
3734 if (nid < NID_undef) {
3735 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3736 return NULL;
3737 }
3738 obj = OBJ_nid2obj(nid);
3739 if (obj == NULL) {
3740 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3741 return NULL;
3742 }
3743 result = asn1obj2py(obj);
3744 ASN1_OBJECT_free(obj);
3745 return result;
3746}
3747
3748#ifdef _MSC_VER
3749
3750static PyObject*
3751certEncodingType(DWORD encodingType)
3752{
3753 static PyObject *x509_asn = NULL;
3754 static PyObject *pkcs_7_asn = NULL;
3755
3756 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003757 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003758 if (x509_asn == NULL)
3759 return NULL;
3760 }
3761 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003762 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003763 if (pkcs_7_asn == NULL)
3764 return NULL;
3765 }
3766 switch(encodingType) {
3767 case X509_ASN_ENCODING:
3768 Py_INCREF(x509_asn);
3769 return x509_asn;
3770 case PKCS_7_ASN_ENCODING:
3771 Py_INCREF(pkcs_7_asn);
3772 return pkcs_7_asn;
3773 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003774 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003775 }
3776}
3777
3778static PyObject*
3779parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3780{
3781 CERT_ENHKEY_USAGE *usage;
3782 DWORD size, error, i;
3783 PyObject *retval;
3784
3785 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3786 error = GetLastError();
3787 if (error == CRYPT_E_NOT_FOUND) {
3788 Py_RETURN_TRUE;
3789 }
3790 return PyErr_SetFromWindowsErr(error);
3791 }
3792
3793 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3794 if (usage == NULL) {
3795 return PyErr_NoMemory();
3796 }
3797
3798 /* Now get the actual enhanced usage property */
3799 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3800 PyMem_Free(usage);
3801 error = GetLastError();
3802 if (error == CRYPT_E_NOT_FOUND) {
3803 Py_RETURN_TRUE;
3804 }
3805 return PyErr_SetFromWindowsErr(error);
3806 }
3807 retval = PySet_New(NULL);
3808 if (retval == NULL) {
3809 goto error;
3810 }
3811 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3812 if (usage->rgpszUsageIdentifier[i]) {
3813 PyObject *oid;
3814 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003815 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003816 if (oid == NULL) {
3817 Py_CLEAR(retval);
3818 goto error;
3819 }
3820 err = PySet_Add(retval, oid);
3821 Py_DECREF(oid);
3822 if (err == -1) {
3823 Py_CLEAR(retval);
3824 goto error;
3825 }
3826 }
3827 }
3828 error:
3829 PyMem_Free(usage);
3830 return retval;
3831}
3832
3833PyDoc_STRVAR(PySSL_enum_certificates_doc,
3834"enum_certificates(store_name) -> []\n\
3835\n\
3836Retrieve certificates from Windows' cert store. store_name may be one of\n\
3837'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3838The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3839encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3840PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3841boolean True.");
3842
3843static PyObject *
3844PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3845{
3846 char *kwlist[] = {"store_name", NULL};
3847 char *store_name;
3848 HCERTSTORE hStore = NULL;
3849 PCCERT_CONTEXT pCertCtx = NULL;
3850 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3851 PyObject *result = NULL;
3852
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003853 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003854 kwlist, &store_name)) {
3855 return NULL;
3856 }
3857 result = PyList_New(0);
3858 if (result == NULL) {
3859 return NULL;
3860 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003861 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3862 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3863 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003864 if (hStore == NULL) {
3865 Py_DECREF(result);
3866 return PyErr_SetFromWindowsErr(GetLastError());
3867 }
3868
3869 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3870 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3871 pCertCtx->cbCertEncoded);
3872 if (!cert) {
3873 Py_CLEAR(result);
3874 break;
3875 }
3876 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3877 Py_CLEAR(result);
3878 break;
3879 }
3880 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3881 if (keyusage == Py_True) {
3882 Py_DECREF(keyusage);
3883 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3884 }
3885 if (keyusage == NULL) {
3886 Py_CLEAR(result);
3887 break;
3888 }
3889 if ((tup = PyTuple_New(3)) == NULL) {
3890 Py_CLEAR(result);
3891 break;
3892 }
3893 PyTuple_SET_ITEM(tup, 0, cert);
3894 cert = NULL;
3895 PyTuple_SET_ITEM(tup, 1, enc);
3896 enc = NULL;
3897 PyTuple_SET_ITEM(tup, 2, keyusage);
3898 keyusage = NULL;
3899 if (PyList_Append(result, tup) < 0) {
3900 Py_CLEAR(result);
3901 break;
3902 }
3903 Py_CLEAR(tup);
3904 }
3905 if (pCertCtx) {
3906 /* loop ended with an error, need to clean up context manually */
3907 CertFreeCertificateContext(pCertCtx);
3908 }
3909
3910 /* In error cases cert, enc and tup may not be NULL */
3911 Py_XDECREF(cert);
3912 Py_XDECREF(enc);
3913 Py_XDECREF(keyusage);
3914 Py_XDECREF(tup);
3915
3916 if (!CertCloseStore(hStore, 0)) {
3917 /* This error case might shadow another exception.*/
3918 Py_XDECREF(result);
3919 return PyErr_SetFromWindowsErr(GetLastError());
3920 }
3921 return result;
3922}
3923
3924PyDoc_STRVAR(PySSL_enum_crls_doc,
3925"enum_crls(store_name) -> []\n\
3926\n\
3927Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3928'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3929The function returns a list of (bytes, encoding_type) tuples. The\n\
3930encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3931PKCS_7_ASN_ENCODING.");
3932
3933static PyObject *
3934PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3935{
3936 char *kwlist[] = {"store_name", NULL};
3937 char *store_name;
3938 HCERTSTORE hStore = NULL;
3939 PCCRL_CONTEXT pCrlCtx = NULL;
3940 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3941 PyObject *result = NULL;
3942
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003943 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003944 kwlist, &store_name)) {
3945 return NULL;
3946 }
3947 result = PyList_New(0);
3948 if (result == NULL) {
3949 return NULL;
3950 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003951 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3952 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3953 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003954 if (hStore == NULL) {
3955 Py_DECREF(result);
3956 return PyErr_SetFromWindowsErr(GetLastError());
3957 }
3958
3959 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3960 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3961 pCrlCtx->cbCrlEncoded);
3962 if (!crl) {
3963 Py_CLEAR(result);
3964 break;
3965 }
3966 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3967 Py_CLEAR(result);
3968 break;
3969 }
3970 if ((tup = PyTuple_New(2)) == NULL) {
3971 Py_CLEAR(result);
3972 break;
3973 }
3974 PyTuple_SET_ITEM(tup, 0, crl);
3975 crl = NULL;
3976 PyTuple_SET_ITEM(tup, 1, enc);
3977 enc = NULL;
3978
3979 if (PyList_Append(result, tup) < 0) {
3980 Py_CLEAR(result);
3981 break;
3982 }
3983 Py_CLEAR(tup);
3984 }
3985 if (pCrlCtx) {
3986 /* loop ended with an error, need to clean up context manually */
3987 CertFreeCRLContext(pCrlCtx);
3988 }
3989
3990 /* In error cases cert, enc and tup may not be NULL */
3991 Py_XDECREF(crl);
3992 Py_XDECREF(enc);
3993 Py_XDECREF(tup);
3994
3995 if (!CertCloseStore(hStore, 0)) {
3996 /* This error case might shadow another exception.*/
3997 Py_XDECREF(result);
3998 return PyErr_SetFromWindowsErr(GetLastError());
3999 }
4000 return result;
4001}
4002
4003#endif /* _MSC_VER */
4004
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004005/* List of functions exported by this module. */
4006
4007static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004008 {"_test_decode_cert", PySSL_test_decode_certificate,
4009 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004010#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004011 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4012 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004013 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4014 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004015#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07004016#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01004017 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
4018 PySSL_RAND_egd_doc},
4019#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004020 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
4021 METH_NOARGS, PySSL_get_default_verify_paths_doc},
4022#ifdef _MSC_VER
4023 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4024 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4025 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4026 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4027#endif
4028 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4029 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4030 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4031 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004032 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004033};
4034
4035
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004036#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004037
4038/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004039 * of the Python C thread library
4040 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4041 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004042
4043static PyThread_type_lock *_ssl_locks = NULL;
4044
Christian Heimes10107812013-08-19 17:36:29 +02004045#if OPENSSL_VERSION_NUMBER >= 0x10000000
4046/* use new CRYPTO_THREADID API. */
4047static void
4048_ssl_threadid_callback(CRYPTO_THREADID *id)
4049{
4050 CRYPTO_THREADID_set_numeric(id,
4051 (unsigned long)PyThread_get_thread_ident());
4052}
4053#else
4054/* deprecated CRYPTO_set_id_callback() API. */
4055static unsigned long
4056_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004057 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004058}
Christian Heimes10107812013-08-19 17:36:29 +02004059#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004060
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004061static void _ssl_thread_locking_function
4062 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004063 /* this function is needed to perform locking on shared data
4064 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004065 structures that will be implicitly shared whenever multiple
4066 threads use OpenSSL.) Multi-threaded applications will
4067 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004068
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004069 locking_function() must be able to handle up to
4070 CRYPTO_num_locks() different mutex locks. It sets the n-th
4071 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004072
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004073 file and line are the file number of the function setting the
4074 lock. They can be useful for debugging.
4075 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004076
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004077 if ((_ssl_locks == NULL) ||
4078 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4079 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004080
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004081 if (mode & CRYPTO_LOCK) {
4082 PyThread_acquire_lock(_ssl_locks[n], 1);
4083 } else {
4084 PyThread_release_lock(_ssl_locks[n]);
4085 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004086}
4087
4088static int _setup_ssl_threads(void) {
4089
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004090 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004091
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004092 if (_ssl_locks == NULL) {
4093 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004094 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4095 if (_ssl_locks == NULL) {
4096 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004097 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004098 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004099 memset(_ssl_locks, 0,
4100 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004101 for (i = 0; i < _ssl_locks_count; i++) {
4102 _ssl_locks[i] = PyThread_allocate_lock();
4103 if (_ssl_locks[i] == NULL) {
4104 unsigned int j;
4105 for (j = 0; j < i; j++) {
4106 PyThread_free_lock(_ssl_locks[j]);
4107 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004108 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004109 return 0;
4110 }
4111 }
4112 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004113#if OPENSSL_VERSION_NUMBER >= 0x10000000
4114 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4115#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004116 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004117#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004118 }
4119 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004120}
4121
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004122#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004124PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004125"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004126for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004127
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004128
4129
4130
4131static void
4132parse_openssl_version(unsigned long libver,
4133 unsigned int *major, unsigned int *minor,
4134 unsigned int *fix, unsigned int *patch,
4135 unsigned int *status)
4136{
4137 *status = libver & 0xF;
4138 libver >>= 4;
4139 *patch = libver & 0xFF;
4140 libver >>= 8;
4141 *fix = libver & 0xFF;
4142 libver >>= 8;
4143 *minor = libver & 0xFF;
4144 libver >>= 8;
4145 *major = libver & 0xFF;
4146}
4147
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004148PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004149init_ssl(void)
4150{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004151 PyObject *m, *d, *r;
4152 unsigned long libver;
4153 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004154 struct py_ssl_error_code *errcode;
4155 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004156
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004157 if (PyType_Ready(&PySSLContext_Type) < 0)
4158 return;
4159 if (PyType_Ready(&PySSLSocket_Type) < 0)
4160 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004161
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004162 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4163 if (m == NULL)
4164 return;
4165 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004166
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004167 /* Load _socket module and its C API */
4168 if (PySocketModule_ImportModuleAndAPI())
4169 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004170
Christian Heimes7daa45d2017-09-05 17:12:12 +02004171#ifndef OPENSSL_VERSION_1_1
4172 /* Load all algorithms and initialize cpuid */
4173 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004174 /* Init OpenSSL */
4175 SSL_load_error_strings();
4176 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004177#endif
4178
Bill Janssen98d19da2007-09-10 21:51:02 +00004179#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004180#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004181 /* note that this will start threading if not already started */
4182 if (!_setup_ssl_threads()) {
4183 return;
4184 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004185#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4186 /* OpenSSL 1.1.0 builtin thread support is enabled */
4187 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004188#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004189#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004190
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004191 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004192 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4193 "ssl.SSLError", SSLError_doc,
4194 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004195 if (PySSLErrorObject == NULL)
4196 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004197 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4198
4199 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4200 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4201 PySSLErrorObject, NULL);
4202 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4203 "ssl.SSLWantReadError", SSLWantReadError_doc,
4204 PySSLErrorObject, NULL);
4205 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4206 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4207 PySSLErrorObject, NULL);
4208 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4209 "ssl.SSLSyscallError", SSLSyscallError_doc,
4210 PySSLErrorObject, NULL);
4211 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4212 "ssl.SSLEOFError", SSLEOFError_doc,
4213 PySSLErrorObject, NULL);
4214 if (PySSLZeroReturnErrorObject == NULL
4215 || PySSLWantReadErrorObject == NULL
4216 || PySSLWantWriteErrorObject == NULL
4217 || PySSLSyscallErrorObject == NULL
4218 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004219 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004220
4221 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4222 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4223 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4224 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4225 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4226
4227 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4228 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4229 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4230 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4231 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4232 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4233 return;
4234 if (PyDict_SetItemString(d, "_SSLContext",
4235 (PyObject *)&PySSLContext_Type) != 0)
4236 return;
4237 if (PyDict_SetItemString(d, "_SSLSocket",
4238 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004239 return;
4240 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4241 PY_SSL_ERROR_ZERO_RETURN);
4242 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4243 PY_SSL_ERROR_WANT_READ);
4244 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4245 PY_SSL_ERROR_WANT_WRITE);
4246 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4247 PY_SSL_ERROR_WANT_X509_LOOKUP);
4248 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4249 PY_SSL_ERROR_SYSCALL);
4250 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4251 PY_SSL_ERROR_SSL);
4252 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4253 PY_SSL_ERROR_WANT_CONNECT);
4254 /* non ssl.h errorcodes */
4255 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4256 PY_SSL_ERROR_EOF);
4257 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4258 PY_SSL_ERROR_INVALID_ERROR_CODE);
4259 /* cert requirements */
4260 PyModule_AddIntConstant(m, "CERT_NONE",
4261 PY_SSL_CERT_NONE);
4262 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4263 PY_SSL_CERT_OPTIONAL);
4264 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4265 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004266 /* CRL verification for verification_flags */
4267 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4268 0);
4269 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4270 X509_V_FLAG_CRL_CHECK);
4271 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4272 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4273 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4274 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004275#ifdef X509_V_FLAG_TRUSTED_FIRST
4276 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4277 X509_V_FLAG_TRUSTED_FIRST);
4278#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004279
4280 /* Alert Descriptions from ssl.h */
4281 /* note RESERVED constants no longer intended for use have been removed */
4282 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4283
4284#define ADD_AD_CONSTANT(s) \
4285 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4286 SSL_AD_##s)
4287
4288 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4289 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4290 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4291 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4292 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4293 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4294 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4295 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4296 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4297 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4298 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4299 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4300 ADD_AD_CONSTANT(UNKNOWN_CA);
4301 ADD_AD_CONSTANT(ACCESS_DENIED);
4302 ADD_AD_CONSTANT(DECODE_ERROR);
4303 ADD_AD_CONSTANT(DECRYPT_ERROR);
4304 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4305 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4306 ADD_AD_CONSTANT(INTERNAL_ERROR);
4307 ADD_AD_CONSTANT(USER_CANCELLED);
4308 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4309 /* Not all constants are in old OpenSSL versions */
4310#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4311 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4312#endif
4313#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4314 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4315#endif
4316#ifdef SSL_AD_UNRECOGNIZED_NAME
4317 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4318#endif
4319#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4320 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4321#endif
4322#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4323 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4324#endif
4325#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4326 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4327#endif
4328
4329#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004330
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004331 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004332#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004333 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4334 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004335#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004336#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004337 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4338 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004339#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004340 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004341 PY_SSL_VERSION_TLS);
4342 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4343 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004344 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4345 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004346#if HAVE_TLSv1_2
4347 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4348 PY_SSL_VERSION_TLS1_1);
4349 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4350 PY_SSL_VERSION_TLS1_2);
4351#endif
4352
4353 /* protocol options */
4354 PyModule_AddIntConstant(m, "OP_ALL",
4355 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4356 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4357 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4358 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4359#if HAVE_TLSv1_2
4360 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4361 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4362#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004363#ifdef SSL_OP_NO_TLSv1_3
4364 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4365#else
4366 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4367#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004368 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4369 SSL_OP_CIPHER_SERVER_PREFERENCE);
4370 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4371#ifdef SSL_OP_SINGLE_ECDH_USE
4372 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4373#endif
4374#ifdef SSL_OP_NO_COMPRESSION
4375 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4376 SSL_OP_NO_COMPRESSION);
4377#endif
4378
4379#if HAVE_SNI
4380 r = Py_True;
4381#else
4382 r = Py_False;
4383#endif
4384 Py_INCREF(r);
4385 PyModule_AddObject(m, "HAS_SNI", r);
4386
4387#if HAVE_OPENSSL_FINISHED
4388 r = Py_True;
4389#else
4390 r = Py_False;
4391#endif
4392 Py_INCREF(r);
4393 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4394
4395#ifdef OPENSSL_NO_ECDH
4396 r = Py_False;
4397#else
4398 r = Py_True;
4399#endif
4400 Py_INCREF(r);
4401 PyModule_AddObject(m, "HAS_ECDH", r);
4402
Christian Heimesdf1732a2018-02-25 14:28:55 +01004403#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004404 r = Py_True;
4405#else
4406 r = Py_False;
4407#endif
4408 Py_INCREF(r);
4409 PyModule_AddObject(m, "HAS_NPN", r);
4410
Christian Heimesdf1732a2018-02-25 14:28:55 +01004411#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004412 r = Py_True;
4413#else
4414 r = Py_False;
4415#endif
4416 Py_INCREF(r);
4417 PyModule_AddObject(m, "HAS_ALPN", r);
4418
Christian Heimesb9a860f2017-09-07 22:31:17 -07004419#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4420 r = Py_True;
4421#else
4422 r = Py_False;
4423#endif
4424 Py_INCREF(r);
4425 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4426
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004427 /* Mappings for error codes */
4428 err_codes_to_names = PyDict_New();
4429 err_names_to_codes = PyDict_New();
4430 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4431 return;
4432 errcode = error_codes;
4433 while (errcode->mnemonic != NULL) {
4434 PyObject *mnemo, *key;
4435 mnemo = PyUnicode_FromString(errcode->mnemonic);
4436 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4437 if (mnemo == NULL || key == NULL)
4438 return;
4439 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4440 return;
4441 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4442 return;
4443 Py_DECREF(key);
4444 Py_DECREF(mnemo);
4445 errcode++;
4446 }
4447 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4448 return;
4449 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4450 return;
4451
4452 lib_codes_to_names = PyDict_New();
4453 if (lib_codes_to_names == NULL)
4454 return;
4455 libcode = library_codes;
4456 while (libcode->library != NULL) {
4457 PyObject *mnemo, *key;
4458 key = PyLong_FromLong(libcode->code);
4459 mnemo = PyUnicode_FromString(libcode->library);
4460 if (key == NULL || mnemo == NULL)
4461 return;
4462 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4463 return;
4464 Py_DECREF(key);
4465 Py_DECREF(mnemo);
4466 libcode++;
4467 }
4468 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4469 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004470
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004471 /* OpenSSL version */
4472 /* SSLeay() gives us the version of the library linked against,
4473 which could be different from the headers version.
4474 */
4475 libver = SSLeay();
4476 r = PyLong_FromUnsignedLong(libver);
4477 if (r == NULL)
4478 return;
4479 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4480 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004481 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004482 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4483 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4484 return;
4485 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4486 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4487 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004488
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004489 libver = OPENSSL_VERSION_NUMBER;
4490 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4491 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4492 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4493 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004494}