blob: 0e0dacd9d223b097f8e9f88cbb09d8ef5555c1c0 [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 */
Dan Willemsendbcebe02019-01-07 18:07:24 -0800594#ifndef OPENSSL_IS_BORINGSSL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000595 (void) ERR_get_state();
Dan Willemsendbcebe02019-01-07 18:07:24 -0800596#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000597 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500600 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000601 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500602 SSL_set_app_data(self->ssl,self);
603 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
604 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000605#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500606 mode |= SSL_MODE_AUTO_RETRY;
607#endif
608 SSL_set_mode(self->ssl, mode);
609
610#if HAVE_SNI
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800611 if (server_hostname != NULL) {
612/* Don't send SNI for IP addresses. We cannot simply use inet_aton() and
613 * inet_pton() here. inet_aton() may be linked weakly and inet_pton() isn't
614 * available on all platforms. Use OpenSSL's IP address parser. It's
615 * available since 1.0.2 and LibreSSL since at least 2.3.0. */
616 int send_sni = 1;
617#if OPENSSL_VERSION_NUMBER >= 0x10200000L
618 ASN1_OCTET_STRING *ip = a2i_IPADDRESS(server_hostname);
619 if (ip == NULL) {
620 send_sni = 1;
621 ERR_clear_error();
622 } else {
623 send_sni = 0;
624 ASN1_OCTET_STRING_free(ip);
625 }
626#elif defined(HAVE_INET_PTON)
627#ifdef ENABLE_IPV6
Christian Heimes439956a2018-02-25 13:08:05 +0100628 #define PySSL_MAX(x, y) (((x) > (y)) ? (x) : (y))
629 char packed[PySSL_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
Miss Islington (bot)a5c91122018-02-25 01:16:37 -0800630#else
631 char packed[sizeof(struct in_addr)];
632#endif /* ENABLE_IPV6 */
633 if (inet_pton(AF_INET, server_hostname, packed)) {
634 send_sni = 0;
635#ifdef ENABLE_IPV6
636 } else if(inet_pton(AF_INET6, server_hostname, packed)) {
637 send_sni = 0;
638#endif /* ENABLE_IPV6 */
639 } else {
640 send_sni = 1;
641 }
642#endif /* HAVE_INET_PTON */
643 if (send_sni) {
644 SSL_set_tlsext_host_name(self->ssl, server_hostname);
645 }
646 }
Antoine Pitrou92719c52010-04-09 20:38:39 +0000647#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000648
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000649 /* If the socket is in non-blocking mode or timeout mode, set the BIO
650 * to non-blocking mode (blocking is the default)
651 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500652 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000653 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
654 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
655 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000656
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000657 PySSL_BEGIN_ALLOW_THREADS
658 if (socket_type == PY_SSL_CLIENT)
659 SSL_set_connect_state(self->ssl);
660 else
661 SSL_set_accept_state(self->ssl);
662 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000663
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500664 self->socket_type = socket_type;
665 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000666 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400667 if (ssl_sock != Py_None) {
668 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
669 if (self->ssl_sock == NULL) {
670 Py_DECREF(self);
671 return NULL;
672 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500673 }
674 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000675}
676
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000677
678/* SSL object methods */
679
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500680static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000681{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000682 int ret;
683 int err;
684 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500685 PySocketSockObject *sock = self->Socket;
686
687 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000688
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000689 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500690 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000691 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
692 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000693
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000694 /* Actually negotiate SSL connection */
695 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
696 do {
697 PySSL_BEGIN_ALLOW_THREADS
698 ret = SSL_do_handshake(self->ssl);
699 err = SSL_get_error(self->ssl, ret);
700 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500701 if (PyErr_CheckSignals())
702 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000703 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500704 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500706 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000707 } else {
708 sockstate = SOCKET_OPERATION_OK;
709 }
710 if (sockstate == SOCKET_HAS_TIMED_OUT) {
711 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000712 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500713 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000714 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
715 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000716 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500717 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000718 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
719 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000720 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500721 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000722 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
723 break;
724 }
725 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500726 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000727 if (ret < 1)
728 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000729
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000730 if (self->peer_cert)
731 X509_free (self->peer_cert);
732 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500733 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000734 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500735 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000736
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000737 Py_INCREF(Py_None);
738 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000739
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500740error:
741 Py_DECREF(sock);
742 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000743}
744
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000745static PyObject *
Christian Heimesc9d668c2017-09-05 19:13:07 +0200746_asn1obj2py(const ASN1_OBJECT *name, int no_name)
747{
748 char buf[X509_NAME_MAXLEN];
749 char *namebuf = buf;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000750 int buflen;
Christian Heimesc9d668c2017-09-05 19:13:07 +0200751 PyObject *name_obj = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000752
Christian Heimesc9d668c2017-09-05 19:13:07 +0200753 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000754 if (buflen < 0) {
755 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200756 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000757 }
Christian Heimesc9d668c2017-09-05 19:13:07 +0200758 /* initial buffer is too small for oid + terminating null byte */
759 if (buflen > X509_NAME_MAXLEN - 1) {
760 /* make OBJ_obj2txt() calculate the required buflen */
761 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
762 /* allocate len + 1 for terminating NULL byte */
763 namebuf = PyMem_Malloc(buflen + 1);
764 if (namebuf == NULL) {
765 PyErr_NoMemory();
766 return NULL;
767 }
768 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
769 if (buflen < 0) {
770 _setSSLError(NULL, 0, __FILE__, __LINE__);
771 goto done;
772 }
773 }
774 if (!buflen && no_name) {
775 Py_INCREF(Py_None);
776 name_obj = Py_None;
777 }
778 else {
779 name_obj = PyString_FromStringAndSize(namebuf, buflen);
780 }
781
782 done:
783 if (buf != namebuf) {
784 PyMem_Free(namebuf);
785 }
786 return name_obj;
787}
788
789static PyObject *
790_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
791{
792 Py_ssize_t buflen;
793 unsigned char *valuebuf = NULL;
794 PyObject *attr, *value_obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000795
796 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
797 if (buflen < 0) {
798 _setSSLError(NULL, 0, __FILE__, __LINE__);
Christian Heimesc9d668c2017-09-05 19:13:07 +0200799 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000800 }
801 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000802 buflen, "strict");
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000803
Christian Heimesc9d668c2017-09-05 19:13:07 +0200804 attr = Py_BuildValue("NN", _asn1obj2py(name, 0), value_obj);
805 OPENSSL_free(valuebuf);
806 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000807}
808
809static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000810_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000811{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000812 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
813 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
814 PyObject *rdnt;
815 PyObject *attr = NULL; /* tuple to hold an attribute */
816 int entry_count = X509_NAME_entry_count(xname);
817 X509_NAME_ENTRY *entry;
818 ASN1_OBJECT *name;
819 ASN1_STRING *value;
820 int index_counter;
821 int rdn_level = -1;
822 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000823
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000824 dn = PyList_New(0);
825 if (dn == NULL)
826 return NULL;
827 /* now create another tuple to hold the top-level RDN */
828 rdn = PyList_New(0);
829 if (rdn == NULL)
830 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000831
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000832 for (index_counter = 0;
833 index_counter < entry_count;
834 index_counter++)
835 {
836 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000837
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000838 /* check to see if we've gotten to a new RDN */
839 if (rdn_level >= 0) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200840 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000841 /* yes, new RDN */
842 /* add old RDN to DN */
843 rdnt = PyList_AsTuple(rdn);
844 Py_DECREF(rdn);
845 if (rdnt == NULL)
846 goto fail0;
847 retcode = PyList_Append(dn, rdnt);
848 Py_DECREF(rdnt);
849 if (retcode < 0)
850 goto fail0;
851 /* create new RDN */
852 rdn = PyList_New(0);
853 if (rdn == NULL)
854 goto fail0;
855 }
856 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200857 rdn_level = X509_NAME_ENTRY_set(entry);
Bill Janssen98d19da2007-09-10 21:51:02 +0000858
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000859 /* now add this attribute to the current RDN */
860 name = X509_NAME_ENTRY_get_object(entry);
861 value = X509_NAME_ENTRY_get_data(entry);
862 attr = _create_tuple_for_attribute(name, value);
863 /*
864 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
865 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500866 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
867 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000868 */
869 if (attr == NULL)
870 goto fail1;
871 retcode = PyList_Append(rdn, attr);
872 Py_DECREF(attr);
873 if (retcode < 0)
874 goto fail1;
875 }
876 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100877 if (rdn != NULL) {
878 if (PyList_GET_SIZE(rdn) > 0) {
879 rdnt = PyList_AsTuple(rdn);
880 Py_DECREF(rdn);
881 if (rdnt == NULL)
882 goto fail0;
883 retcode = PyList_Append(dn, rdnt);
884 Py_DECREF(rdnt);
885 if (retcode < 0)
886 goto fail0;
887 }
888 else {
889 Py_DECREF(rdn);
890 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000891 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000892
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000893 /* convert list to tuple */
894 rdnt = PyList_AsTuple(dn);
895 Py_DECREF(dn);
896 if (rdnt == NULL)
897 return NULL;
898 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000899
900 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000901 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000902
903 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000904 Py_XDECREF(dn);
905 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000906}
907
908static PyObject *
909_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000910
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000911 /* this code follows the procedure outlined in
912 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
913 function to extract the STACK_OF(GENERAL_NAME),
914 then iterates through the stack to add the
915 names. */
916
917 int i, j;
918 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200919 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000920 X509_EXTENSION *ext = NULL;
921 GENERAL_NAMES *names = NULL;
922 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000923 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000924 BIO *biobuf = NULL;
925 char buf[2048];
926 char *vptr;
927 int len;
928 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000929#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000930 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000931#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000932 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000933#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000934
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000935 if (certificate == NULL)
936 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000937
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000938 /* get a memory buffer */
939 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000940
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200941 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000942 while ((i = X509_get_ext_by_NID(
943 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000944
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000945 if (peer_alt_names == Py_None) {
946 peer_alt_names = PyList_New(0);
947 if (peer_alt_names == NULL)
948 goto fail;
949 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000950
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000951 /* now decode the altName */
952 ext = X509_get_ext(certificate, i);
953 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500954 PyErr_SetString
955 (PySSLErrorObject,
956 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000957 goto fail;
958 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000959
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200960 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000961 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500962 names = (GENERAL_NAMES*)
963 (ASN1_item_d2i(NULL,
964 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200965 X509_EXTENSION_get_data(ext)->length,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500966 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000967 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500968 names = (GENERAL_NAMES*)
969 (method->d2i(NULL,
970 &p,
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200971 X509_EXTENSION_get_data(ext)->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000972
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000973 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000974 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200975 int gntype;
976 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000977
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000978 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200979 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200980 switch (gntype) {
981 case GEN_DIRNAME:
982 /* we special-case DirName as a tuple of
983 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000984
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000985 t = PyTuple_New(2);
986 if (t == NULL) {
987 goto fail;
988 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000989
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000990 v = PyString_FromString("DirName");
991 if (v == NULL) {
992 Py_DECREF(t);
993 goto fail;
994 }
995 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000996
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000997 v = _create_tuple_for_X509_NAME (name->d.dirn);
998 if (v == NULL) {
999 Py_DECREF(t);
1000 goto fail;
1001 }
1002 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001003 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001004
Christian Heimes88b174c2013-08-17 00:54:47 +02001005 case GEN_EMAIL:
1006 case GEN_DNS:
1007 case GEN_URI:
1008 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1009 correctly, CVE-2013-4238 */
1010 t = PyTuple_New(2);
1011 if (t == NULL)
1012 goto fail;
1013 switch (gntype) {
1014 case GEN_EMAIL:
1015 v = PyString_FromString("email");
1016 as = name->d.rfc822Name;
1017 break;
1018 case GEN_DNS:
1019 v = PyString_FromString("DNS");
1020 as = name->d.dNSName;
1021 break;
1022 case GEN_URI:
1023 v = PyString_FromString("URI");
1024 as = name->d.uniformResourceIdentifier;
1025 break;
1026 }
1027 if (v == NULL) {
1028 Py_DECREF(t);
1029 goto fail;
1030 }
1031 PyTuple_SET_ITEM(t, 0, v);
1032 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
1033 ASN1_STRING_length(as));
1034 if (v == NULL) {
1035 Py_DECREF(t);
1036 goto fail;
1037 }
1038 PyTuple_SET_ITEM(t, 1, v);
1039 break;
Bill Janssen98d19da2007-09-10 21:51:02 +00001040
Christian Heimes6663eb62016-09-06 23:25:35 +02001041 case GEN_RID:
1042 t = PyTuple_New(2);
1043 if (t == NULL)
1044 goto fail;
1045
1046 v = PyUnicode_FromString("Registered ID");
1047 if (v == NULL) {
1048 Py_DECREF(t);
1049 goto fail;
1050 }
1051 PyTuple_SET_ITEM(t, 0, v);
1052
1053 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1054 if (len < 0) {
1055 Py_DECREF(t);
1056 _setSSLError(NULL, 0, __FILE__, __LINE__);
1057 goto fail;
1058 } else if (len >= (int)sizeof(buf)) {
1059 v = PyUnicode_FromString("<INVALID>");
1060 } else {
1061 v = PyUnicode_FromStringAndSize(buf, len);
1062 }
1063 if (v == NULL) {
1064 Py_DECREF(t);
1065 goto fail;
1066 }
1067 PyTuple_SET_ITEM(t, 1, v);
1068 break;
1069
Christian Heimes88b174c2013-08-17 00:54:47 +02001070 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001071 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +02001072 switch (gntype) {
1073 /* check for new general name type */
1074 case GEN_OTHERNAME:
1075 case GEN_X400:
1076 case GEN_EDIPARTY:
1077 case GEN_IPADD:
1078 case GEN_RID:
1079 break;
1080 default:
1081 if (PyErr_Warn(PyExc_RuntimeWarning,
1082 "Unknown general name type") == -1) {
1083 goto fail;
1084 }
1085 break;
1086 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001087 (void) BIO_reset(biobuf);
1088 GENERAL_NAME_print(biobuf, name);
1089 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1090 if (len < 0) {
1091 _setSSLError(NULL, 0, __FILE__, __LINE__);
1092 goto fail;
1093 }
1094 vptr = strchr(buf, ':');
Christian Heimes6663eb62016-09-06 23:25:35 +02001095 if (vptr == NULL) {
1096 PyErr_Format(PyExc_ValueError,
1097 "Invalid value %.200s",
1098 buf);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001099 goto fail;
Christian Heimes6663eb62016-09-06 23:25:35 +02001100 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001101 t = PyTuple_New(2);
1102 if (t == NULL)
1103 goto fail;
1104 v = PyString_FromStringAndSize(buf, (vptr - buf));
1105 if (v == NULL) {
1106 Py_DECREF(t);
1107 goto fail;
1108 }
1109 PyTuple_SET_ITEM(t, 0, v);
1110 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
1111 if (v == NULL) {
1112 Py_DECREF(t);
1113 goto fail;
1114 }
1115 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +02001116 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001117 }
1118
1119 /* and add that rendering to the list */
1120
1121 if (PyList_Append(peer_alt_names, t) < 0) {
1122 Py_DECREF(t);
1123 goto fail;
1124 }
1125 Py_DECREF(t);
1126 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +01001127 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001128 }
1129 BIO_free(biobuf);
1130 if (peer_alt_names != Py_None) {
1131 v = PyList_AsTuple(peer_alt_names);
1132 Py_DECREF(peer_alt_names);
1133 return v;
1134 } else {
1135 return peer_alt_names;
1136 }
1137
Bill Janssen98d19da2007-09-10 21:51:02 +00001138
1139 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001140 if (biobuf != NULL)
1141 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +00001142
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001143 if (peer_alt_names != Py_None) {
1144 Py_XDECREF(peer_alt_names);
1145 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001146
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001147 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001148}
1149
1150static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001151_get_aia_uri(X509 *certificate, int nid) {
1152 PyObject *lst = NULL, *ostr = NULL;
1153 int i, result;
1154 AUTHORITY_INFO_ACCESS *info;
1155
1156 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonc5919362015-11-14 15:12:18 -08001157 if (info == NULL)
1158 return Py_None;
1159 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1160 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001161 return Py_None;
1162 }
1163
1164 if ((lst = PyList_New(0)) == NULL) {
1165 goto fail;
1166 }
1167
1168 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1169 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1170 ASN1_IA5STRING *uri;
1171
1172 if ((OBJ_obj2nid(ad->method) != nid) ||
1173 (ad->location->type != GEN_URI)) {
1174 continue;
1175 }
1176 uri = ad->location->d.uniformResourceIdentifier;
1177 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1178 uri->length);
1179 if (ostr == NULL) {
1180 goto fail;
1181 }
1182 result = PyList_Append(lst, ostr);
1183 Py_DECREF(ostr);
1184 if (result < 0) {
1185 goto fail;
1186 }
1187 }
1188 AUTHORITY_INFO_ACCESS_free(info);
1189
1190 /* convert to tuple or None */
1191 if (PyList_Size(lst) == 0) {
1192 Py_DECREF(lst);
1193 return Py_None;
1194 } else {
1195 PyObject *tup;
1196 tup = PyList_AsTuple(lst);
1197 Py_DECREF(lst);
1198 return tup;
1199 }
1200
1201 fail:
1202 AUTHORITY_INFO_ACCESS_free(info);
1203 Py_XDECREF(lst);
1204 return NULL;
1205}
1206
1207static PyObject *
1208_get_crl_dp(X509 *certificate) {
1209 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001210 int i, j;
1211 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001212
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001213 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001214
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001215 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001216 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001217
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001218 lst = PyList_New(0);
1219 if (lst == NULL)
1220 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001221
1222 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1223 DIST_POINT *dp;
1224 STACK_OF(GENERAL_NAME) *gns;
1225
1226 dp = sk_DIST_POINT_value(dps, i);
1227 gns = dp->distpoint->name.fullname;
1228
1229 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1230 GENERAL_NAME *gn;
1231 ASN1_IA5STRING *uri;
1232 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001233 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001234
1235 gn = sk_GENERAL_NAME_value(gns, j);
1236 if (gn->type != GEN_URI) {
1237 continue;
1238 }
1239 uri = gn->d.uniformResourceIdentifier;
1240 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1241 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001242 if (ouri == NULL)
1243 goto done;
1244
1245 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001246 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001247 if (err < 0)
1248 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001249 }
1250 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001251
1252 /* Convert to tuple. */
1253 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1254
1255 done:
1256 Py_XDECREF(lst);
Mariattab2b00e02017-04-14 18:24:22 -07001257 CRL_DIST_POINTS_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001258 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001259}
1260
1261static PyObject *
1262_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001263
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001264 PyObject *retval = NULL;
1265 BIO *biobuf = NULL;
1266 PyObject *peer;
1267 PyObject *peer_alt_names = NULL;
1268 PyObject *issuer;
1269 PyObject *version;
1270 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001271 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001272 ASN1_INTEGER *serialNumber;
1273 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001274 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001275 ASN1_TIME *notBefore, *notAfter;
1276 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001277
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001278 retval = PyDict_New();
1279 if (retval == NULL)
1280 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001281
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001282 peer = _create_tuple_for_X509_NAME(
1283 X509_get_subject_name(certificate));
1284 if (peer == NULL)
1285 goto fail0;
1286 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1287 Py_DECREF(peer);
1288 goto fail0;
1289 }
1290 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001291
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001292 issuer = _create_tuple_for_X509_NAME(
1293 X509_get_issuer_name(certificate));
1294 if (issuer == NULL)
1295 goto fail0;
1296 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001297 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001298 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001299 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001300 Py_DECREF(issuer);
1301
1302 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1303 if (version == NULL)
1304 goto fail0;
1305 if (PyDict_SetItemString(retval, "version", version) < 0) {
1306 Py_DECREF(version);
1307 goto fail0;
1308 }
1309 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001310
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001311 /* get a memory buffer */
1312 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001313
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001314 (void) BIO_reset(biobuf);
1315 serialNumber = X509_get_serialNumber(certificate);
1316 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1317 i2a_ASN1_INTEGER(biobuf, serialNumber);
1318 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1319 if (len < 0) {
1320 _setSSLError(NULL, 0, __FILE__, __LINE__);
1321 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001322 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001323 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1324 if (sn_obj == NULL)
1325 goto fail1;
1326 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1327 Py_DECREF(sn_obj);
1328 goto fail1;
1329 }
1330 Py_DECREF(sn_obj);
1331
1332 (void) BIO_reset(biobuf);
1333 notBefore = X509_get_notBefore(certificate);
1334 ASN1_TIME_print(biobuf, notBefore);
1335 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1336 if (len < 0) {
1337 _setSSLError(NULL, 0, __FILE__, __LINE__);
1338 goto fail1;
1339 }
1340 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1341 if (pnotBefore == NULL)
1342 goto fail1;
1343 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1344 Py_DECREF(pnotBefore);
1345 goto fail1;
1346 }
1347 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001348
1349 (void) BIO_reset(biobuf);
1350 notAfter = X509_get_notAfter(certificate);
1351 ASN1_TIME_print(biobuf, notAfter);
1352 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1353 if (len < 0) {
1354 _setSSLError(NULL, 0, __FILE__, __LINE__);
1355 goto fail1;
1356 }
1357 pnotAfter = PyString_FromStringAndSize(buf, len);
1358 if (pnotAfter == NULL)
1359 goto fail1;
1360 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1361 Py_DECREF(pnotAfter);
1362 goto fail1;
1363 }
1364 Py_DECREF(pnotAfter);
1365
1366 /* Now look for subjectAltName */
1367
1368 peer_alt_names = _get_peer_alt_names(certificate);
1369 if (peer_alt_names == NULL)
1370 goto fail1;
1371 else if (peer_alt_names != Py_None) {
1372 if (PyDict_SetItemString(retval, "subjectAltName",
1373 peer_alt_names) < 0) {
1374 Py_DECREF(peer_alt_names);
1375 goto fail1;
1376 }
1377 Py_DECREF(peer_alt_names);
1378 }
1379
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001380 /* Authority Information Access: OCSP URIs */
1381 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1382 if (obj == NULL) {
1383 goto fail1;
1384 } else if (obj != Py_None) {
1385 result = PyDict_SetItemString(retval, "OCSP", obj);
1386 Py_DECREF(obj);
1387 if (result < 0) {
1388 goto fail1;
1389 }
1390 }
1391
1392 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1393 if (obj == NULL) {
1394 goto fail1;
1395 } else if (obj != Py_None) {
1396 result = PyDict_SetItemString(retval, "caIssuers", obj);
1397 Py_DECREF(obj);
1398 if (result < 0) {
1399 goto fail1;
1400 }
1401 }
1402
1403 /* CDP (CRL distribution points) */
1404 obj = _get_crl_dp(certificate);
1405 if (obj == NULL) {
1406 goto fail1;
1407 } else if (obj != Py_None) {
1408 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1409 Py_DECREF(obj);
1410 if (result < 0) {
1411 goto fail1;
1412 }
1413 }
1414
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001415 BIO_free(biobuf);
1416 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001417
1418 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001419 if (biobuf != NULL)
1420 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001421 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001422 Py_XDECREF(retval);
1423 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001424}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001426static PyObject *
1427_certificate_to_der(X509 *certificate)
1428{
1429 unsigned char *bytes_buf = NULL;
1430 int len;
1431 PyObject *retval;
1432
1433 bytes_buf = NULL;
1434 len = i2d_X509(certificate, &bytes_buf);
1435 if (len < 0) {
1436 _setSSLError(NULL, 0, __FILE__, __LINE__);
1437 return NULL;
1438 }
1439 /* this is actually an immutable bytes sequence */
1440 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1441 OPENSSL_free(bytes_buf);
1442 return retval;
1443}
Bill Janssen98d19da2007-09-10 21:51:02 +00001444
1445static PyObject *
1446PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1447
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001448 PyObject *retval = NULL;
1449 char *filename = NULL;
1450 X509 *x=NULL;
1451 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001452
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001453 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001454 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001455
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001456 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001457 PyErr_SetString(PySSLErrorObject,
1458 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001459 goto fail0;
1460 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001461
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001462 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001463 PyErr_SetString(PySSLErrorObject,
1464 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001465 goto fail0;
1466 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001467
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001468 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1469 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001470 PyErr_SetString(PySSLErrorObject,
1471 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001472 goto fail0;
1473 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001474
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001475 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001476 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001477
1478 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001479
1480 if (cert != NULL) BIO_free(cert);
1481 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001482}
1483
1484
1485static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001486PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001487{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001488 int verification;
1489 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001490 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001491
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001492 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1493 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001494
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001495 if (!self->handshake_done) {
1496 PyErr_SetString(PyExc_ValueError,
1497 "handshake not done yet");
1498 return NULL;
1499 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001500 if (!self->peer_cert)
1501 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001502
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001503 b = PyObject_IsTrue(binary_mode);
1504 if (b < 0)
1505 return NULL;
1506 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001507 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001508 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001509 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001510 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001511 if ((verification & SSL_VERIFY_PEER) == 0)
1512 return PyDict_New();
1513 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001514 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001515 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001516}
1517
1518PyDoc_STRVAR(PySSL_peercert_doc,
1519"peer_certificate([der=False]) -> certificate\n\
1520\n\
1521Returns the certificate for the peer. If no certificate was provided,\n\
1522returns None. If a certificate was provided, but not validated, returns\n\
1523an empty dictionary. Otherwise returns a dict containing information\n\
1524about the peer certificate.\n\
1525\n\
1526If the optional argument is True, returns a DER-encoded copy of the\n\
1527peer certificate, or None if no certificate was provided. This will\n\
1528return the certificate even if it wasn't validated.");
1529
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001530static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001531
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001532 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001533 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001534 char *cipher_name;
1535 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001536
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001537 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001538 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001539 current = SSL_get_current_cipher(self->ssl);
1540 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001541 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001542
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001543 retval = PyTuple_New(3);
1544 if (retval == NULL)
1545 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001546
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001547 cipher_name = (char *) SSL_CIPHER_get_name(current);
1548 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001549 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001550 PyTuple_SET_ITEM(retval, 0, Py_None);
1551 } else {
1552 v = PyString_FromString(cipher_name);
1553 if (v == NULL)
1554 goto fail0;
1555 PyTuple_SET_ITEM(retval, 0, v);
1556 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001557 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001558 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001559 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001560 PyTuple_SET_ITEM(retval, 1, Py_None);
1561 } else {
1562 v = PyString_FromString(cipher_protocol);
1563 if (v == NULL)
1564 goto fail0;
1565 PyTuple_SET_ITEM(retval, 1, v);
1566 }
1567 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1568 if (v == NULL)
1569 goto fail0;
1570 PyTuple_SET_ITEM(retval, 2, v);
1571 return retval;
1572
Bill Janssen98d19da2007-09-10 21:51:02 +00001573 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001574 Py_DECREF(retval);
1575 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001576}
1577
Alex Gaynore98205d2014-09-04 13:33:22 -07001578static PyObject *PySSL_version(PySSLSocket *self)
1579{
1580 const char *version;
1581
1582 if (self->ssl == NULL)
1583 Py_RETURN_NONE;
1584 version = SSL_get_version(self->ssl);
1585 if (!strcmp(version, "unknown"))
1586 Py_RETURN_NONE;
1587 return PyUnicode_FromString(version);
1588}
1589
Christian Heimes72ed2332017-09-05 01:11:40 +02001590#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001591static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1592 const unsigned char *out;
1593 unsigned int outlen;
1594
1595 SSL_get0_next_proto_negotiated(self->ssl,
1596 &out, &outlen);
1597
1598 if (out == NULL)
1599 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001600 return PyString_FromStringAndSize((char *)out, outlen);
1601}
1602#endif
1603
Christian Heimesdf1732a2018-02-25 14:28:55 +01001604#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001605static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1606 const unsigned char *out;
1607 unsigned int outlen;
1608
1609 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1610
1611 if (out == NULL)
1612 Py_RETURN_NONE;
1613 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001614}
1615#endif
1616
1617static PyObject *PySSL_compression(PySSLSocket *self) {
1618#ifdef OPENSSL_NO_COMP
1619 Py_RETURN_NONE;
1620#else
1621 const COMP_METHOD *comp_method;
1622 const char *short_name;
1623
1624 if (self->ssl == NULL)
1625 Py_RETURN_NONE;
1626 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001627 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001628 Py_RETURN_NONE;
Christian Heimes99406332016-09-06 01:10:39 +02001629 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001630 if (short_name == NULL)
1631 Py_RETURN_NONE;
1632 return PyBytes_FromString(short_name);
1633#endif
1634}
1635
1636static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1637 Py_INCREF(self->ctx);
1638 return self->ctx;
1639}
1640
1641static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1642 void *closure) {
1643
1644 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1645#if !HAVE_SNI
1646 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1647 "context is not supported by your OpenSSL library");
1648 return -1;
1649#else
1650 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001651 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001652 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1653#endif
1654 } else {
1655 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1656 return -1;
1657 }
1658
1659 return 0;
1660}
1661
1662PyDoc_STRVAR(PySSL_set_context_doc,
1663"_setter_context(ctx)\n\
1664\
1665This changes the context associated with the SSLSocket. This is typically\n\
1666used from within a callback function set by the set_servername_callback\n\
1667on the SSLContext to change the certificate information associated with the\n\
1668SSLSocket before the cryptographic exchange handshake messages\n");
1669
1670
1671
1672static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001673{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001674 if (self->peer_cert) /* Possible not to have one? */
1675 X509_free (self->peer_cert);
1676 if (self->ssl)
1677 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001678 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001679 Py_XDECREF(self->ssl_sock);
1680 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001681 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001682}
1683
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001684/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001685 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001686 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001687 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001688
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001689static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001690check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001691{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001692 fd_set fds;
1693 struct timeval tv;
1694 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001695
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001696 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1697 if (s->sock_timeout < 0.0)
1698 return SOCKET_IS_BLOCKING;
1699 else if (s->sock_timeout == 0.0)
1700 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001701
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001702 /* Guard against closed socket */
1703 if (s->sock_fd < 0)
1704 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001705
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001706 /* Prefer poll, if available, since you can poll() any fd
1707 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001708#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001709 {
1710 struct pollfd pollfd;
1711 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001712
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001713 pollfd.fd = s->sock_fd;
1714 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001715
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001716 /* s->sock_timeout is in seconds, timeout in ms */
1717 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1718 PySSL_BEGIN_ALLOW_THREADS
1719 rc = poll(&pollfd, 1, timeout);
1720 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001721
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001722 goto normal_return;
1723 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001724#endif
1725
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001726 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001727 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001729
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001730 /* Construct the arguments to select */
1731 tv.tv_sec = (int)s->sock_timeout;
1732 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1733 FD_ZERO(&fds);
1734 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001735
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001736 /* See if the socket is ready */
1737 PySSL_BEGIN_ALLOW_THREADS
1738 if (writing)
1739 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1740 else
1741 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1742 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001743
Bill Janssen934b16d2008-06-28 22:19:33 +00001744#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001745normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001746#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001747 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1748 (when we are able to write or when there's something to read) */
1749 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001750}
1751
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001752static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001753{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001754 Py_buffer buf;
1755 int len;
1756 int sockstate;
1757 int err;
1758 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001759 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001761 Py_INCREF(sock);
1762
1763 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1764 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001765 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001766 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001767
Victor Stinnerc1a44262013-06-25 00:48:02 +02001768 if (buf.len > INT_MAX) {
1769 PyErr_Format(PyExc_OverflowError,
1770 "string longer than %d bytes", INT_MAX);
1771 goto error;
1772 }
1773
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001774 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001775 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001776 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1777 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001778
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001779 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001780 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1781 PyErr_SetString(PySSLErrorObject,
1782 "The write operation timed out");
1783 goto error;
1784 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1785 PyErr_SetString(PySSLErrorObject,
1786 "Underlying socket has been closed.");
1787 goto error;
1788 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1789 PyErr_SetString(PySSLErrorObject,
1790 "Underlying socket too large for select().");
1791 goto error;
1792 }
1793 do {
1794 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001795 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001796 err = SSL_get_error(self->ssl, len);
1797 PySSL_END_ALLOW_THREADS
1798 if (PyErr_CheckSignals()) {
1799 goto error;
1800 }
1801 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001802 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001803 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001804 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001805 } else {
1806 sockstate = SOCKET_OPERATION_OK;
1807 }
1808 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1809 PyErr_SetString(PySSLErrorObject,
1810 "The write operation timed out");
1811 goto error;
1812 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1813 PyErr_SetString(PySSLErrorObject,
1814 "Underlying socket has been closed.");
1815 goto error;
1816 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1817 break;
1818 }
1819 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001820
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001821 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001822 PyBuffer_Release(&buf);
1823 if (len > 0)
1824 return PyInt_FromLong(len);
1825 else
1826 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001827
1828error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001829 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001830 PyBuffer_Release(&buf);
1831 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001832}
1833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001834PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001835"write(s) -> len\n\
1836\n\
1837Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001838of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001839
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001840static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001841{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001843
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001844 PySSL_BEGIN_ALLOW_THREADS
1845 count = SSL_pending(self->ssl);
1846 PySSL_END_ALLOW_THREADS
1847 if (count < 0)
1848 return PySSL_SetError(self, count, __FILE__, __LINE__);
1849 else
1850 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001851}
1852
1853PyDoc_STRVAR(PySSL_SSLpending_doc,
1854"pending() -> count\n\
1855\n\
1856Returns the number of already decrypted bytes available for read,\n\
1857pending on the connection.\n");
1858
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001859static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001860{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001861 PyObject *dest = NULL;
1862 Py_buffer buf;
1863 char *mem;
1864 int len, count;
1865 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001866 int sockstate;
1867 int err;
1868 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001869 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001870
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001871 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001872
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001873 buf.obj = NULL;
1874 buf.buf = NULL;
1875 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1876 goto error;
1877
1878 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001879 if (len < 0) {
1880 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1881 goto error;
1882 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001883 dest = PyBytes_FromStringAndSize(NULL, len);
1884 if (dest == NULL)
1885 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001886 if (len == 0) {
1887 Py_XDECREF(sock);
1888 return dest;
1889 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001890 mem = PyBytes_AS_STRING(dest);
1891 }
1892 else {
1893 buf_passed = 1;
1894 mem = buf.buf;
1895 if (len <= 0 || len > buf.len) {
1896 len = (int) buf.len;
1897 if (buf.len != len) {
1898 PyErr_SetString(PyExc_OverflowError,
1899 "maximum length can't fit in a C 'int'");
1900 goto error;
1901 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001902 if (len == 0) {
1903 count = 0;
1904 goto done;
1905 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001906 }
1907 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001908
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001909 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001910 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001911 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1912 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001913
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001914 do {
1915 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001916 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001917 err = SSL_get_error(self->ssl, count);
1918 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001919 if (PyErr_CheckSignals())
1920 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001921 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001922 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001923 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001924 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001925 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1926 (SSL_get_shutdown(self->ssl) ==
1927 SSL_RECEIVED_SHUTDOWN))
1928 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001929 count = 0;
1930 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001931 } else {
1932 sockstate = SOCKET_OPERATION_OK;
1933 }
1934 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1935 PyErr_SetString(PySSLErrorObject,
1936 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001937 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001938 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1939 break;
1940 }
1941 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1942 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001943 PySSL_SetError(self, count, __FILE__, __LINE__);
1944 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001945 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001946
1947done:
1948 Py_DECREF(sock);
1949 if (!buf_passed) {
1950 _PyBytes_Resize(&dest, count);
1951 return dest;
1952 }
1953 else {
1954 PyBuffer_Release(&buf);
1955 return PyLong_FromLong(count);
1956 }
1957
1958error:
1959 Py_DECREF(sock);
1960 if (!buf_passed)
1961 Py_XDECREF(dest);
1962 else
1963 PyBuffer_Release(&buf);
1964 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001965}
1966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001968"read([len]) -> string\n\
1969\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001970Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001971
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001972static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001973{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001974 int err, ssl_err, sockstate, nonblocking;
1975 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001976 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001977
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001978 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001979 if (sock->sock_fd < 0) {
1980 _setSSLError("Underlying socket connection gone",
1981 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001982 return NULL;
1983 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001984 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001985
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001986 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001987 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001988 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1989 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001990
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001991 while (1) {
1992 PySSL_BEGIN_ALLOW_THREADS
1993 /* Disable read-ahead so that unwrap can work correctly.
1994 * Otherwise OpenSSL might read in too much data,
1995 * eating clear text data that happens to be
1996 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001997 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001998 * function is used and the shutdown_seen_zero != 0
1999 * condition is met.
2000 */
2001 if (self->shutdown_seen_zero)
2002 SSL_set_read_ahead(self->ssl, 0);
2003 err = SSL_shutdown(self->ssl);
2004 PySSL_END_ALLOW_THREADS
2005 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2006 if (err > 0)
2007 break;
2008 if (err == 0) {
2009 /* Don't loop endlessly; instead preserve legacy
2010 behaviour of trying SSL_shutdown() only twice.
2011 This looks necessary for OpenSSL < 0.9.8m */
2012 if (++zeros > 1)
2013 break;
2014 /* Shutdown was sent, now try receiving */
2015 self->shutdown_seen_zero = 1;
2016 continue;
2017 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00002018
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002019 /* Possibly retry shutdown until timeout or failure */
2020 ssl_err = SSL_get_error(self->ssl, err);
2021 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002022 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002023 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002024 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002025 else
2026 break;
2027 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2028 if (ssl_err == SSL_ERROR_WANT_READ)
2029 PyErr_SetString(PySSLErrorObject,
2030 "The read operation timed out");
2031 else
2032 PyErr_SetString(PySSLErrorObject,
2033 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002034 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002035 }
2036 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2037 PyErr_SetString(PySSLErrorObject,
2038 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002039 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002040 }
2041 else if (sockstate != SOCKET_OPERATION_OK)
2042 /* Retain the SSL error code */
2043 break;
2044 }
Bill Janssen934b16d2008-06-28 22:19:33 +00002045
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002046 if (err < 0) {
2047 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002048 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002049 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002050 else
2051 /* It's already INCREF'ed */
2052 return (PyObject *) sock;
2053
2054error:
2055 Py_DECREF(sock);
2056 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00002057}
2058
2059PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2060"shutdown(s) -> socket\n\
2061\n\
2062Does the SSL shutdown handshake with the remote end, and returns\n\
2063the underlying socket object.");
2064
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002065#if HAVE_OPENSSL_FINISHED
2066static PyObject *
2067PySSL_tls_unique_cb(PySSLSocket *self)
2068{
2069 PyObject *retval = NULL;
2070 char buf[PySSL_CB_MAXLEN];
2071 size_t len;
2072
2073 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2074 /* if session is resumed XOR we are the client */
2075 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2076 }
2077 else {
2078 /* if a new session XOR we are the server */
2079 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2080 }
2081
2082 /* It cannot be negative in current OpenSSL version as of July 2011 */
2083 if (len == 0)
2084 Py_RETURN_NONE;
2085
2086 retval = PyBytes_FromStringAndSize(buf, len);
2087
2088 return retval;
2089}
2090
2091PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2092"tls_unique_cb() -> bytes\n\
2093\n\
2094Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2095\n\
2096If the TLS handshake is not yet complete, None is returned");
2097
2098#endif /* HAVE_OPENSSL_FINISHED */
2099
2100static PyGetSetDef ssl_getsetlist[] = {
2101 {"context", (getter) PySSL_get_context,
2102 (setter) PySSL_set_context, PySSL_set_context_doc},
2103 {NULL}, /* sentinel */
2104};
2105
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002106static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002107 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2108 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2109 PySSL_SSLwrite_doc},
2110 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2111 PySSL_SSLread_doc},
2112 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2113 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002114 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2115 PySSL_peercert_doc},
2116 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07002117 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002118#ifdef OPENSSL_NPN_NEGOTIATED
2119 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2120#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002121#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002122 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2123#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002124 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002125 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2126 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002127#if HAVE_OPENSSL_FINISHED
2128 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2129 PySSL_tls_unique_cb_doc},
2130#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002131 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002132};
2133
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002134static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002135 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002136 "_ssl._SSLSocket", /*tp_name*/
2137 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002138 0, /*tp_itemsize*/
2139 /* methods */
2140 (destructor)PySSL_dealloc, /*tp_dealloc*/
2141 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002142 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002143 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002144 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00002145 0, /*tp_repr*/
2146 0, /*tp_as_number*/
2147 0, /*tp_as_sequence*/
2148 0, /*tp_as_mapping*/
2149 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002150 0, /*tp_call*/
2151 0, /*tp_str*/
2152 0, /*tp_getattro*/
2153 0, /*tp_setattro*/
2154 0, /*tp_as_buffer*/
2155 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2156 0, /*tp_doc*/
2157 0, /*tp_traverse*/
2158 0, /*tp_clear*/
2159 0, /*tp_richcompare*/
2160 0, /*tp_weaklistoffset*/
2161 0, /*tp_iter*/
2162 0, /*tp_iternext*/
2163 PySSLMethods, /*tp_methods*/
2164 0, /*tp_members*/
2165 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002166};
2167
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002168
2169/*
2170 * _SSLContext objects
2171 */
2172
2173static PyObject *
2174context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2175{
2176 char *kwlist[] = {"protocol", NULL};
2177 PySSLContext *self;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002178 int proto_version = PY_SSL_VERSION_TLS;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002179 long options;
2180 SSL_CTX *ctx = NULL;
2181
2182 if (!PyArg_ParseTupleAndKeywords(
2183 args, kwds, "i:_SSLContext", kwlist,
2184 &proto_version))
2185 return NULL;
2186
2187 PySSL_BEGIN_ALLOW_THREADS
2188 if (proto_version == PY_SSL_VERSION_TLS1)
2189 ctx = SSL_CTX_new(TLSv1_method());
2190#if HAVE_TLSv1_2
2191 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2192 ctx = SSL_CTX_new(TLSv1_1_method());
2193 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2194 ctx = SSL_CTX_new(TLSv1_2_method());
2195#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002196#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002197 else if (proto_version == PY_SSL_VERSION_SSL3)
2198 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002199#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002200#ifndef OPENSSL_NO_SSL2
2201 else if (proto_version == PY_SSL_VERSION_SSL2)
2202 ctx = SSL_CTX_new(SSLv2_method());
2203#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002204 else if (proto_version == PY_SSL_VERSION_TLS)
2205 ctx = SSL_CTX_new(TLS_method());
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002206 else
2207 proto_version = -1;
2208 PySSL_END_ALLOW_THREADS
2209
2210 if (proto_version == -1) {
2211 PyErr_SetString(PyExc_ValueError,
2212 "invalid protocol version");
2213 return NULL;
2214 }
2215 if (ctx == NULL) {
Christian Heimes611a3ea2017-09-07 16:45:07 -07002216 _setSSLError(NULL, 0, __FILE__, __LINE__);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002217 return NULL;
2218 }
2219
2220 assert(type != NULL && type->tp_alloc != NULL);
2221 self = (PySSLContext *) type->tp_alloc(type, 0);
2222 if (self == NULL) {
2223 SSL_CTX_free(ctx);
2224 return NULL;
2225 }
2226 self->ctx = ctx;
Christian Heimesdf1732a2018-02-25 14:28:55 +01002227#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002228 self->npn_protocols = NULL;
2229#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002230#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002231 self->alpn_protocols = NULL;
2232#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002233#ifndef OPENSSL_NO_TLSEXT
2234 self->set_hostname = NULL;
2235#endif
2236 /* Don't check host name by default */
2237 self->check_hostname = 0;
2238 /* Defaults */
2239 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2240 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2241 if (proto_version != PY_SSL_VERSION_SSL2)
2242 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002243 if (proto_version != PY_SSL_VERSION_SSL3)
2244 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002245 SSL_CTX_set_options(self->ctx, options);
2246
Donald Stufftf1a696e2017-03-02 12:37:07 -05002247#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002248 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2249 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002250 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2251 */
Donald Stufftf1a696e2017-03-02 12:37:07 -05002252#if defined(SSL_CTX_set_ecdh_auto)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002253 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2254#else
2255 {
2256 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2257 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2258 EC_KEY_free(key);
2259 }
2260#endif
2261#endif
2262
2263#define SID_CTX "Python"
2264 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2265 sizeof(SID_CTX));
2266#undef SID_CTX
2267
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002268#ifdef X509_V_FLAG_TRUSTED_FIRST
2269 {
2270 /* Improve trust chain building when cross-signed intermediate
2271 certificates are present. See https://bugs.python.org/issue23476. */
2272 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2273 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2274 }
2275#endif
2276
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002277 return (PyObject *)self;
2278}
2279
2280static int
2281context_traverse(PySSLContext *self, visitproc visit, void *arg)
2282{
2283#ifndef OPENSSL_NO_TLSEXT
2284 Py_VISIT(self->set_hostname);
2285#endif
2286 return 0;
2287}
2288
2289static int
2290context_clear(PySSLContext *self)
2291{
2292#ifndef OPENSSL_NO_TLSEXT
2293 Py_CLEAR(self->set_hostname);
2294#endif
2295 return 0;
2296}
2297
2298static void
2299context_dealloc(PySSLContext *self)
2300{
INADA Naoki4cde4bd2017-09-04 12:31:41 +09002301 /* bpo-31095: UnTrack is needed before calling any callbacks */
2302 PyObject_GC_UnTrack(self);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002303 context_clear(self);
2304 SSL_CTX_free(self->ctx);
Christian Heimesdf1732a2018-02-25 14:28:55 +01002305#if HAVE_NPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002306 PyMem_FREE(self->npn_protocols);
2307#endif
Christian Heimesdf1732a2018-02-25 14:28:55 +01002308#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002309 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002310#endif
2311 Py_TYPE(self)->tp_free(self);
2312}
2313
2314static PyObject *
2315set_ciphers(PySSLContext *self, PyObject *args)
2316{
2317 int ret;
2318 const char *cipherlist;
2319
2320 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2321 return NULL;
2322 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2323 if (ret == 0) {
2324 /* Clearing the error queue is necessary on some OpenSSL versions,
2325 otherwise the error will be reported again when another SSL call
2326 is done. */
2327 ERR_clear_error();
2328 PyErr_SetString(PySSLErrorObject,
2329 "No cipher can be selected.");
2330 return NULL;
2331 }
2332 Py_RETURN_NONE;
2333}
2334
Christian Heimesdf1732a2018-02-25 14:28:55 +01002335#if HAVE_NPN || HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002336static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002337do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2338 const unsigned char *server_protocols, unsigned int server_protocols_len,
2339 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002340{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002341 int ret;
2342 if (client_protocols == NULL) {
2343 client_protocols = (unsigned char *)"";
2344 client_protocols_len = 0;
2345 }
2346 if (server_protocols == NULL) {
2347 server_protocols = (unsigned char *)"";
2348 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002349 }
2350
Benjamin Petersonaa707582015-01-23 17:30:26 -05002351 ret = SSL_select_next_proto(out, outlen,
2352 server_protocols, server_protocols_len,
2353 client_protocols, client_protocols_len);
2354 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2355 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002356
2357 return SSL_TLSEXT_ERR_OK;
2358}
Christian Heimes72ed2332017-09-05 01:11:40 +02002359#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002360
Christian Heimesdf1732a2018-02-25 14:28:55 +01002361#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002362/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2363static int
2364_advertiseNPN_cb(SSL *s,
2365 const unsigned char **data, unsigned int *len,
2366 void *args)
2367{
2368 PySSLContext *ssl_ctx = (PySSLContext *) args;
2369
2370 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002371 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002372 *len = 0;
2373 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002374 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002375 *len = ssl_ctx->npn_protocols_len;
2376 }
2377
2378 return SSL_TLSEXT_ERR_OK;
2379}
2380/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2381static int
2382_selectNPN_cb(SSL *s,
2383 unsigned char **out, unsigned char *outlen,
2384 const unsigned char *server, unsigned int server_len,
2385 void *args)
2386{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002387 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002388 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002389 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002390}
2391#endif
2392
2393static PyObject *
2394_set_npn_protocols(PySSLContext *self, PyObject *args)
2395{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002396#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002397 Py_buffer protos;
2398
2399 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2400 return NULL;
2401
2402 if (self->npn_protocols != NULL) {
2403 PyMem_Free(self->npn_protocols);
2404 }
2405
2406 self->npn_protocols = PyMem_Malloc(protos.len);
2407 if (self->npn_protocols == NULL) {
2408 PyBuffer_Release(&protos);
2409 return PyErr_NoMemory();
2410 }
2411 memcpy(self->npn_protocols, protos.buf, protos.len);
2412 self->npn_protocols_len = (int) protos.len;
2413
2414 /* set both server and client callbacks, because the context can
2415 * be used to create both types of sockets */
2416 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2417 _advertiseNPN_cb,
2418 self);
2419 SSL_CTX_set_next_proto_select_cb(self->ctx,
2420 _selectNPN_cb,
2421 self);
2422
2423 PyBuffer_Release(&protos);
2424 Py_RETURN_NONE;
2425#else
2426 PyErr_SetString(PyExc_NotImplementedError,
2427 "The NPN extension requires OpenSSL 1.0.1 or later.");
2428 return NULL;
2429#endif
2430}
2431
Christian Heimesdf1732a2018-02-25 14:28:55 +01002432#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002433static int
2434_selectALPN_cb(SSL *s,
2435 const unsigned char **out, unsigned char *outlen,
2436 const unsigned char *client_protocols, unsigned int client_protocols_len,
2437 void *args)
2438{
2439 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002440 return do_protocol_selection(1, (unsigned char **)out, outlen,
2441 ctx->alpn_protocols, ctx->alpn_protocols_len,
2442 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002443}
2444#endif
2445
2446static PyObject *
2447_set_alpn_protocols(PySSLContext *self, PyObject *args)
2448{
Christian Heimesdf1732a2018-02-25 14:28:55 +01002449#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002450 Py_buffer protos;
2451
2452 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2453 return NULL;
2454
2455 PyMem_FREE(self->alpn_protocols);
2456 self->alpn_protocols = PyMem_Malloc(protos.len);
2457 if (!self->alpn_protocols)
2458 return PyErr_NoMemory();
2459 memcpy(self->alpn_protocols, protos.buf, protos.len);
2460 self->alpn_protocols_len = protos.len;
2461 PyBuffer_Release(&protos);
2462
2463 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2464 return PyErr_NoMemory();
2465 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2466
2467 PyBuffer_Release(&protos);
2468 Py_RETURN_NONE;
2469#else
2470 PyErr_SetString(PyExc_NotImplementedError,
2471 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2472 return NULL;
2473#endif
2474}
2475
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002476static PyObject *
2477get_verify_mode(PySSLContext *self, void *c)
2478{
2479 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2480 case SSL_VERIFY_NONE:
2481 return PyLong_FromLong(PY_SSL_CERT_NONE);
2482 case SSL_VERIFY_PEER:
2483 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2484 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2485 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2486 }
2487 PyErr_SetString(PySSLErrorObject,
2488 "invalid return value from SSL_CTX_get_verify_mode");
2489 return NULL;
2490}
2491
2492static int
2493set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2494{
2495 int n, mode;
2496 if (!PyArg_Parse(arg, "i", &n))
2497 return -1;
2498 if (n == PY_SSL_CERT_NONE)
2499 mode = SSL_VERIFY_NONE;
2500 else if (n == PY_SSL_CERT_OPTIONAL)
2501 mode = SSL_VERIFY_PEER;
2502 else if (n == PY_SSL_CERT_REQUIRED)
2503 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2504 else {
2505 PyErr_SetString(PyExc_ValueError,
2506 "invalid value for verify_mode");
2507 return -1;
2508 }
2509 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2510 PyErr_SetString(PyExc_ValueError,
2511 "Cannot set verify_mode to CERT_NONE when "
2512 "check_hostname is enabled.");
2513 return -1;
2514 }
2515 SSL_CTX_set_verify(self->ctx, mode, NULL);
2516 return 0;
2517}
2518
2519#ifdef HAVE_OPENSSL_VERIFY_PARAM
2520static PyObject *
2521get_verify_flags(PySSLContext *self, void *c)
2522{
2523 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002524 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002525 unsigned long flags;
2526
2527 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002528 param = X509_STORE_get0_param(store);
2529 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002530 return PyLong_FromUnsignedLong(flags);
2531}
2532
2533static int
2534set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2535{
2536 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002537 X509_VERIFY_PARAM *param;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002538 unsigned long new_flags, flags, set, clear;
2539
2540 if (!PyArg_Parse(arg, "k", &new_flags))
2541 return -1;
2542 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002543 param = X509_STORE_get0_param(store);
2544 flags = X509_VERIFY_PARAM_get_flags(param);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002545 clear = flags & ~new_flags;
2546 set = ~flags & new_flags;
2547 if (clear) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002548 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002549 _setSSLError(NULL, 0, __FILE__, __LINE__);
2550 return -1;
2551 }
2552 }
2553 if (set) {
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002554 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002555 _setSSLError(NULL, 0, __FILE__, __LINE__);
2556 return -1;
2557 }
2558 }
2559 return 0;
2560}
2561#endif
2562
2563static PyObject *
2564get_options(PySSLContext *self, void *c)
2565{
2566 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2567}
2568
2569static int
2570set_options(PySSLContext *self, PyObject *arg, void *c)
2571{
2572 long new_opts, opts, set, clear;
2573 if (!PyArg_Parse(arg, "l", &new_opts))
2574 return -1;
2575 opts = SSL_CTX_get_options(self->ctx);
2576 clear = opts & ~new_opts;
2577 set = ~opts & new_opts;
2578 if (clear) {
2579#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2580 SSL_CTX_clear_options(self->ctx, clear);
2581#else
2582 PyErr_SetString(PyExc_ValueError,
2583 "can't clear options before OpenSSL 0.9.8m");
2584 return -1;
2585#endif
2586 }
2587 if (set)
2588 SSL_CTX_set_options(self->ctx, set);
2589 return 0;
2590}
2591
2592static PyObject *
2593get_check_hostname(PySSLContext *self, void *c)
2594{
2595 return PyBool_FromLong(self->check_hostname);
2596}
2597
2598static int
2599set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2600{
2601 PyObject *py_check_hostname;
2602 int check_hostname;
2603 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2604 return -1;
2605
2606 check_hostname = PyObject_IsTrue(py_check_hostname);
2607 if (check_hostname < 0)
2608 return -1;
2609 if (check_hostname &&
2610 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2611 PyErr_SetString(PyExc_ValueError,
2612 "check_hostname needs a SSL context with either "
2613 "CERT_OPTIONAL or CERT_REQUIRED");
2614 return -1;
2615 }
2616 self->check_hostname = check_hostname;
2617 return 0;
2618}
2619
2620
2621typedef struct {
2622 PyThreadState *thread_state;
2623 PyObject *callable;
2624 char *password;
2625 int size;
2626 int error;
2627} _PySSLPasswordInfo;
2628
2629static int
2630_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2631 const char *bad_type_error)
2632{
2633 /* Set the password and size fields of a _PySSLPasswordInfo struct
2634 from a unicode, bytes, or byte array object.
2635 The password field will be dynamically allocated and must be freed
2636 by the caller */
2637 PyObject *password_bytes = NULL;
2638 const char *data = NULL;
2639 Py_ssize_t size;
2640
2641 if (PyUnicode_Check(password)) {
2642 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2643 if (!password_bytes) {
2644 goto error;
2645 }
2646 data = PyBytes_AS_STRING(password_bytes);
2647 size = PyBytes_GET_SIZE(password_bytes);
2648 } else if (PyBytes_Check(password)) {
2649 data = PyBytes_AS_STRING(password);
2650 size = PyBytes_GET_SIZE(password);
2651 } else if (PyByteArray_Check(password)) {
2652 data = PyByteArray_AS_STRING(password);
2653 size = PyByteArray_GET_SIZE(password);
2654 } else {
2655 PyErr_SetString(PyExc_TypeError, bad_type_error);
2656 goto error;
2657 }
2658
2659 if (size > (Py_ssize_t)INT_MAX) {
2660 PyErr_Format(PyExc_ValueError,
2661 "password cannot be longer than %d bytes", INT_MAX);
2662 goto error;
2663 }
2664
2665 PyMem_Free(pw_info->password);
2666 pw_info->password = PyMem_Malloc(size);
2667 if (!pw_info->password) {
2668 PyErr_SetString(PyExc_MemoryError,
2669 "unable to allocate password buffer");
2670 goto error;
2671 }
2672 memcpy(pw_info->password, data, size);
2673 pw_info->size = (int)size;
2674
2675 Py_XDECREF(password_bytes);
2676 return 1;
2677
2678error:
2679 Py_XDECREF(password_bytes);
2680 return 0;
2681}
2682
2683static int
2684_password_callback(char *buf, int size, int rwflag, void *userdata)
2685{
2686 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2687 PyObject *fn_ret = NULL;
2688
2689 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2690
2691 if (pw_info->callable) {
2692 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2693 if (!fn_ret) {
2694 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2695 core python API, so we could use it to add a frame here */
2696 goto error;
2697 }
2698
2699 if (!_pwinfo_set(pw_info, fn_ret,
2700 "password callback must return a string")) {
2701 goto error;
2702 }
2703 Py_CLEAR(fn_ret);
2704 }
2705
2706 if (pw_info->size > size) {
2707 PyErr_Format(PyExc_ValueError,
2708 "password cannot be longer than %d bytes", size);
2709 goto error;
2710 }
2711
2712 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2713 memcpy(buf, pw_info->password, pw_info->size);
2714 return pw_info->size;
2715
2716error:
2717 Py_XDECREF(fn_ret);
2718 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2719 pw_info->error = 1;
2720 return -1;
2721}
2722
2723static PyObject *
2724load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2725{
2726 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002727 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2728 char *certfile_bytes = NULL;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002729 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2730 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002731 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2732 int r;
2733
2734 errno = 0;
2735 ERR_clear_error();
2736 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002737 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002738 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002739 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002740 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002741
2742 if (keyfile && keyfile != Py_None) {
2743 if (PyString_Check(keyfile)) {
2744 Py_INCREF(keyfile);
2745 keyfile_bytes = keyfile;
2746 } else {
2747 PyObject *u = PyUnicode_FromObject(keyfile);
2748 if (!u)
2749 goto error;
2750 keyfile_bytes = PyUnicode_AsEncodedString(
2751 u, Py_FileSystemDefaultEncoding, NULL);
2752 Py_DECREF(u);
2753 if (!keyfile_bytes)
2754 goto error;
2755 }
2756 }
2757
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002758 if (password && password != Py_None) {
2759 if (PyCallable_Check(password)) {
2760 pw_info.callable = password;
2761 } else if (!_pwinfo_set(&pw_info, password,
2762 "password should be a string or callable")) {
2763 goto error;
2764 }
2765 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2766 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2767 }
2768 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2769 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2770 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2771 if (r != 1) {
2772 if (pw_info.error) {
2773 ERR_clear_error();
2774 /* the password callback has already set the error information */
2775 }
2776 else if (errno != 0) {
2777 ERR_clear_error();
2778 PyErr_SetFromErrno(PyExc_IOError);
2779 }
2780 else {
2781 _setSSLError(NULL, 0, __FILE__, __LINE__);
2782 }
2783 goto error;
2784 }
2785 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2786 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002787 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002788 SSL_FILETYPE_PEM);
2789 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2790 if (r != 1) {
2791 if (pw_info.error) {
2792 ERR_clear_error();
2793 /* the password callback has already set the error information */
2794 }
2795 else if (errno != 0) {
2796 ERR_clear_error();
2797 PyErr_SetFromErrno(PyExc_IOError);
2798 }
2799 else {
2800 _setSSLError(NULL, 0, __FILE__, __LINE__);
2801 }
2802 goto error;
2803 }
2804 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2805 r = SSL_CTX_check_private_key(self->ctx);
2806 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2807 if (r != 1) {
2808 _setSSLError(NULL, 0, __FILE__, __LINE__);
2809 goto error;
2810 }
2811 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2812 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002813 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002814 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002815 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002816 Py_RETURN_NONE;
2817
2818error:
2819 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2820 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002821 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002822 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002823 PyMem_Free(certfile_bytes);
2824 return NULL;
2825}
2826
2827/* internal helper function, returns -1 on error
2828 */
2829static int
2830_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2831 int filetype)
2832{
2833 BIO *biobuf = NULL;
2834 X509_STORE *store;
2835 int retval = 0, err, loaded = 0;
2836
2837 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2838
2839 if (len <= 0) {
2840 PyErr_SetString(PyExc_ValueError,
2841 "Empty certificate data");
2842 return -1;
2843 } else if (len > INT_MAX) {
2844 PyErr_SetString(PyExc_OverflowError,
2845 "Certificate data is too long.");
2846 return -1;
2847 }
2848
2849 biobuf = BIO_new_mem_buf(data, (int)len);
2850 if (biobuf == NULL) {
2851 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2852 return -1;
2853 }
2854
2855 store = SSL_CTX_get_cert_store(self->ctx);
2856 assert(store != NULL);
2857
2858 while (1) {
2859 X509 *cert = NULL;
2860 int r;
2861
2862 if (filetype == SSL_FILETYPE_ASN1) {
2863 cert = d2i_X509_bio(biobuf, NULL);
2864 } else {
2865 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimesc2fc7c42016-09-05 23:37:13 +02002866 SSL_CTX_get_default_passwd_cb(self->ctx),
2867 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2868 );
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002869 }
2870 if (cert == NULL) {
2871 break;
2872 }
2873 r = X509_STORE_add_cert(store, cert);
2874 X509_free(cert);
2875 if (!r) {
2876 err = ERR_peek_last_error();
2877 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2878 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2879 /* cert already in hash table, not an error */
2880 ERR_clear_error();
2881 } else {
2882 break;
2883 }
2884 }
2885 loaded++;
2886 }
2887
2888 err = ERR_peek_last_error();
2889 if ((filetype == SSL_FILETYPE_ASN1) &&
2890 (loaded > 0) &&
2891 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2892 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2893 /* EOF ASN1 file, not an error */
2894 ERR_clear_error();
2895 retval = 0;
2896 } else if ((filetype == SSL_FILETYPE_PEM) &&
2897 (loaded > 0) &&
2898 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2899 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2900 /* EOF PEM file, not an error */
2901 ERR_clear_error();
2902 retval = 0;
2903 } else {
2904 _setSSLError(NULL, 0, __FILE__, __LINE__);
2905 retval = -1;
2906 }
2907
2908 BIO_free(biobuf);
2909 return retval;
2910}
2911
2912
2913static PyObject *
2914load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2915{
2916 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2917 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2918 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2919 const char *cafile_buf = NULL, *capath_buf = NULL;
2920 int r = 0, ok = 1;
2921
2922 errno = 0;
2923 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2924 "|OOO:load_verify_locations", kwlist,
2925 &cafile, &capath, &cadata))
2926 return NULL;
2927
2928 if (cafile == Py_None)
2929 cafile = NULL;
2930 if (capath == Py_None)
2931 capath = NULL;
2932 if (cadata == Py_None)
2933 cadata = NULL;
2934
2935 if (cafile == NULL && capath == NULL && cadata == NULL) {
2936 PyErr_SetString(PyExc_TypeError,
2937 "cafile, capath and cadata cannot be all omitted");
2938 goto error;
2939 }
2940
2941 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002942 if (PyString_Check(cafile)) {
2943 Py_INCREF(cafile);
2944 cafile_bytes = cafile;
2945 } else {
2946 PyObject *u = PyUnicode_FromObject(cafile);
2947 if (!u)
2948 goto error;
2949 cafile_bytes = PyUnicode_AsEncodedString(
2950 u, Py_FileSystemDefaultEncoding, NULL);
2951 Py_DECREF(u);
2952 if (!cafile_bytes)
2953 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002954 }
2955 }
2956 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002957 if (PyString_Check(capath)) {
2958 Py_INCREF(capath);
2959 capath_bytes = capath;
2960 } else {
2961 PyObject *u = PyUnicode_FromObject(capath);
2962 if (!u)
2963 goto error;
2964 capath_bytes = PyUnicode_AsEncodedString(
2965 u, Py_FileSystemDefaultEncoding, NULL);
2966 Py_DECREF(u);
2967 if (!capath_bytes)
2968 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002969 }
2970 }
2971
2972 /* validata cadata type and load cadata */
2973 if (cadata) {
2974 Py_buffer buf;
2975 PyObject *cadata_ascii = NULL;
2976
2977 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2978 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2979 PyBuffer_Release(&buf);
2980 PyErr_SetString(PyExc_TypeError,
2981 "cadata should be a contiguous buffer with "
2982 "a single dimension");
2983 goto error;
2984 }
2985 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2986 PyBuffer_Release(&buf);
2987 if (r == -1) {
2988 goto error;
2989 }
2990 } else {
2991 PyErr_Clear();
2992 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2993 if (cadata_ascii == NULL) {
2994 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002995 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002996 "bytes-like object");
2997 goto error;
2998 }
2999 r = _add_ca_certs(self,
3000 PyBytes_AS_STRING(cadata_ascii),
3001 PyBytes_GET_SIZE(cadata_ascii),
3002 SSL_FILETYPE_PEM);
3003 Py_DECREF(cadata_ascii);
3004 if (r == -1) {
3005 goto error;
3006 }
3007 }
3008 }
3009
3010 /* load cafile or capath */
3011 if (cafile_bytes || capath_bytes) {
3012 if (cafile)
3013 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3014 if (capath)
3015 capath_buf = PyBytes_AS_STRING(capath_bytes);
3016 PySSL_BEGIN_ALLOW_THREADS
3017 r = SSL_CTX_load_verify_locations(
3018 self->ctx,
3019 cafile_buf,
3020 capath_buf);
3021 PySSL_END_ALLOW_THREADS
3022 if (r != 1) {
3023 ok = 0;
3024 if (errno != 0) {
3025 ERR_clear_error();
3026 PyErr_SetFromErrno(PyExc_IOError);
3027 }
3028 else {
3029 _setSSLError(NULL, 0, __FILE__, __LINE__);
3030 }
3031 goto error;
3032 }
3033 }
3034 goto end;
3035
3036 error:
3037 ok = 0;
3038 end:
3039 Py_XDECREF(cafile_bytes);
3040 Py_XDECREF(capath_bytes);
3041 if (ok) {
3042 Py_RETURN_NONE;
3043 } else {
3044 return NULL;
3045 }
3046}
3047
3048static PyObject *
3049load_dh_params(PySSLContext *self, PyObject *filepath)
3050{
3051 BIO *bio;
3052 DH *dh;
Christian Heimes6e8f3952018-02-25 09:48:02 +01003053 PyObject *filepath_bytes = NULL;
3054
3055 if (PyString_Check(filepath)) {
3056 Py_INCREF(filepath);
3057 filepath_bytes = filepath;
3058 } else {
3059 PyObject *u = PyUnicode_FromObject(filepath);
3060 if (!u)
3061 return NULL;
3062 filepath_bytes = PyUnicode_AsEncodedString(
3063 u, Py_FileSystemDefaultEncoding, NULL);
3064 Py_DECREF(u);
3065 if (!filepath_bytes)
3066 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003067 }
3068
Christian Heimes6e8f3952018-02-25 09:48:02 +01003069 bio = BIO_new_file(PyBytes_AS_STRING(filepath_bytes), "r");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003070 if (bio == NULL) {
Christian Heimes6e8f3952018-02-25 09:48:02 +01003071 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003072 ERR_clear_error();
3073 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
3074 return NULL;
3075 }
3076 errno = 0;
3077 PySSL_BEGIN_ALLOW_THREADS
3078 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3079 BIO_free(bio);
Christian Heimes6e8f3952018-02-25 09:48:02 +01003080 Py_DECREF(filepath_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003081 PySSL_END_ALLOW_THREADS
3082 if (dh == NULL) {
3083 if (errno != 0) {
3084 ERR_clear_error();
3085 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3086 }
3087 else {
3088 _setSSLError(NULL, 0, __FILE__, __LINE__);
3089 }
3090 return NULL;
3091 }
3092 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3093 _setSSLError(NULL, 0, __FILE__, __LINE__);
3094 DH_free(dh);
3095 Py_RETURN_NONE;
3096}
3097
3098static PyObject *
3099context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3100{
3101 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
3102 PySocketSockObject *sock;
3103 int server_side = 0;
3104 char *hostname = NULL;
3105 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
3106
3107 /* server_hostname is either None (or absent), or to be encoded
3108 using the idna encoding. */
3109 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
3110 PySocketModule.Sock_Type,
3111 &sock, &server_side,
3112 Py_TYPE(Py_None), &hostname_obj,
3113 &ssl_sock)) {
3114 PyErr_Clear();
3115 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
3116 PySocketModule.Sock_Type,
3117 &sock, &server_side,
3118 "idna", &hostname, &ssl_sock))
3119 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003120 }
3121
3122 res = (PyObject *) newPySSLSocket(self, sock, server_side,
3123 hostname, ssl_sock);
3124 if (hostname != NULL)
3125 PyMem_Free(hostname);
3126 return res;
3127}
3128
3129static PyObject *
3130session_stats(PySSLContext *self, PyObject *unused)
3131{
3132 int r;
3133 PyObject *value, *stats = PyDict_New();
3134 if (!stats)
3135 return NULL;
3136
3137#define ADD_STATS(SSL_NAME, KEY_NAME) \
3138 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3139 if (value == NULL) \
3140 goto error; \
3141 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3142 Py_DECREF(value); \
3143 if (r < 0) \
3144 goto error;
3145
3146 ADD_STATS(number, "number");
3147 ADD_STATS(connect, "connect");
3148 ADD_STATS(connect_good, "connect_good");
3149 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3150 ADD_STATS(accept, "accept");
3151 ADD_STATS(accept_good, "accept_good");
3152 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3153 ADD_STATS(accept, "accept");
3154 ADD_STATS(hits, "hits");
3155 ADD_STATS(misses, "misses");
3156 ADD_STATS(timeouts, "timeouts");
3157 ADD_STATS(cache_full, "cache_full");
3158
3159#undef ADD_STATS
3160
3161 return stats;
3162
3163error:
3164 Py_DECREF(stats);
3165 return NULL;
3166}
3167
3168static PyObject *
3169set_default_verify_paths(PySSLContext *self, PyObject *unused)
3170{
3171 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3172 _setSSLError(NULL, 0, __FILE__, __LINE__);
3173 return NULL;
3174 }
3175 Py_RETURN_NONE;
3176}
3177
3178#ifndef OPENSSL_NO_ECDH
3179static PyObject *
3180set_ecdh_curve(PySSLContext *self, PyObject *name)
3181{
3182 char *name_bytes;
3183 int nid;
3184 EC_KEY *key;
3185
3186 name_bytes = PyBytes_AsString(name);
3187 if (!name_bytes) {
3188 return NULL;
3189 }
3190 nid = OBJ_sn2nid(name_bytes);
3191 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003192 PyObject *r = PyObject_Repr(name);
3193 if (!r)
3194 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003195 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05003196 "unknown elliptic curve name %s", PyString_AS_STRING(r));
3197 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003198 return NULL;
3199 }
3200 key = EC_KEY_new_by_curve_name(nid);
3201 if (key == NULL) {
3202 _setSSLError(NULL, 0, __FILE__, __LINE__);
3203 return NULL;
3204 }
3205 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3206 EC_KEY_free(key);
3207 Py_RETURN_NONE;
3208}
3209#endif
3210
3211#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3212static int
3213_servername_callback(SSL *s, int *al, void *args)
3214{
3215 int ret;
3216 PySSLContext *ssl_ctx = (PySSLContext *) args;
3217 PySSLSocket *ssl;
3218 PyObject *servername_o;
3219 PyObject *servername_idna;
3220 PyObject *result;
3221 /* The high-level ssl.SSLSocket object */
3222 PyObject *ssl_socket;
3223 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3224#ifdef WITH_THREAD
3225 PyGILState_STATE gstate = PyGILState_Ensure();
3226#endif
3227
3228 if (ssl_ctx->set_hostname == NULL) {
3229 /* remove race condition in this the call back while if removing the
3230 * callback is in progress */
3231#ifdef WITH_THREAD
3232 PyGILState_Release(gstate);
3233#endif
3234 return SSL_TLSEXT_ERR_OK;
3235 }
3236
3237 ssl = SSL_get_app_data(s);
3238 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003239 if (ssl->ssl_sock == NULL) {
3240 ssl_socket = Py_None;
3241 } else {
3242 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3243 Py_INCREF(ssl_socket);
3244 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003245 if (ssl_socket == Py_None) {
3246 goto error;
3247 }
3248
3249 if (servername == NULL) {
3250 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3251 Py_None, ssl_ctx, NULL);
3252 }
3253 else {
3254 servername_o = PyBytes_FromString(servername);
3255 if (servername_o == NULL) {
3256 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3257 goto error;
3258 }
3259 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3260 if (servername_idna == NULL) {
3261 PyErr_WriteUnraisable(servername_o);
3262 Py_DECREF(servername_o);
3263 goto error;
3264 }
3265 Py_DECREF(servername_o);
3266 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3267 servername_idna, ssl_ctx, NULL);
3268 Py_DECREF(servername_idna);
3269 }
3270 Py_DECREF(ssl_socket);
3271
3272 if (result == NULL) {
3273 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3274 *al = SSL_AD_HANDSHAKE_FAILURE;
3275 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3276 }
3277 else {
3278 if (result != Py_None) {
3279 *al = (int) PyLong_AsLong(result);
3280 if (PyErr_Occurred()) {
3281 PyErr_WriteUnraisable(result);
3282 *al = SSL_AD_INTERNAL_ERROR;
3283 }
3284 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3285 }
3286 else {
3287 ret = SSL_TLSEXT_ERR_OK;
3288 }
3289 Py_DECREF(result);
3290 }
3291
3292#ifdef WITH_THREAD
3293 PyGILState_Release(gstate);
3294#endif
3295 return ret;
3296
3297error:
3298 Py_DECREF(ssl_socket);
3299 *al = SSL_AD_INTERNAL_ERROR;
3300 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3301#ifdef WITH_THREAD
3302 PyGILState_Release(gstate);
3303#endif
3304 return ret;
3305}
3306#endif
3307
3308PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3309"set_servername_callback(method)\n\
3310\n\
3311This sets a callback that will be called when a server name is provided by\n\
3312the SSL/TLS client in the SNI extension.\n\
3313\n\
3314If the argument is None then the callback is disabled. The method is called\n\
3315with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3316See RFC 6066 for details of the SNI extension.");
3317
3318static PyObject *
3319set_servername_callback(PySSLContext *self, PyObject *args)
3320{
3321#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3322 PyObject *cb;
3323
3324 if (!PyArg_ParseTuple(args, "O", &cb))
3325 return NULL;
3326
3327 Py_CLEAR(self->set_hostname);
3328 if (cb == Py_None) {
3329 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3330 }
3331 else {
3332 if (!PyCallable_Check(cb)) {
3333 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3334 PyErr_SetString(PyExc_TypeError,
3335 "not a callable object");
3336 return NULL;
3337 }
3338 Py_INCREF(cb);
3339 self->set_hostname = cb;
3340 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3341 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3342 }
3343 Py_RETURN_NONE;
3344#else
3345 PyErr_SetString(PyExc_NotImplementedError,
3346 "The TLS extension servername callback, "
3347 "SSL_CTX_set_tlsext_servername_callback, "
3348 "is not in the current OpenSSL library.");
3349 return NULL;
3350#endif
3351}
3352
3353PyDoc_STRVAR(PySSL_get_stats_doc,
3354"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3355\n\
3356Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3357CA extension and certificate revocation lists inside the context's cert\n\
3358store.\n\
3359NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3360been used at least once.");
3361
3362static PyObject *
3363cert_store_stats(PySSLContext *self)
3364{
3365 X509_STORE *store;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003366 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003367 X509_OBJECT *obj;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003368 int x509 = 0, crl = 0, ca = 0, i;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003369
3370 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003371 objs = X509_STORE_get0_objects(store);
3372 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3373 obj = sk_X509_OBJECT_value(objs, i);
3374 switch (X509_OBJECT_get_type(obj)) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003375 case X509_LU_X509:
3376 x509++;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003377 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003378 ca++;
3379 }
3380 break;
3381 case X509_LU_CRL:
3382 crl++;
3383 break;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003384 default:
3385 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3386 * As far as I can tell they are internal states and never
3387 * stored in a cert store */
3388 break;
3389 }
3390 }
3391 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3392 "x509_ca", ca);
3393}
3394
3395PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3396"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3397\n\
3398Returns a list of dicts with information of loaded CA certs. If the\n\
3399optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3400NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3401been used at least once.");
3402
3403static PyObject *
3404get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3405{
3406 char *kwlist[] = {"binary_form", NULL};
3407 X509_STORE *store;
3408 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003409 STACK_OF(X509_OBJECT) *objs;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003410 int i;
3411 int binary_mode = 0;
3412
3413 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3414 kwlist, &py_binary_mode)) {
3415 return NULL;
3416 }
3417 binary_mode = PyObject_IsTrue(py_binary_mode);
3418 if (binary_mode < 0) {
3419 return NULL;
3420 }
3421
3422 if ((rlist = PyList_New(0)) == NULL) {
3423 return NULL;
3424 }
3425
3426 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003427 objs = X509_STORE_get0_objects(store);
3428 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003429 X509_OBJECT *obj;
3430 X509 *cert;
3431
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003432 obj = sk_X509_OBJECT_value(objs, i);
3433 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003434 /* not a x509 cert */
3435 continue;
3436 }
3437 /* CA for any purpose */
Christian Heimesc2fc7c42016-09-05 23:37:13 +02003438 cert = X509_OBJECT_get0_X509(obj);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003439 if (!X509_check_ca(cert)) {
3440 continue;
3441 }
3442 if (binary_mode) {
3443 ci = _certificate_to_der(cert);
3444 } else {
3445 ci = _decode_certificate(cert);
3446 }
3447 if (ci == NULL) {
3448 goto error;
3449 }
3450 if (PyList_Append(rlist, ci) == -1) {
3451 goto error;
3452 }
3453 Py_CLEAR(ci);
3454 }
3455 return rlist;
3456
3457 error:
3458 Py_XDECREF(ci);
3459 Py_XDECREF(rlist);
3460 return NULL;
3461}
3462
3463
3464static PyGetSetDef context_getsetlist[] = {
3465 {"check_hostname", (getter) get_check_hostname,
3466 (setter) set_check_hostname, NULL},
3467 {"options", (getter) get_options,
3468 (setter) set_options, NULL},
3469#ifdef HAVE_OPENSSL_VERIFY_PARAM
3470 {"verify_flags", (getter) get_verify_flags,
3471 (setter) set_verify_flags, NULL},
3472#endif
3473 {"verify_mode", (getter) get_verify_mode,
3474 (setter) set_verify_mode, NULL},
3475 {NULL}, /* sentinel */
3476};
3477
3478static struct PyMethodDef context_methods[] = {
3479 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3480 METH_VARARGS | METH_KEYWORDS, NULL},
3481 {"set_ciphers", (PyCFunction) set_ciphers,
3482 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003483 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3484 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003485 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3486 METH_VARARGS, NULL},
3487 {"load_cert_chain", (PyCFunction) load_cert_chain,
3488 METH_VARARGS | METH_KEYWORDS, NULL},
3489 {"load_dh_params", (PyCFunction) load_dh_params,
3490 METH_O, NULL},
3491 {"load_verify_locations", (PyCFunction) load_verify_locations,
3492 METH_VARARGS | METH_KEYWORDS, NULL},
3493 {"session_stats", (PyCFunction) session_stats,
3494 METH_NOARGS, NULL},
3495 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3496 METH_NOARGS, NULL},
3497#ifndef OPENSSL_NO_ECDH
3498 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3499 METH_O, NULL},
3500#endif
3501 {"set_servername_callback", (PyCFunction) set_servername_callback,
3502 METH_VARARGS, PySSL_set_servername_callback_doc},
3503 {"cert_store_stats", (PyCFunction) cert_store_stats,
3504 METH_NOARGS, PySSL_get_stats_doc},
3505 {"get_ca_certs", (PyCFunction) get_ca_certs,
3506 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3507 {NULL, NULL} /* sentinel */
3508};
3509
3510static PyTypeObject PySSLContext_Type = {
3511 PyVarObject_HEAD_INIT(NULL, 0)
3512 "_ssl._SSLContext", /*tp_name*/
3513 sizeof(PySSLContext), /*tp_basicsize*/
3514 0, /*tp_itemsize*/
3515 (destructor)context_dealloc, /*tp_dealloc*/
3516 0, /*tp_print*/
3517 0, /*tp_getattr*/
3518 0, /*tp_setattr*/
3519 0, /*tp_reserved*/
3520 0, /*tp_repr*/
3521 0, /*tp_as_number*/
3522 0, /*tp_as_sequence*/
3523 0, /*tp_as_mapping*/
3524 0, /*tp_hash*/
3525 0, /*tp_call*/
3526 0, /*tp_str*/
3527 0, /*tp_getattro*/
3528 0, /*tp_setattro*/
3529 0, /*tp_as_buffer*/
3530 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3531 0, /*tp_doc*/
3532 (traverseproc) context_traverse, /*tp_traverse*/
3533 (inquiry) context_clear, /*tp_clear*/
3534 0, /*tp_richcompare*/
3535 0, /*tp_weaklistoffset*/
3536 0, /*tp_iter*/
3537 0, /*tp_iternext*/
3538 context_methods, /*tp_methods*/
3539 0, /*tp_members*/
3540 context_getsetlist, /*tp_getset*/
3541 0, /*tp_base*/
3542 0, /*tp_dict*/
3543 0, /*tp_descr_get*/
3544 0, /*tp_descr_set*/
3545 0, /*tp_dictoffset*/
3546 0, /*tp_init*/
3547 0, /*tp_alloc*/
3548 context_new, /*tp_new*/
3549};
3550
3551
3552
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003553#ifdef HAVE_OPENSSL_RAND
3554
3555/* helper routines for seeding the SSL PRNG */
3556static PyObject *
3557PySSL_RAND_add(PyObject *self, PyObject *args)
3558{
3559 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003560 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003561 double entropy;
3562
3563 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003564 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003565 do {
3566 if (len >= INT_MAX) {
3567 written = INT_MAX;
3568 } else {
3569 written = len;
3570 }
3571 RAND_add(buf, (int)written, entropy);
3572 buf += written;
3573 len -= written;
3574 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003575 Py_INCREF(Py_None);
3576 return Py_None;
3577}
3578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003579PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003580"RAND_add(string, entropy)\n\
3581\n\
3582Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003583bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003584
3585static PyObject *
3586PySSL_RAND_status(PyObject *self)
3587{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003588 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003589}
3590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003592"RAND_status() -> 0 or 1\n\
3593\n\
3594Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3595It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003596using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003597
Victor Stinner7c906672015-01-06 13:53:37 +01003598#endif /* HAVE_OPENSSL_RAND */
3599
3600
Benjamin Peterson42e10292016-07-07 00:02:31 -07003601#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003602
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003603static PyObject *
3604PySSL_RAND_egd(PyObject *self, PyObject *arg)
3605{
3606 int bytes;
3607
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003608 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003609 return PyErr_Format(PyExc_TypeError,
3610 "RAND_egd() expected string, found %s",
3611 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003612 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003613 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003614 PyErr_SetString(PySSLErrorObject,
3615 "EGD connection failed or EGD did not return "
3616 "enough data to seed the PRNG");
3617 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003618 }
3619 return PyInt_FromLong(bytes);
3620}
3621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003622PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003623"RAND_egd(path) -> bytes\n\
3624\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003625Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3626Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003627fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003628
Benjamin Peterson42e10292016-07-07 00:02:31 -07003629#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003630
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003631
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003632PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3633"get_default_verify_paths() -> tuple\n\
3634\n\
3635Return search paths and environment vars that are used by SSLContext's\n\
3636set_default_verify_paths() to load default CAs. The values are\n\
3637'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3638
3639static PyObject *
3640PySSL_get_default_verify_paths(PyObject *self)
3641{
3642 PyObject *ofile_env = NULL;
3643 PyObject *ofile = NULL;
3644 PyObject *odir_env = NULL;
3645 PyObject *odir = NULL;
3646
Benjamin Peterson65192c12015-07-18 10:59:13 -07003647#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003648 const char *tmp = (info); \
3649 target = NULL; \
3650 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3651 else { target = PyBytes_FromString(tmp); } \
3652 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003653 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003654
Benjamin Peterson65192c12015-07-18 10:59:13 -07003655 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3656 CONVERT(X509_get_default_cert_file(), ofile);
3657 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3658 CONVERT(X509_get_default_cert_dir(), odir);
3659#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003660
3661 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3662
3663 error:
3664 Py_XDECREF(ofile_env);
3665 Py_XDECREF(ofile);
3666 Py_XDECREF(odir_env);
3667 Py_XDECREF(odir);
3668 return NULL;
3669}
3670
3671static PyObject*
3672asn1obj2py(ASN1_OBJECT *obj)
3673{
3674 int nid;
3675 const char *ln, *sn;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003676
3677 nid = OBJ_obj2nid(obj);
3678 if (nid == NID_undef) {
3679 PyErr_Format(PyExc_ValueError, "Unknown object");
3680 return NULL;
3681 }
3682 sn = OBJ_nid2sn(nid);
3683 ln = OBJ_nid2ln(nid);
Christian Heimesc9d668c2017-09-05 19:13:07 +02003684 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003685}
3686
3687PyDoc_STRVAR(PySSL_txt2obj_doc,
3688"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3689\n\
3690Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3691objects are looked up by OID. With name=True short and long name are also\n\
3692matched.");
3693
3694static PyObject*
3695PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3696{
3697 char *kwlist[] = {"txt", "name", NULL};
3698 PyObject *result = NULL;
3699 char *txt;
3700 PyObject *pyname = Py_None;
3701 int name = 0;
3702 ASN1_OBJECT *obj;
3703
3704 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3705 kwlist, &txt, &pyname)) {
3706 return NULL;
3707 }
3708 name = PyObject_IsTrue(pyname);
3709 if (name < 0)
3710 return NULL;
3711 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3712 if (obj == NULL) {
3713 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3714 return NULL;
3715 }
3716 result = asn1obj2py(obj);
3717 ASN1_OBJECT_free(obj);
3718 return result;
3719}
3720
3721PyDoc_STRVAR(PySSL_nid2obj_doc,
3722"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3723\n\
3724Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3725
3726static PyObject*
3727PySSL_nid2obj(PyObject *self, PyObject *args)
3728{
3729 PyObject *result = NULL;
3730 int nid;
3731 ASN1_OBJECT *obj;
3732
3733 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3734 return NULL;
3735 }
3736 if (nid < NID_undef) {
3737 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3738 return NULL;
3739 }
3740 obj = OBJ_nid2obj(nid);
3741 if (obj == NULL) {
3742 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3743 return NULL;
3744 }
3745 result = asn1obj2py(obj);
3746 ASN1_OBJECT_free(obj);
3747 return result;
3748}
3749
3750#ifdef _MSC_VER
3751
3752static PyObject*
3753certEncodingType(DWORD encodingType)
3754{
3755 static PyObject *x509_asn = NULL;
3756 static PyObject *pkcs_7_asn = NULL;
3757
3758 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003759 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003760 if (x509_asn == NULL)
3761 return NULL;
3762 }
3763 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003764 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003765 if (pkcs_7_asn == NULL)
3766 return NULL;
3767 }
3768 switch(encodingType) {
3769 case X509_ASN_ENCODING:
3770 Py_INCREF(x509_asn);
3771 return x509_asn;
3772 case PKCS_7_ASN_ENCODING:
3773 Py_INCREF(pkcs_7_asn);
3774 return pkcs_7_asn;
3775 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003776 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003777 }
3778}
3779
3780static PyObject*
3781parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3782{
3783 CERT_ENHKEY_USAGE *usage;
3784 DWORD size, error, i;
3785 PyObject *retval;
3786
3787 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3788 error = GetLastError();
3789 if (error == CRYPT_E_NOT_FOUND) {
3790 Py_RETURN_TRUE;
3791 }
3792 return PyErr_SetFromWindowsErr(error);
3793 }
3794
3795 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3796 if (usage == NULL) {
3797 return PyErr_NoMemory();
3798 }
3799
3800 /* Now get the actual enhanced usage property */
3801 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3802 PyMem_Free(usage);
3803 error = GetLastError();
3804 if (error == CRYPT_E_NOT_FOUND) {
3805 Py_RETURN_TRUE;
3806 }
3807 return PyErr_SetFromWindowsErr(error);
3808 }
3809 retval = PySet_New(NULL);
3810 if (retval == NULL) {
3811 goto error;
3812 }
3813 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3814 if (usage->rgpszUsageIdentifier[i]) {
3815 PyObject *oid;
3816 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003817 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003818 if (oid == NULL) {
3819 Py_CLEAR(retval);
3820 goto error;
3821 }
3822 err = PySet_Add(retval, oid);
3823 Py_DECREF(oid);
3824 if (err == -1) {
3825 Py_CLEAR(retval);
3826 goto error;
3827 }
3828 }
3829 }
3830 error:
3831 PyMem_Free(usage);
3832 return retval;
3833}
3834
3835PyDoc_STRVAR(PySSL_enum_certificates_doc,
3836"enum_certificates(store_name) -> []\n\
3837\n\
3838Retrieve certificates from Windows' cert store. store_name may be one of\n\
3839'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3840The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3841encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3842PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3843boolean True.");
3844
3845static PyObject *
3846PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3847{
3848 char *kwlist[] = {"store_name", NULL};
3849 char *store_name;
3850 HCERTSTORE hStore = NULL;
3851 PCCERT_CONTEXT pCertCtx = NULL;
3852 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3853 PyObject *result = NULL;
3854
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003855 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003856 kwlist, &store_name)) {
3857 return NULL;
3858 }
3859 result = PyList_New(0);
3860 if (result == NULL) {
3861 return NULL;
3862 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003863 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3864 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3865 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003866 if (hStore == NULL) {
3867 Py_DECREF(result);
3868 return PyErr_SetFromWindowsErr(GetLastError());
3869 }
3870
3871 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3872 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3873 pCertCtx->cbCertEncoded);
3874 if (!cert) {
3875 Py_CLEAR(result);
3876 break;
3877 }
3878 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3879 Py_CLEAR(result);
3880 break;
3881 }
3882 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3883 if (keyusage == Py_True) {
3884 Py_DECREF(keyusage);
3885 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3886 }
3887 if (keyusage == NULL) {
3888 Py_CLEAR(result);
3889 break;
3890 }
3891 if ((tup = PyTuple_New(3)) == NULL) {
3892 Py_CLEAR(result);
3893 break;
3894 }
3895 PyTuple_SET_ITEM(tup, 0, cert);
3896 cert = NULL;
3897 PyTuple_SET_ITEM(tup, 1, enc);
3898 enc = NULL;
3899 PyTuple_SET_ITEM(tup, 2, keyusage);
3900 keyusage = NULL;
3901 if (PyList_Append(result, tup) < 0) {
3902 Py_CLEAR(result);
3903 break;
3904 }
3905 Py_CLEAR(tup);
3906 }
3907 if (pCertCtx) {
3908 /* loop ended with an error, need to clean up context manually */
3909 CertFreeCertificateContext(pCertCtx);
3910 }
3911
3912 /* In error cases cert, enc and tup may not be NULL */
3913 Py_XDECREF(cert);
3914 Py_XDECREF(enc);
3915 Py_XDECREF(keyusage);
3916 Py_XDECREF(tup);
3917
3918 if (!CertCloseStore(hStore, 0)) {
3919 /* This error case might shadow another exception.*/
3920 Py_XDECREF(result);
3921 return PyErr_SetFromWindowsErr(GetLastError());
3922 }
3923 return result;
3924}
3925
3926PyDoc_STRVAR(PySSL_enum_crls_doc,
3927"enum_crls(store_name) -> []\n\
3928\n\
3929Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3930'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3931The function returns a list of (bytes, encoding_type) tuples. The\n\
3932encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3933PKCS_7_ASN_ENCODING.");
3934
3935static PyObject *
3936PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3937{
3938 char *kwlist[] = {"store_name", NULL};
3939 char *store_name;
3940 HCERTSTORE hStore = NULL;
3941 PCCRL_CONTEXT pCrlCtx = NULL;
3942 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3943 PyObject *result = NULL;
3944
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003945 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003946 kwlist, &store_name)) {
3947 return NULL;
3948 }
3949 result = PyList_New(0);
3950 if (result == NULL) {
3951 return NULL;
3952 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003953 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3954 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3955 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003956 if (hStore == NULL) {
3957 Py_DECREF(result);
3958 return PyErr_SetFromWindowsErr(GetLastError());
3959 }
3960
3961 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3962 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3963 pCrlCtx->cbCrlEncoded);
3964 if (!crl) {
3965 Py_CLEAR(result);
3966 break;
3967 }
3968 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3969 Py_CLEAR(result);
3970 break;
3971 }
3972 if ((tup = PyTuple_New(2)) == NULL) {
3973 Py_CLEAR(result);
3974 break;
3975 }
3976 PyTuple_SET_ITEM(tup, 0, crl);
3977 crl = NULL;
3978 PyTuple_SET_ITEM(tup, 1, enc);
3979 enc = NULL;
3980
3981 if (PyList_Append(result, tup) < 0) {
3982 Py_CLEAR(result);
3983 break;
3984 }
3985 Py_CLEAR(tup);
3986 }
3987 if (pCrlCtx) {
3988 /* loop ended with an error, need to clean up context manually */
3989 CertFreeCRLContext(pCrlCtx);
3990 }
3991
3992 /* In error cases cert, enc and tup may not be NULL */
3993 Py_XDECREF(crl);
3994 Py_XDECREF(enc);
3995 Py_XDECREF(tup);
3996
3997 if (!CertCloseStore(hStore, 0)) {
3998 /* This error case might shadow another exception.*/
3999 Py_XDECREF(result);
4000 return PyErr_SetFromWindowsErr(GetLastError());
4001 }
4002 return result;
4003}
4004
4005#endif /* _MSC_VER */
4006
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004007/* List of functions exported by this module. */
4008
4009static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004010 {"_test_decode_cert", PySSL_test_decode_certificate,
4011 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004012#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004013 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4014 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004015 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4016 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004017#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07004018#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01004019 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
4020 PySSL_RAND_egd_doc},
4021#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004022 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
4023 METH_NOARGS, PySSL_get_default_verify_paths_doc},
4024#ifdef _MSC_VER
4025 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4026 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4027 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4028 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
4029#endif
4030 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4031 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4032 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4033 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004034 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004035};
4036
4037
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004038#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Bill Janssen98d19da2007-09-10 21:51:02 +00004039
4040/* an implementation of OpenSSL threading operations in terms
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004041 * of the Python C thread library
4042 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4043 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004044
4045static PyThread_type_lock *_ssl_locks = NULL;
4046
Christian Heimes10107812013-08-19 17:36:29 +02004047#if OPENSSL_VERSION_NUMBER >= 0x10000000
4048/* use new CRYPTO_THREADID API. */
4049static void
4050_ssl_threadid_callback(CRYPTO_THREADID *id)
4051{
4052 CRYPTO_THREADID_set_numeric(id,
4053 (unsigned long)PyThread_get_thread_ident());
4054}
4055#else
4056/* deprecated CRYPTO_set_id_callback() API. */
4057static unsigned long
4058_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004059 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00004060}
Christian Heimes10107812013-08-19 17:36:29 +02004061#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00004062
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004063static void _ssl_thread_locking_function
4064 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004065 /* this function is needed to perform locking on shared data
4066 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004067 structures that will be implicitly shared whenever multiple
4068 threads use OpenSSL.) Multi-threaded applications will
4069 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00004070
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004071 locking_function() must be able to handle up to
4072 CRYPTO_num_locks() different mutex locks. It sets the n-th
4073 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00004074
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004075 file and line are the file number of the function setting the
4076 lock. They can be useful for debugging.
4077 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004078
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004079 if ((_ssl_locks == NULL) ||
4080 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4081 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00004082
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004083 if (mode & CRYPTO_LOCK) {
4084 PyThread_acquire_lock(_ssl_locks[n], 1);
4085 } else {
4086 PyThread_release_lock(_ssl_locks[n]);
4087 }
Bill Janssen98d19da2007-09-10 21:51:02 +00004088}
4089
4090static int _setup_ssl_threads(void) {
4091
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004092 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00004093
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004094 if (_ssl_locks == NULL) {
4095 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004096 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4097 if (_ssl_locks == NULL) {
4098 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004099 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02004100 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004101 memset(_ssl_locks, 0,
4102 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004103 for (i = 0; i < _ssl_locks_count; i++) {
4104 _ssl_locks[i] = PyThread_allocate_lock();
4105 if (_ssl_locks[i] == NULL) {
4106 unsigned int j;
4107 for (j = 0; j < i; j++) {
4108 PyThread_free_lock(_ssl_locks[j]);
4109 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004110 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004111 return 0;
4112 }
4113 }
4114 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02004115#if OPENSSL_VERSION_NUMBER >= 0x10000000
4116 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4117#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004118 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02004119#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004120 }
4121 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00004122}
4123
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004124#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Bill Janssen98d19da2007-09-10 21:51:02 +00004125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004126PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004127"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004128for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004129
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004130
4131
4132
4133static void
4134parse_openssl_version(unsigned long libver,
4135 unsigned int *major, unsigned int *minor,
4136 unsigned int *fix, unsigned int *patch,
4137 unsigned int *status)
4138{
4139 *status = libver & 0xF;
4140 libver >>= 4;
4141 *patch = libver & 0xFF;
4142 libver >>= 8;
4143 *fix = libver & 0xFF;
4144 libver >>= 8;
4145 *minor = libver & 0xFF;
4146 libver >>= 8;
4147 *major = libver & 0xFF;
4148}
4149
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004150PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004151init_ssl(void)
4152{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004153 PyObject *m, *d, *r;
4154 unsigned long libver;
4155 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004156 struct py_ssl_error_code *errcode;
4157 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004158
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004159 if (PyType_Ready(&PySSLContext_Type) < 0)
4160 return;
4161 if (PyType_Ready(&PySSLSocket_Type) < 0)
4162 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004163
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004164 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
4165 if (m == NULL)
4166 return;
4167 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004168
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004169 /* Load _socket module and its C API */
4170 if (PySocketModule_ImportModuleAndAPI())
4171 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004172
Christian Heimes7daa45d2017-09-05 17:12:12 +02004173#ifndef OPENSSL_VERSION_1_1
4174 /* Load all algorithms and initialize cpuid */
4175 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004176 /* Init OpenSSL */
4177 SSL_load_error_strings();
4178 SSL_library_init();
Christian Heimes7daa45d2017-09-05 17:12:12 +02004179#endif
4180
Bill Janssen98d19da2007-09-10 21:51:02 +00004181#ifdef WITH_THREAD
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004182#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004183 /* note that this will start threading if not already started */
4184 if (!_setup_ssl_threads()) {
4185 return;
4186 }
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004187#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4188 /* OpenSSL 1.1.0 builtin thread support is enabled */
4189 _ssl_locks_count++;
Bill Janssen98d19da2007-09-10 21:51:02 +00004190#endif
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004191#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004192
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004193 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004194 PySSLErrorObject = PyErr_NewExceptionWithDoc(
4195 "ssl.SSLError", SSLError_doc,
4196 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004197 if (PySSLErrorObject == NULL)
4198 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004199 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
4200
4201 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4202 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4203 PySSLErrorObject, NULL);
4204 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4205 "ssl.SSLWantReadError", SSLWantReadError_doc,
4206 PySSLErrorObject, NULL);
4207 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4208 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4209 PySSLErrorObject, NULL);
4210 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4211 "ssl.SSLSyscallError", SSLSyscallError_doc,
4212 PySSLErrorObject, NULL);
4213 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4214 "ssl.SSLEOFError", SSLEOFError_doc,
4215 PySSLErrorObject, NULL);
4216 if (PySSLZeroReturnErrorObject == NULL
4217 || PySSLWantReadErrorObject == NULL
4218 || PySSLWantWriteErrorObject == NULL
4219 || PySSLSyscallErrorObject == NULL
4220 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004221 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004222
4223 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4224 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4225 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4226 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4227 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4228
4229 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4230 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4231 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4232 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4233 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4234 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4235 return;
4236 if (PyDict_SetItemString(d, "_SSLContext",
4237 (PyObject *)&PySSLContext_Type) != 0)
4238 return;
4239 if (PyDict_SetItemString(d, "_SSLSocket",
4240 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004241 return;
4242 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4243 PY_SSL_ERROR_ZERO_RETURN);
4244 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4245 PY_SSL_ERROR_WANT_READ);
4246 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4247 PY_SSL_ERROR_WANT_WRITE);
4248 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4249 PY_SSL_ERROR_WANT_X509_LOOKUP);
4250 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4251 PY_SSL_ERROR_SYSCALL);
4252 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4253 PY_SSL_ERROR_SSL);
4254 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4255 PY_SSL_ERROR_WANT_CONNECT);
4256 /* non ssl.h errorcodes */
4257 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4258 PY_SSL_ERROR_EOF);
4259 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4260 PY_SSL_ERROR_INVALID_ERROR_CODE);
4261 /* cert requirements */
4262 PyModule_AddIntConstant(m, "CERT_NONE",
4263 PY_SSL_CERT_NONE);
4264 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4265 PY_SSL_CERT_OPTIONAL);
4266 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4267 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004268 /* CRL verification for verification_flags */
4269 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4270 0);
4271 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4272 X509_V_FLAG_CRL_CHECK);
4273 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4274 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4275 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4276 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004277#ifdef X509_V_FLAG_TRUSTED_FIRST
4278 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4279 X509_V_FLAG_TRUSTED_FIRST);
4280#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004281
4282 /* Alert Descriptions from ssl.h */
4283 /* note RESERVED constants no longer intended for use have been removed */
4284 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4285
4286#define ADD_AD_CONSTANT(s) \
4287 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4288 SSL_AD_##s)
4289
4290 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4291 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4292 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4293 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4294 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4295 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4296 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4297 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4298 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4299 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4300 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4301 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4302 ADD_AD_CONSTANT(UNKNOWN_CA);
4303 ADD_AD_CONSTANT(ACCESS_DENIED);
4304 ADD_AD_CONSTANT(DECODE_ERROR);
4305 ADD_AD_CONSTANT(DECRYPT_ERROR);
4306 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4307 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4308 ADD_AD_CONSTANT(INTERNAL_ERROR);
4309 ADD_AD_CONSTANT(USER_CANCELLED);
4310 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4311 /* Not all constants are in old OpenSSL versions */
4312#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4313 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4314#endif
4315#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4316 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4317#endif
4318#ifdef SSL_AD_UNRECOGNIZED_NAME
4319 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4320#endif
4321#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4322 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4323#endif
4324#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4325 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4326#endif
4327#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4328 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4329#endif
4330
4331#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004332
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004333 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004334#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004335 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4336 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004337#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004338#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004339 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4340 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004341#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004342 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimesc2fc7c42016-09-05 23:37:13 +02004343 PY_SSL_VERSION_TLS);
4344 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4345 PY_SSL_VERSION_TLS);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004346 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4347 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004348#if HAVE_TLSv1_2
4349 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4350 PY_SSL_VERSION_TLS1_1);
4351 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4352 PY_SSL_VERSION_TLS1_2);
4353#endif
4354
4355 /* protocol options */
4356 PyModule_AddIntConstant(m, "OP_ALL",
4357 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4358 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4359 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4360 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4361#if HAVE_TLSv1_2
4362 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4363 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4364#endif
Christian Heimesb9a860f2017-09-07 22:31:17 -07004365#ifdef SSL_OP_NO_TLSv1_3
4366 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
4367#else
4368 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
4369#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004370 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4371 SSL_OP_CIPHER_SERVER_PREFERENCE);
4372 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4373#ifdef SSL_OP_SINGLE_ECDH_USE
4374 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4375#endif
4376#ifdef SSL_OP_NO_COMPRESSION
4377 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4378 SSL_OP_NO_COMPRESSION);
4379#endif
4380
4381#if HAVE_SNI
4382 r = Py_True;
4383#else
4384 r = Py_False;
4385#endif
4386 Py_INCREF(r);
4387 PyModule_AddObject(m, "HAS_SNI", r);
4388
4389#if HAVE_OPENSSL_FINISHED
4390 r = Py_True;
4391#else
4392 r = Py_False;
4393#endif
4394 Py_INCREF(r);
4395 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4396
4397#ifdef OPENSSL_NO_ECDH
4398 r = Py_False;
4399#else
4400 r = Py_True;
4401#endif
4402 Py_INCREF(r);
4403 PyModule_AddObject(m, "HAS_ECDH", r);
4404
Christian Heimesdf1732a2018-02-25 14:28:55 +01004405#if HAVE_NPN
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004406 r = Py_True;
4407#else
4408 r = Py_False;
4409#endif
4410 Py_INCREF(r);
4411 PyModule_AddObject(m, "HAS_NPN", r);
4412
Christian Heimesdf1732a2018-02-25 14:28:55 +01004413#if HAVE_ALPN
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004414 r = Py_True;
4415#else
4416 r = Py_False;
4417#endif
4418 Py_INCREF(r);
4419 PyModule_AddObject(m, "HAS_ALPN", r);
4420
Christian Heimesb9a860f2017-09-07 22:31:17 -07004421#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
4422 r = Py_True;
4423#else
4424 r = Py_False;
4425#endif
4426 Py_INCREF(r);
4427 PyModule_AddObject(m, "HAS_TLSv1_3", r);
4428
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004429 /* Mappings for error codes */
4430 err_codes_to_names = PyDict_New();
4431 err_names_to_codes = PyDict_New();
4432 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4433 return;
4434 errcode = error_codes;
4435 while (errcode->mnemonic != NULL) {
4436 PyObject *mnemo, *key;
4437 mnemo = PyUnicode_FromString(errcode->mnemonic);
4438 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4439 if (mnemo == NULL || key == NULL)
4440 return;
4441 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4442 return;
4443 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4444 return;
4445 Py_DECREF(key);
4446 Py_DECREF(mnemo);
4447 errcode++;
4448 }
4449 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4450 return;
4451 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4452 return;
4453
4454 lib_codes_to_names = PyDict_New();
4455 if (lib_codes_to_names == NULL)
4456 return;
4457 libcode = library_codes;
4458 while (libcode->library != NULL) {
4459 PyObject *mnemo, *key;
4460 key = PyLong_FromLong(libcode->code);
4461 mnemo = PyUnicode_FromString(libcode->library);
4462 if (key == NULL || mnemo == NULL)
4463 return;
4464 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4465 return;
4466 Py_DECREF(key);
4467 Py_DECREF(mnemo);
4468 libcode++;
4469 }
4470 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4471 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004472
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004473 /* OpenSSL version */
4474 /* SSLeay() gives us the version of the library linked against,
4475 which could be different from the headers version.
4476 */
4477 libver = SSLeay();
4478 r = PyLong_FromUnsignedLong(libver);
4479 if (r == NULL)
4480 return;
4481 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4482 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004483 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004484 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4485 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4486 return;
4487 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4488 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4489 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004490
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004491 libver = OPENSSL_VERSION_NUMBER;
4492 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4493 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4494 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4495 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004496}