blob: b4fac44b62948168e1c6eb69d0704c4167e0d2b3 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +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.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +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
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
Christian Heimes598894f2016-09-05 23:19:05 +020058/* Don't warn about deprecated functions */
59#ifdef __GNUC__
60#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61#endif
62#ifdef __clang__
63#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64#endif
65
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066/* Include OpenSSL header files */
67#include "openssl/rsa.h"
68#include "openssl/crypto.h"
69#include "openssl/x509.h"
70#include "openssl/x509v3.h"
71#include "openssl/pem.h"
72#include "openssl/ssl.h"
73#include "openssl/err.h"
74#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020075#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010076
77/* SSL error object */
78static PyObject *PySSLErrorObject;
79static PyObject *PySSLZeroReturnErrorObject;
80static PyObject *PySSLWantReadErrorObject;
81static PyObject *PySSLWantWriteErrorObject;
82static PyObject *PySSLSyscallErrorObject;
83static PyObject *PySSLEOFErrorObject;
84
85/* Error mappings */
86static PyObject *err_codes_to_names;
87static PyObject *err_names_to_codes;
88static PyObject *lib_codes_to_names;
89
90struct py_ssl_error_code {
91 const char *mnemonic;
92 int library, reason;
93};
94struct py_ssl_library_code {
95 const char *library;
96 int code;
97};
98
99/* Include generated data (error codes) */
100#include "_ssl_data.h"
101
Christian Heimes598894f2016-09-05 23:19:05 +0200102#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
103# define OPENSSL_VERSION_1_1 1
104#endif
105
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100106/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
107 http://www.openssl.org/news/changelog.html
108 */
109#if OPENSSL_VERSION_NUMBER >= 0x10001000L
110# define HAVE_TLSv1_2 1
111#else
112# define HAVE_TLSv1_2 0
113#endif
114
Christian Heimes470fba12013-11-28 15:12:15 +0100115/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100116 * This includes the SSL_set_SSL_CTX() function.
117 */
118#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
119# define HAVE_SNI 1
120#else
121# define HAVE_SNI 0
122#endif
123
Benjamin Petersond3308222015-09-27 00:09:02 -0700124#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500125# define HAVE_ALPN
126#endif
127
Victor Stinner524714e2016-07-22 17:43:59 +0200128#ifndef INVALID_SOCKET /* MS defines this */
129#define INVALID_SOCKET (-1)
130#endif
131
Christian Heimes598894f2016-09-05 23:19:05 +0200132#ifdef OPENSSL_VERSION_1_1
133/* OpenSSL 1.1.0+ */
134#ifndef OPENSSL_NO_SSL2
135#define OPENSSL_NO_SSL2
136#endif
137#else /* OpenSSL < 1.1.0 */
138#if defined(WITH_THREAD)
139#define HAVE_OPENSSL_CRYPTO_LOCK
140#endif
141
142#define TLS_method SSLv23_method
143
144static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
145{
146 return ne->set;
147}
148
149#ifndef OPENSSL_NO_COMP
150static int COMP_get_type(const COMP_METHOD *meth)
151{
152 return meth->type;
153}
Christian Heimes598894f2016-09-05 23:19:05 +0200154#endif
155
156static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
157{
158 return ctx->default_passwd_callback;
159}
160
161static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
162{
163 return ctx->default_passwd_callback_userdata;
164}
165
166static int X509_OBJECT_get_type(X509_OBJECT *x)
167{
168 return x->type;
169}
170
171static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
172{
173 return x->data.x509;
174}
175
176static int BIO_up_ref(BIO *b)
177{
178 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
179 return 1;
180}
181
182static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
183 return store->objs;
184}
185
186static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
187{
188 return store->param;
189}
190#endif /* OpenSSL < 1.1.0 or LibreSSL */
191
192
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000193enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000194 /* these mirror ssl.h */
195 PY_SSL_ERROR_NONE,
196 PY_SSL_ERROR_SSL,
197 PY_SSL_ERROR_WANT_READ,
198 PY_SSL_ERROR_WANT_WRITE,
199 PY_SSL_ERROR_WANT_X509_LOOKUP,
200 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
201 PY_SSL_ERROR_ZERO_RETURN,
202 PY_SSL_ERROR_WANT_CONNECT,
203 /* start of non ssl.h errorcodes */
204 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
205 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
206 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000207};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000208
Thomas Woutersed03b412007-08-28 21:37:11 +0000209enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000210 PY_SSL_CLIENT,
211 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000212};
213
214enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 PY_SSL_CERT_NONE,
216 PY_SSL_CERT_OPTIONAL,
217 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000218};
219
220enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000221 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200222 PY_SSL_VERSION_SSL3=1,
Christian Heimes598894f2016-09-05 23:19:05 +0200223 PY_SSL_VERSION_TLS,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100224#if HAVE_TLSv1_2
225 PY_SSL_VERSION_TLS1,
226 PY_SSL_VERSION_TLS1_1,
227 PY_SSL_VERSION_TLS1_2
228#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000230#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100231};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200232
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000233#ifdef WITH_THREAD
234
235/* serves as a flag to see whether we've initialized the SSL thread support. */
236/* 0 means no, greater than 0 means yes */
237
238static unsigned int _ssl_locks_count = 0;
239
240#endif /* def WITH_THREAD */
241
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000242/* SSL socket object */
243
244#define X509_NAME_MAXLEN 256
245
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000246/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
247 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
248 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
249#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000250# define HAVE_SSL_CTX_CLEAR_OPTIONS
251#else
252# undef HAVE_SSL_CTX_CLEAR_OPTIONS
253#endif
254
Antoine Pitroud6494802011-07-21 01:11:30 +0200255/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
256 * older SSL, but let's be safe */
257#define PySSL_CB_MAXLEN 128
258
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100259
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000260typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000261 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000262 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100263#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500264 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100265 int npn_protocols_len;
266#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500267#ifdef HAVE_ALPN
268 unsigned char *alpn_protocols;
269 int alpn_protocols_len;
270#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100271#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200272 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100273#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100274 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000275} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000276
Antoine Pitrou152efa22010-05-16 18:19:27 +0000277typedef struct {
278 PyObject_HEAD
279 PyObject *Socket; /* weakref to socket on which we're layered */
280 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100281 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200283 char shutdown_seen_zero;
284 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200285 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200286 PyObject *owner; /* Python level "owner" passed to servername callback */
287 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000289
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200290typedef struct {
291 PyObject_HEAD
292 BIO *bio;
293 int eof_written;
294} PySSLMemoryBIO;
295
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296static PyTypeObject PySSLContext_Type;
297static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200298static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300300/*[clinic input]
301module _ssl
302class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
303class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
304class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
305[clinic start generated code]*/
306/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
307
308#include "clinic/_ssl.c.h"
309
Victor Stinner14690702015-04-06 22:46:13 +0200310static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
313#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200314#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000316typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000317 SOCKET_IS_NONBLOCKING,
318 SOCKET_IS_BLOCKING,
319 SOCKET_HAS_TIMED_OUT,
320 SOCKET_HAS_BEEN_CLOSED,
321 SOCKET_TOO_LARGE_FOR_SELECT,
322 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000323} timeout_state;
324
Thomas Woutersed03b412007-08-28 21:37:11 +0000325/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000326#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200327#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000328
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200329/* Get the socket from a PySSLSocket, if it has one */
330#define GET_SOCKET(obj) ((obj)->Socket ? \
331 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200332
Victor Stinner14690702015-04-06 22:46:13 +0200333/* If sock is NULL, use a timeout of 0 second */
334#define GET_SOCKET_TIMEOUT(sock) \
335 ((sock != NULL) ? (sock)->sock_timeout : 0)
336
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200337/*
338 * SSL errors.
339 */
340
341PyDoc_STRVAR(SSLError_doc,
342"An error occurred in the SSL implementation.");
343
344PyDoc_STRVAR(SSLZeroReturnError_doc,
345"SSL/TLS session closed cleanly.");
346
347PyDoc_STRVAR(SSLWantReadError_doc,
348"Non-blocking SSL socket needs to read more data\n"
349"before the requested operation can be completed.");
350
351PyDoc_STRVAR(SSLWantWriteError_doc,
352"Non-blocking SSL socket needs to write more data\n"
353"before the requested operation can be completed.");
354
355PyDoc_STRVAR(SSLSyscallError_doc,
356"System error when attempting SSL operation.");
357
358PyDoc_STRVAR(SSLEOFError_doc,
359"SSL/TLS connection terminated abruptly.");
360
361static PyObject *
362SSLError_str(PyOSErrorObject *self)
363{
364 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
365 Py_INCREF(self->strerror);
366 return self->strerror;
367 }
368 else
369 return PyObject_Str(self->args);
370}
371
372static PyType_Slot sslerror_type_slots[] = {
373 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
374 {Py_tp_doc, SSLError_doc},
375 {Py_tp_str, SSLError_str},
376 {0, 0},
377};
378
379static PyType_Spec sslerror_type_spec = {
380 "ssl.SSLError",
381 sizeof(PyOSErrorObject),
382 0,
383 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
384 sslerror_type_slots
385};
386
387static void
388fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
389 int lineno, unsigned long errcode)
390{
391 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
392 PyObject *init_value, *msg, *key;
393 _Py_IDENTIFIER(reason);
394 _Py_IDENTIFIER(library);
395
396 if (errcode != 0) {
397 int lib, reason;
398
399 lib = ERR_GET_LIB(errcode);
400 reason = ERR_GET_REASON(errcode);
401 key = Py_BuildValue("ii", lib, reason);
402 if (key == NULL)
403 goto fail;
404 reason_obj = PyDict_GetItem(err_codes_to_names, key);
405 Py_DECREF(key);
406 if (reason_obj == NULL) {
407 /* XXX if reason < 100, it might reflect a library number (!!) */
408 PyErr_Clear();
409 }
410 key = PyLong_FromLong(lib);
411 if (key == NULL)
412 goto fail;
413 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
414 Py_DECREF(key);
415 if (lib_obj == NULL) {
416 PyErr_Clear();
417 }
418 if (errstr == NULL)
419 errstr = ERR_reason_error_string(errcode);
420 }
421 if (errstr == NULL)
422 errstr = "unknown error";
423
424 if (reason_obj && lib_obj)
425 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
426 lib_obj, reason_obj, errstr, lineno);
427 else if (lib_obj)
428 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
429 lib_obj, errstr, lineno);
430 else
431 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 if (msg == NULL)
433 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100434
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200435 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100436 if (init_value == NULL)
437 goto fail;
438
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439 err_value = PyObject_CallObject(type, init_value);
440 Py_DECREF(init_value);
441 if (err_value == NULL)
442 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100443
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200444 if (reason_obj == NULL)
445 reason_obj = Py_None;
446 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
447 goto fail;
448 if (lib_obj == NULL)
449 lib_obj = Py_None;
450 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
451 goto fail;
452 PyErr_SetObject(type, err_value);
453fail:
454 Py_XDECREF(err_value);
455}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000456
457static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200458PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200460 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200461 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000462 int err;
463 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 if (obj->ssl != NULL) {
470 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000472 switch (err) {
473 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200474 errstr = "TLS/SSL connection has been closed (EOF)";
475 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 p = PY_SSL_ERROR_ZERO_RETURN;
477 break;
478 case SSL_ERROR_WANT_READ:
479 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200480 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 p = PY_SSL_ERROR_WANT_READ;
482 break;
483 case SSL_ERROR_WANT_WRITE:
484 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200485 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 errstr = "The operation did not complete (write)";
487 break;
488 case SSL_ERROR_WANT_X509_LOOKUP:
489 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000490 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 break;
492 case SSL_ERROR_WANT_CONNECT:
493 p = PY_SSL_ERROR_WANT_CONNECT;
494 errstr = "The operation did not complete (connect)";
495 break;
496 case SSL_ERROR_SYSCALL:
497 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200499 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000501 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200502 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000503 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200504 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000505 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000506 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000507 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200508 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000509 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200510 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000512 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200513 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000514 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000515 }
516 } else {
517 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 }
519 break;
520 }
521 case SSL_ERROR_SSL:
522 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200524 if (e == 0)
525 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000526 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 break;
528 }
529 default:
530 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
531 errstr = "Invalid error code";
532 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200534 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000535 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000536 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000537}
538
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200540_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200542 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200544 else
545 errcode = 0;
546 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000547 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549}
550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551/*
552 * SSL objects
553 */
554
Antoine Pitrou152efa22010-05-16 18:19:27 +0000555static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100556newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000557 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200558 char *server_hostname,
559 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000560{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000561 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100562 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200563 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564
Antoine Pitrou152efa22010-05-16 18:19:27 +0000565 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 if (self == NULL)
567 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 self->peer_cert = NULL;
570 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100572 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200573 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200574 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200575 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700576 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200577 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700578 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
579 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200580 if (hostname == NULL) {
581 Py_DECREF(self);
582 return NULL;
583 }
584 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700585 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200586
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100587 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000588
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 /* Make sure the SSL error state is initialized */
590 (void) ERR_get_state();
591 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000594 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 SSL_set_app_data(self->ssl, self);
597 if (sock) {
598 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
599 } else {
600 /* BIOs are reference counted and SSL_set_bio borrows our reference.
601 * To prevent a double free in memory_bio_dealloc() we need to take an
602 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200603 BIO_up_ref(inbio->bio);
604 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200605 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
606 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200607 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000608#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200609 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000610#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200611 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000612
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100613#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000614 if (server_hostname != NULL)
615 SSL_set_tlsext_host_name(self->ssl, server_hostname);
616#endif
617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 /* If the socket is in non-blocking mode or timeout mode, set the BIO
619 * to non-blocking mode (blocking is the default)
620 */
Victor Stinnere2452312015-03-28 03:00:46 +0100621 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
623 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
624 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 PySSL_BEGIN_ALLOW_THREADS
627 if (socket_type == PY_SSL_CLIENT)
628 SSL_set_connect_state(self->ssl);
629 else
630 SSL_set_accept_state(self->ssl);
631 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000632
Antoine Pitroud6494802011-07-21 01:11:30 +0200633 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200634 if (sock != NULL) {
635 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
636 if (self->Socket == NULL) {
637 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200638 return NULL;
639 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100640 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000642}
643
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000644/* SSL object methods */
645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300646/*[clinic input]
647_ssl._SSLSocket.do_handshake
648[clinic start generated code]*/
649
650static PyObject *
651_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
652/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000653{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 int ret;
655 int err;
656 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200657 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200658 _PyTime_t timeout, deadline = 0;
659 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000660
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 if (sock) {
662 if (((PyObject*)sock) == Py_None) {
663 _setSSLError("Underlying socket connection gone",
664 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
665 return NULL;
666 }
667 Py_INCREF(sock);
668
669 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100670 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200671 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
672 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000674
Victor Stinner14690702015-04-06 22:46:13 +0200675 timeout = GET_SOCKET_TIMEOUT(sock);
676 has_timeout = (timeout > 0);
677 if (has_timeout)
678 deadline = _PyTime_GetMonotonicClock() + timeout;
679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 /* Actually negotiate SSL connection */
681 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000683 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 ret = SSL_do_handshake(self->ssl);
685 err = SSL_get_error(self->ssl, ret);
686 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200687
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000688 if (PyErr_CheckSignals())
689 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200690
Victor Stinner14690702015-04-06 22:46:13 +0200691 if (has_timeout)
692 timeout = deadline - _PyTime_GetMonotonicClock();
693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200695 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200697 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 } else {
699 sockstate = SOCKET_OPERATION_OK;
700 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000703 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000704 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000705 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
707 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000708 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000709 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
711 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000712 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000713 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
715 break;
716 }
717 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200718 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 if (ret < 1)
720 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 if (self->peer_cert)
723 X509_free (self->peer_cert);
724 PySSL_BEGIN_ALLOW_THREADS
725 self->peer_cert = SSL_get_peer_certificate(self->ssl);
726 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200727 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728
729 Py_INCREF(Py_None);
730 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000731
732error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200733 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000734 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000735}
736
Thomas Woutersed03b412007-08-28 21:37:11 +0000737static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 char namebuf[X509_NAME_MAXLEN];
741 int buflen;
742 PyObject *name_obj;
743 PyObject *value_obj;
744 PyObject *attr;
745 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
748 if (buflen < 0) {
749 _setSSLError(NULL, 0, __FILE__, __LINE__);
750 goto fail;
751 }
752 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
753 if (name_obj == NULL)
754 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
757 if (buflen < 0) {
758 _setSSLError(NULL, 0, __FILE__, __LINE__);
759 Py_DECREF(name_obj);
760 goto fail;
761 }
762 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000763 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 OPENSSL_free(valuebuf);
765 if (value_obj == NULL) {
766 Py_DECREF(name_obj);
767 goto fail;
768 }
769 attr = PyTuple_New(2);
770 if (attr == NULL) {
771 Py_DECREF(name_obj);
772 Py_DECREF(value_obj);
773 goto fail;
774 }
775 PyTuple_SET_ITEM(attr, 0, name_obj);
776 PyTuple_SET_ITEM(attr, 1, value_obj);
777 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000778
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000781}
782
783static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000785{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
787 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
788 PyObject *rdnt;
789 PyObject *attr = NULL; /* tuple to hold an attribute */
790 int entry_count = X509_NAME_entry_count(xname);
791 X509_NAME_ENTRY *entry;
792 ASN1_OBJECT *name;
793 ASN1_STRING *value;
794 int index_counter;
795 int rdn_level = -1;
796 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 dn = PyList_New(0);
799 if (dn == NULL)
800 return NULL;
801 /* now create another tuple to hold the top-level RDN */
802 rdn = PyList_New(0);
803 if (rdn == NULL)
804 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 for (index_counter = 0;
807 index_counter < entry_count;
808 index_counter++)
809 {
810 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 /* check to see if we've gotten to a new RDN */
813 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200814 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 /* yes, new RDN */
816 /* add old RDN to DN */
817 rdnt = PyList_AsTuple(rdn);
818 Py_DECREF(rdn);
819 if (rdnt == NULL)
820 goto fail0;
821 retcode = PyList_Append(dn, rdnt);
822 Py_DECREF(rdnt);
823 if (retcode < 0)
824 goto fail0;
825 /* create new RDN */
826 rdn = PyList_New(0);
827 if (rdn == NULL)
828 goto fail0;
829 }
830 }
Christian Heimes598894f2016-09-05 23:19:05 +0200831 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 /* now add this attribute to the current RDN */
834 name = X509_NAME_ENTRY_get_object(entry);
835 value = X509_NAME_ENTRY_get_data(entry);
836 attr = _create_tuple_for_attribute(name, value);
837 /*
838 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
839 entry->set,
840 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
841 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
842 */
843 if (attr == NULL)
844 goto fail1;
845 retcode = PyList_Append(rdn, attr);
846 Py_DECREF(attr);
847 if (retcode < 0)
848 goto fail1;
849 }
850 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100851 if (rdn != NULL) {
852 if (PyList_GET_SIZE(rdn) > 0) {
853 rdnt = PyList_AsTuple(rdn);
854 Py_DECREF(rdn);
855 if (rdnt == NULL)
856 goto fail0;
857 retcode = PyList_Append(dn, rdnt);
858 Py_DECREF(rdnt);
859 if (retcode < 0)
860 goto fail0;
861 }
862 else {
863 Py_DECREF(rdn);
864 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 /* convert list to tuple */
868 rdnt = PyList_AsTuple(dn);
869 Py_DECREF(dn);
870 if (rdnt == NULL)
871 return NULL;
872 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873
874 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
877 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 Py_XDECREF(dn);
879 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880}
881
882static PyObject *
883_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 /* this code follows the procedure outlined in
886 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
887 function to extract the STACK_OF(GENERAL_NAME),
888 then iterates through the stack to add the
889 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 int i, j;
892 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200893 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 X509_EXTENSION *ext = NULL;
895 GENERAL_NAMES *names = NULL;
896 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000897 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 BIO *biobuf = NULL;
899 char buf[2048];
900 char *vptr;
901 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 if (certificate == NULL)
905 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 /* get a memory buffer */
908 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200910 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 while ((i = X509_get_ext_by_NID(
912 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 if (peer_alt_names == Py_None) {
915 peer_alt_names = PyList_New(0);
916 if (peer_alt_names == NULL)
917 goto fail;
918 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 /* now decode the altName */
921 ext = X509_get_ext(certificate, i);
922 if(!(method = X509V3_EXT_get(ext))) {
923 PyErr_SetString
924 (PySSLErrorObject,
925 ERRSTR("No method for internalizing subjectAltName!"));
926 goto fail;
927 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Christian Heimes598894f2016-09-05 23:19:05 +0200929 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (method->it)
931 names = (GENERAL_NAMES*)
932 (ASN1_item_d2i(NULL,
933 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200934 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 ASN1_ITEM_ptr(method->it)));
936 else
937 names = (GENERAL_NAMES*)
938 (method->d2i(NULL,
939 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200940 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200944 int gntype;
945 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200948 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200949 switch (gntype) {
950 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 /* we special-case DirName as a tuple of
952 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 t = PyTuple_New(2);
955 if (t == NULL) {
956 goto fail;
957 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 v = PyUnicode_FromString("DirName");
960 if (v == NULL) {
961 Py_DECREF(t);
962 goto fail;
963 }
964 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 v = _create_tuple_for_X509_NAME (name->d.dirn);
967 if (v == NULL) {
968 Py_DECREF(t);
969 goto fail;
970 }
971 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200972 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Christian Heimes824f7f32013-08-17 00:54:47 +0200974 case GEN_EMAIL:
975 case GEN_DNS:
976 case GEN_URI:
977 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
978 correctly, CVE-2013-4238 */
979 t = PyTuple_New(2);
980 if (t == NULL)
981 goto fail;
982 switch (gntype) {
983 case GEN_EMAIL:
984 v = PyUnicode_FromString("email");
985 as = name->d.rfc822Name;
986 break;
987 case GEN_DNS:
988 v = PyUnicode_FromString("DNS");
989 as = name->d.dNSName;
990 break;
991 case GEN_URI:
992 v = PyUnicode_FromString("URI");
993 as = name->d.uniformResourceIdentifier;
994 break;
995 }
996 if (v == NULL) {
997 Py_DECREF(t);
998 goto fail;
999 }
1000 PyTuple_SET_ITEM(t, 0, v);
1001 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1002 ASN1_STRING_length(as));
1003 if (v == NULL) {
1004 Py_DECREF(t);
1005 goto fail;
1006 }
1007 PyTuple_SET_ITEM(t, 1, v);
1008 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Christian Heimes1c03abd2016-09-06 23:25:35 +02001010 case GEN_RID:
1011 t = PyTuple_New(2);
1012 if (t == NULL)
1013 goto fail;
1014
1015 v = PyUnicode_FromString("Registered ID");
1016 if (v == NULL) {
1017 Py_DECREF(t);
1018 goto fail;
1019 }
1020 PyTuple_SET_ITEM(t, 0, v);
1021
1022 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1023 if (len < 0) {
1024 Py_DECREF(t);
1025 _setSSLError(NULL, 0, __FILE__, __LINE__);
1026 goto fail;
1027 } else if (len >= (int)sizeof(buf)) {
1028 v = PyUnicode_FromString("<INVALID>");
1029 } else {
1030 v = PyUnicode_FromStringAndSize(buf, len);
1031 }
1032 if (v == NULL) {
1033 Py_DECREF(t);
1034 goto fail;
1035 }
1036 PyTuple_SET_ITEM(t, 1, v);
1037 break;
1038
Christian Heimes824f7f32013-08-17 00:54:47 +02001039 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001041 switch (gntype) {
1042 /* check for new general name type */
1043 case GEN_OTHERNAME:
1044 case GEN_X400:
1045 case GEN_EDIPARTY:
1046 case GEN_IPADD:
1047 case GEN_RID:
1048 break;
1049 default:
1050 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1051 "Unknown general name type %d",
1052 gntype) == -1) {
1053 goto fail;
1054 }
1055 break;
1056 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 (void) BIO_reset(biobuf);
1058 GENERAL_NAME_print(biobuf, name);
1059 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1060 if (len < 0) {
1061 _setSSLError(NULL, 0, __FILE__, __LINE__);
1062 goto fail;
1063 }
1064 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001065 if (vptr == NULL) {
1066 PyErr_Format(PyExc_ValueError,
1067 "Invalid value %.200s",
1068 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001070 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 t = PyTuple_New(2);
1072 if (t == NULL)
1073 goto fail;
1074 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1075 if (v == NULL) {
1076 Py_DECREF(t);
1077 goto fail;
1078 }
1079 PyTuple_SET_ITEM(t, 0, v);
1080 v = PyUnicode_FromStringAndSize((vptr + 1),
1081 (len - (vptr - buf + 1)));
1082 if (v == NULL) {
1083 Py_DECREF(t);
1084 goto fail;
1085 }
1086 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001087 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 if (PyList_Append(peer_alt_names, t) < 0) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 Py_DECREF(t);
1097 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001098 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 }
1100 BIO_free(biobuf);
1101 if (peer_alt_names != Py_None) {
1102 v = PyList_AsTuple(peer_alt_names);
1103 Py_DECREF(peer_alt_names);
1104 return v;
1105 } else {
1106 return peer_alt_names;
1107 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001108
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
1110 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 if (biobuf != NULL)
1112 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 if (peer_alt_names != Py_None) {
1115 Py_XDECREF(peer_alt_names);
1116 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119}
1120
1121static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001122_get_aia_uri(X509 *certificate, int nid) {
1123 PyObject *lst = NULL, *ostr = NULL;
1124 int i, result;
1125 AUTHORITY_INFO_ACCESS *info;
1126
1127 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001128 if (info == NULL)
1129 return Py_None;
1130 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1131 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001132 return Py_None;
1133 }
1134
1135 if ((lst = PyList_New(0)) == NULL) {
1136 goto fail;
1137 }
1138
1139 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1140 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1141 ASN1_IA5STRING *uri;
1142
1143 if ((OBJ_obj2nid(ad->method) != nid) ||
1144 (ad->location->type != GEN_URI)) {
1145 continue;
1146 }
1147 uri = ad->location->d.uniformResourceIdentifier;
1148 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1149 uri->length);
1150 if (ostr == NULL) {
1151 goto fail;
1152 }
1153 result = PyList_Append(lst, ostr);
1154 Py_DECREF(ostr);
1155 if (result < 0) {
1156 goto fail;
1157 }
1158 }
1159 AUTHORITY_INFO_ACCESS_free(info);
1160
1161 /* convert to tuple or None */
1162 if (PyList_Size(lst) == 0) {
1163 Py_DECREF(lst);
1164 return Py_None;
1165 } else {
1166 PyObject *tup;
1167 tup = PyList_AsTuple(lst);
1168 Py_DECREF(lst);
1169 return tup;
1170 }
1171
1172 fail:
1173 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001174 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001175 return NULL;
1176}
1177
1178static PyObject *
1179_get_crl_dp(X509 *certificate) {
1180 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001181 int i, j;
1182 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001183
Christian Heimes598894f2016-09-05 23:19:05 +02001184#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001185 /* Calls x509v3_cache_extensions and sets up crldp */
1186 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001187#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001188 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001189
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001190 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001191 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001192
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001193 lst = PyList_New(0);
1194 if (lst == NULL)
1195 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001196
1197 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1198 DIST_POINT *dp;
1199 STACK_OF(GENERAL_NAME) *gns;
1200
1201 dp = sk_DIST_POINT_value(dps, i);
1202 gns = dp->distpoint->name.fullname;
1203
1204 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1205 GENERAL_NAME *gn;
1206 ASN1_IA5STRING *uri;
1207 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001208 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001209
1210 gn = sk_GENERAL_NAME_value(gns, j);
1211 if (gn->type != GEN_URI) {
1212 continue;
1213 }
1214 uri = gn->d.uniformResourceIdentifier;
1215 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1216 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001217 if (ouri == NULL)
1218 goto done;
1219
1220 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001221 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001222 if (err < 0)
1223 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001224 }
1225 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001226
1227 /* Convert to tuple. */
1228 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1229
1230 done:
1231 Py_XDECREF(lst);
1232#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001233 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001234#endif
1235 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001236}
1237
1238static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001239_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 PyObject *retval = NULL;
1242 BIO *biobuf = NULL;
1243 PyObject *peer;
1244 PyObject *peer_alt_names = NULL;
1245 PyObject *issuer;
1246 PyObject *version;
1247 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001248 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 ASN1_INTEGER *serialNumber;
1250 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001251 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 ASN1_TIME *notBefore, *notAfter;
1253 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 retval = PyDict_New();
1256 if (retval == NULL)
1257 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 peer = _create_tuple_for_X509_NAME(
1260 X509_get_subject_name(certificate));
1261 if (peer == NULL)
1262 goto fail0;
1263 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1264 Py_DECREF(peer);
1265 goto fail0;
1266 }
1267 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001268
Antoine Pitroufb046912010-11-09 20:21:19 +00001269 issuer = _create_tuple_for_X509_NAME(
1270 X509_get_issuer_name(certificate));
1271 if (issuer == NULL)
1272 goto fail0;
1273 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001275 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001277 Py_DECREF(issuer);
1278
1279 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001280 if (version == NULL)
1281 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001282 if (PyDict_SetItemString(retval, "version", version) < 0) {
1283 Py_DECREF(version);
1284 goto fail0;
1285 }
1286 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 /* get a memory buffer */
1289 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001290
Antoine Pitroufb046912010-11-09 20:21:19 +00001291 (void) BIO_reset(biobuf);
1292 serialNumber = X509_get_serialNumber(certificate);
1293 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1294 i2a_ASN1_INTEGER(biobuf, serialNumber);
1295 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1296 if (len < 0) {
1297 _setSSLError(NULL, 0, __FILE__, __LINE__);
1298 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001300 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1301 if (sn_obj == NULL)
1302 goto fail1;
1303 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1304 Py_DECREF(sn_obj);
1305 goto fail1;
1306 }
1307 Py_DECREF(sn_obj);
1308
1309 (void) BIO_reset(biobuf);
1310 notBefore = X509_get_notBefore(certificate);
1311 ASN1_TIME_print(biobuf, notBefore);
1312 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1313 if (len < 0) {
1314 _setSSLError(NULL, 0, __FILE__, __LINE__);
1315 goto fail1;
1316 }
1317 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1318 if (pnotBefore == NULL)
1319 goto fail1;
1320 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1321 Py_DECREF(pnotBefore);
1322 goto fail1;
1323 }
1324 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 (void) BIO_reset(biobuf);
1327 notAfter = X509_get_notAfter(certificate);
1328 ASN1_TIME_print(biobuf, notAfter);
1329 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1330 if (len < 0) {
1331 _setSSLError(NULL, 0, __FILE__, __LINE__);
1332 goto fail1;
1333 }
1334 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1335 if (pnotAfter == NULL)
1336 goto fail1;
1337 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1338 Py_DECREF(pnotAfter);
1339 goto fail1;
1340 }
1341 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 peer_alt_names = _get_peer_alt_names(certificate);
1346 if (peer_alt_names == NULL)
1347 goto fail1;
1348 else if (peer_alt_names != Py_None) {
1349 if (PyDict_SetItemString(retval, "subjectAltName",
1350 peer_alt_names) < 0) {
1351 Py_DECREF(peer_alt_names);
1352 goto fail1;
1353 }
1354 Py_DECREF(peer_alt_names);
1355 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001356
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001357 /* Authority Information Access: OCSP URIs */
1358 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1359 if (obj == NULL) {
1360 goto fail1;
1361 } else if (obj != Py_None) {
1362 result = PyDict_SetItemString(retval, "OCSP", obj);
1363 Py_DECREF(obj);
1364 if (result < 0) {
1365 goto fail1;
1366 }
1367 }
1368
1369 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1370 if (obj == NULL) {
1371 goto fail1;
1372 } else if (obj != Py_None) {
1373 result = PyDict_SetItemString(retval, "caIssuers", obj);
1374 Py_DECREF(obj);
1375 if (result < 0) {
1376 goto fail1;
1377 }
1378 }
1379
1380 /* CDP (CRL distribution points) */
1381 obj = _get_crl_dp(certificate);
1382 if (obj == NULL) {
1383 goto fail1;
1384 } else if (obj != Py_None) {
1385 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1386 Py_DECREF(obj);
1387 if (result < 0) {
1388 goto fail1;
1389 }
1390 }
1391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 BIO_free(biobuf);
1393 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001394
1395 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 if (biobuf != NULL)
1397 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001398 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 Py_XDECREF(retval);
1400 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001401}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001402
Christian Heimes9a5395a2013-06-17 15:44:12 +02001403static PyObject *
1404_certificate_to_der(X509 *certificate)
1405{
1406 unsigned char *bytes_buf = NULL;
1407 int len;
1408 PyObject *retval;
1409
1410 bytes_buf = NULL;
1411 len = i2d_X509(certificate, &bytes_buf);
1412 if (len < 0) {
1413 _setSSLError(NULL, 0, __FILE__, __LINE__);
1414 return NULL;
1415 }
1416 /* this is actually an immutable bytes sequence */
1417 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1418 OPENSSL_free(bytes_buf);
1419 return retval;
1420}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001422/*[clinic input]
1423_ssl._test_decode_cert
1424 path: object(converter="PyUnicode_FSConverter")
1425 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001427[clinic start generated code]*/
1428
1429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001430_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1431/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001432{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 X509 *x=NULL;
1435 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1438 PyErr_SetString(PySSLErrorObject,
1439 "Can't malloc memory to read file");
1440 goto fail0;
1441 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001443 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 PyErr_SetString(PySSLErrorObject,
1445 "Can't open file");
1446 goto fail0;
1447 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1450 if (x == NULL) {
1451 PyErr_SetString(PySSLErrorObject,
1452 "Error decoding PEM-encoded file");
1453 goto fail0;
1454 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001455
Antoine Pitroufb046912010-11-09 20:21:19 +00001456 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001457 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001458
1459 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001460 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 if (cert != NULL) BIO_free(cert);
1462 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463}
1464
1465
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001466/*[clinic input]
1467_ssl._SSLSocket.peer_certificate
1468 der as binary_mode: bool = False
1469 /
1470
1471Returns the certificate for the peer.
1472
1473If no certificate was provided, returns None. If a certificate was
1474provided, but not validated, returns an empty dictionary. Otherwise
1475returns a dict containing information about the peer certificate.
1476
1477If the optional argument is True, returns a DER-encoded copy of the
1478peer certificate, or None if no certificate was provided. This will
1479return the certificate even if it wasn't validated.
1480[clinic start generated code]*/
1481
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001483_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1484/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487
Antoine Pitrou20b85552013-09-29 19:50:53 +02001488 if (!self->handshake_done) {
1489 PyErr_SetString(PyExc_ValueError,
1490 "handshake not done yet");
1491 return NULL;
1492 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 if (!self->peer_cert)
1494 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001495
Antoine Pitrou721738f2012-08-15 23:20:39 +02001496 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001498 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001500 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 if ((verification & SSL_VERIFY_PEER) == 0)
1502 return PyDict_New();
1503 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001504 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506}
1507
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001508static PyObject *
1509cipher_to_tuple(const SSL_CIPHER *cipher)
1510{
1511 const char *cipher_name, *cipher_protocol;
1512 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 if (retval == NULL)
1514 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001516 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001518 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 PyTuple_SET_ITEM(retval, 0, Py_None);
1520 } else {
1521 v = PyUnicode_FromString(cipher_name);
1522 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001523 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 PyTuple_SET_ITEM(retval, 0, v);
1525 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001526
1527 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001529 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 PyTuple_SET_ITEM(retval, 1, Py_None);
1531 } else {
1532 v = PyUnicode_FromString(cipher_protocol);
1533 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001534 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 PyTuple_SET_ITEM(retval, 1, v);
1536 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001537
1538 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001540 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001544
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001545 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 Py_DECREF(retval);
1547 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548}
1549
Christian Heimes25bfcd52016-09-06 00:04:45 +02001550#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1551static PyObject *
1552cipher_to_dict(const SSL_CIPHER *cipher)
1553{
1554 const char *cipher_name, *cipher_protocol;
1555
1556 unsigned long cipher_id;
1557 int alg_bits, strength_bits, len;
1558 char buf[512] = {0};
1559#if OPENSSL_VERSION_1_1
1560 int aead, nid;
1561 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1562#endif
1563 PyObject *retval;
1564
1565 retval = PyDict_New();
1566 if (retval == NULL) {
1567 goto error;
1568 }
1569
1570 /* can be NULL */
1571 cipher_name = SSL_CIPHER_get_name(cipher);
1572 cipher_protocol = SSL_CIPHER_get_version(cipher);
1573 cipher_id = SSL_CIPHER_get_id(cipher);
1574 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1575 len = strlen(buf);
1576 if (len > 1 && buf[len-1] == '\n')
1577 buf[len-1] = '\0';
1578 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1579
1580#if OPENSSL_VERSION_1_1
1581 aead = SSL_CIPHER_is_aead(cipher);
1582 nid = SSL_CIPHER_get_cipher_nid(cipher);
1583 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1584 nid = SSL_CIPHER_get_digest_nid(cipher);
1585 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1586 nid = SSL_CIPHER_get_kx_nid(cipher);
1587 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1588 nid = SSL_CIPHER_get_auth_nid(cipher);
1589 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1590#endif
1591
1592 retval = Py_BuildValue(
1593 "{sksssssssisi"
1594#if OPENSSL_VERSION_1_1
1595 "sOssssssss"
1596#endif
1597 "}",
1598 "id", cipher_id,
1599 "name", cipher_name,
1600 "protocol", cipher_protocol,
1601 "description", buf,
1602 "strength_bits", strength_bits,
1603 "alg_bits", alg_bits
1604#if OPENSSL_VERSION_1_1
1605 ,"aead", aead ? Py_True : Py_False,
1606 "symmetric", skcipher,
1607 "digest", digest,
1608 "kea", kx,
1609 "auth", auth
1610#endif
1611 );
1612 return retval;
1613
1614 error:
1615 Py_XDECREF(retval);
1616 return NULL;
1617}
1618#endif
1619
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001620/*[clinic input]
1621_ssl._SSLSocket.shared_ciphers
1622[clinic start generated code]*/
1623
1624static PyObject *
1625_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1626/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001627{
1628 STACK_OF(SSL_CIPHER) *ciphers;
1629 int i;
1630 PyObject *res;
1631
Christian Heimes598894f2016-09-05 23:19:05 +02001632 ciphers = SSL_get_ciphers(self->ssl);
1633 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001634 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001635 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1636 if (!res)
1637 return NULL;
1638 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1639 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1640 if (!tup) {
1641 Py_DECREF(res);
1642 return NULL;
1643 }
1644 PyList_SET_ITEM(res, i, tup);
1645 }
1646 return res;
1647}
1648
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001649/*[clinic input]
1650_ssl._SSLSocket.cipher
1651[clinic start generated code]*/
1652
1653static PyObject *
1654_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1655/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001656{
1657 const SSL_CIPHER *current;
1658
1659 if (self->ssl == NULL)
1660 Py_RETURN_NONE;
1661 current = SSL_get_current_cipher(self->ssl);
1662 if (current == NULL)
1663 Py_RETURN_NONE;
1664 return cipher_to_tuple(current);
1665}
1666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001667/*[clinic input]
1668_ssl._SSLSocket.version
1669[clinic start generated code]*/
1670
1671static PyObject *
1672_ssl__SSLSocket_version_impl(PySSLSocket *self)
1673/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001674{
1675 const char *version;
1676
1677 if (self->ssl == NULL)
1678 Py_RETURN_NONE;
1679 version = SSL_get_version(self->ssl);
1680 if (!strcmp(version, "unknown"))
1681 Py_RETURN_NONE;
1682 return PyUnicode_FromString(version);
1683}
1684
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001685#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001686/*[clinic input]
1687_ssl._SSLSocket.selected_npn_protocol
1688[clinic start generated code]*/
1689
1690static PyObject *
1691_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1692/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1693{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001694 const unsigned char *out;
1695 unsigned int outlen;
1696
Victor Stinner4569cd52013-06-23 14:58:43 +02001697 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001698 &out, &outlen);
1699
1700 if (out == NULL)
1701 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001702 return PyUnicode_FromStringAndSize((char *)out, outlen);
1703}
1704#endif
1705
1706#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001707/*[clinic input]
1708_ssl._SSLSocket.selected_alpn_protocol
1709[clinic start generated code]*/
1710
1711static PyObject *
1712_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1713/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1714{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001715 const unsigned char *out;
1716 unsigned int outlen;
1717
1718 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1719
1720 if (out == NULL)
1721 Py_RETURN_NONE;
1722 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001723}
1724#endif
1725
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001726/*[clinic input]
1727_ssl._SSLSocket.compression
1728[clinic start generated code]*/
1729
1730static PyObject *
1731_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1732/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1733{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001734#ifdef OPENSSL_NO_COMP
1735 Py_RETURN_NONE;
1736#else
1737 const COMP_METHOD *comp_method;
1738 const char *short_name;
1739
1740 if (self->ssl == NULL)
1741 Py_RETURN_NONE;
1742 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001743 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001744 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001745 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001746 if (short_name == NULL)
1747 Py_RETURN_NONE;
1748 return PyUnicode_DecodeFSDefault(short_name);
1749#endif
1750}
1751
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001752static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1753 Py_INCREF(self->ctx);
1754 return self->ctx;
1755}
1756
1757static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1758 void *closure) {
1759
1760 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001761#if !HAVE_SNI
1762 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1763 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001764 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001765#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001766 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001767 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001768 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001769#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001770 } else {
1771 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1772 return -1;
1773 }
1774
1775 return 0;
1776}
1777
1778PyDoc_STRVAR(PySSL_set_context_doc,
1779"_setter_context(ctx)\n\
1780\
1781This changes the context associated with the SSLSocket. This is typically\n\
1782used from within a callback function set by the set_servername_callback\n\
1783on the SSLContext to change the certificate information associated with the\n\
1784SSLSocket before the cryptographic exchange handshake messages\n");
1785
1786
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001787static PyObject *
1788PySSL_get_server_side(PySSLSocket *self, void *c)
1789{
1790 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1791}
1792
1793PyDoc_STRVAR(PySSL_get_server_side_doc,
1794"Whether this is a server-side socket.");
1795
1796static PyObject *
1797PySSL_get_server_hostname(PySSLSocket *self, void *c)
1798{
1799 if (self->server_hostname == NULL)
1800 Py_RETURN_NONE;
1801 Py_INCREF(self->server_hostname);
1802 return self->server_hostname;
1803}
1804
1805PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1806"The currently set server hostname (for SNI).");
1807
1808static PyObject *
1809PySSL_get_owner(PySSLSocket *self, void *c)
1810{
1811 PyObject *owner;
1812
1813 if (self->owner == NULL)
1814 Py_RETURN_NONE;
1815
1816 owner = PyWeakref_GetObject(self->owner);
1817 Py_INCREF(owner);
1818 return owner;
1819}
1820
1821static int
1822PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1823{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001824 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001825 if (self->owner == NULL)
1826 return -1;
1827 return 0;
1828}
1829
1830PyDoc_STRVAR(PySSL_get_owner_doc,
1831"The Python-level owner of this object.\
1832Passed as \"self\" in servername callback.");
1833
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001834
Antoine Pitrou152efa22010-05-16 18:19:27 +00001835static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001836{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 if (self->peer_cert) /* Possible not to have one? */
1838 X509_free (self->peer_cert);
1839 if (self->ssl)
1840 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001842 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001843 Py_XDECREF(self->server_hostname);
1844 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001846}
1847
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001848/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001849 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001850 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001851 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001852
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001853static int
Victor Stinner14690702015-04-06 22:46:13 +02001854PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001855{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001856 int rc;
1857#ifdef HAVE_POLL
1858 struct pollfd pollfd;
1859 _PyTime_t ms;
1860#else
1861 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 fd_set fds;
1863 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001864#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001867 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001869 else if (timeout < 0) {
1870 if (s->sock_timeout > 0)
1871 return SOCKET_HAS_TIMED_OUT;
1872 else
1873 return SOCKET_IS_BLOCKING;
1874 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001877 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 /* Prefer poll, if available, since you can poll() any fd
1881 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001882#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001883 pollfd.fd = s->sock_fd;
1884 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001885
Victor Stinner14690702015-04-06 22:46:13 +02001886 /* timeout is in seconds, poll() uses milliseconds */
1887 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001888 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001889
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001890 PySSL_BEGIN_ALLOW_THREADS
1891 rc = poll(&pollfd, 1, (int)ms);
1892 PySSL_END_ALLOW_THREADS
1893#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001895 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001897
Victor Stinner14690702015-04-06 22:46:13 +02001898 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 FD_ZERO(&fds);
1901 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001902
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001903 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001905 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001907 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001909 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001910 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001911#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1914 (when we are able to write or when there's something to read) */
1915 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001916}
1917
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001918/*[clinic input]
1919_ssl._SSLSocket.write
1920 b: Py_buffer
1921 /
1922
1923Writes the bytes-like object b into the SSL object.
1924
1925Returns the number of bytes written.
1926[clinic start generated code]*/
1927
1928static PyObject *
1929_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1930/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001931{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 int len;
1933 int sockstate;
1934 int err;
1935 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001936 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001937 _PyTime_t timeout, deadline = 0;
1938 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001939
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001940 if (sock != NULL) {
1941 if (((PyObject*)sock) == Py_None) {
1942 _setSSLError("Underlying socket connection gone",
1943 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1944 return NULL;
1945 }
1946 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 }
1948
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001949 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001950 PyErr_Format(PyExc_OverflowError,
1951 "string longer than %d bytes", INT_MAX);
1952 goto error;
1953 }
1954
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001955 if (sock != NULL) {
1956 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001957 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001958 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1959 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1960 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961
Victor Stinner14690702015-04-06 22:46:13 +02001962 timeout = GET_SOCKET_TIMEOUT(sock);
1963 has_timeout = (timeout > 0);
1964 if (has_timeout)
1965 deadline = _PyTime_GetMonotonicClock() + timeout;
1966
1967 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001969 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 "The write operation timed out");
1971 goto error;
1972 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1973 PyErr_SetString(PySSLErrorObject,
1974 "Underlying socket has been closed.");
1975 goto error;
1976 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1977 PyErr_SetString(PySSLErrorObject,
1978 "Underlying socket too large for select().");
1979 goto error;
1980 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001984 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 err = SSL_get_error(self->ssl, len);
1986 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001987
1988 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001990
Victor Stinner14690702015-04-06 22:46:13 +02001991 if (has_timeout)
1992 timeout = deadline - _PyTime_GetMonotonicClock();
1993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001995 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001997 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001998 } else {
1999 sockstate = SOCKET_OPERATION_OK;
2000 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002002 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002003 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002004 "The write operation timed out");
2005 goto error;
2006 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2007 PyErr_SetString(PySSLErrorObject,
2008 "Underlying socket has been closed.");
2009 goto error;
2010 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2011 break;
2012 }
2013 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002014
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002015 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 if (len > 0)
2017 return PyLong_FromLong(len);
2018 else
2019 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002020
2021error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002022 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002023 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002024}
2025
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002026/*[clinic input]
2027_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029Returns the number of already decrypted bytes available for read, pending on the connection.
2030[clinic start generated code]*/
2031
2032static PyObject *
2033_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2034/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002035{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002037
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002038 PySSL_BEGIN_ALLOW_THREADS
2039 count = SSL_pending(self->ssl);
2040 PySSL_END_ALLOW_THREADS
2041 if (count < 0)
2042 return PySSL_SetError(self, count, __FILE__, __LINE__);
2043 else
2044 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002045}
2046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002047/*[clinic input]
2048_ssl._SSLSocket.read
2049 size as len: int
2050 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002051 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002052 ]
2053 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002054
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002055Read up to size bytes from the SSL socket.
2056[clinic start generated code]*/
2057
2058static PyObject *
2059_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2060 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002061/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002062{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002063 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 int sockstate;
2067 int err;
2068 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002069 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002070 _PyTime_t timeout, deadline = 0;
2071 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002072
Martin Panter5503d472016-03-27 05:35:19 +00002073 if (!group_right_1 && len < 0) {
2074 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2075 return NULL;
2076 }
2077
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002078 if (sock != NULL) {
2079 if (((PyObject*)sock) == Py_None) {
2080 _setSSLError("Underlying socket connection gone",
2081 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2082 return NULL;
2083 }
2084 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002085 }
2086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002087 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002088 dest = PyBytes_FromStringAndSize(NULL, len);
2089 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002090 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002091 if (len == 0) {
2092 Py_XDECREF(sock);
2093 return dest;
2094 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002095 mem = PyBytes_AS_STRING(dest);
2096 }
2097 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002098 mem = buffer->buf;
2099 if (len <= 0 || len > buffer->len) {
2100 len = (int) buffer->len;
2101 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002102 PyErr_SetString(PyExc_OverflowError,
2103 "maximum length can't fit in a C 'int'");
2104 goto error;
2105 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002106 if (len == 0) {
2107 count = 0;
2108 goto done;
2109 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002110 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 }
2112
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002113 if (sock != NULL) {
2114 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002115 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002116 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2117 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2118 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119
Victor Stinner14690702015-04-06 22:46:13 +02002120 timeout = GET_SOCKET_TIMEOUT(sock);
2121 has_timeout = (timeout > 0);
2122 if (has_timeout)
2123 deadline = _PyTime_GetMonotonicClock() + timeout;
2124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002126 PySSL_BEGIN_ALLOW_THREADS
2127 count = SSL_read(self->ssl, mem, len);
2128 err = SSL_get_error(self->ssl, count);
2129 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002131 if (PyErr_CheckSignals())
2132 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002133
Victor Stinner14690702015-04-06 22:46:13 +02002134 if (has_timeout)
2135 timeout = deadline - _PyTime_GetMonotonicClock();
2136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002138 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002140 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002141 } else if (err == SSL_ERROR_ZERO_RETURN &&
2142 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 {
2144 count = 0;
2145 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147 else
2148 sockstate = SOCKET_OPERATION_OK;
2149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002150 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002151 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002152 "The read operation timed out");
2153 goto error;
2154 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2155 break;
2156 }
2157 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 if (count <= 0) {
2160 PySSL_SetError(self, count, __FILE__, __LINE__);
2161 goto error;
2162 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002163
2164done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002165 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002166 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002167 _PyBytes_Resize(&dest, count);
2168 return dest;
2169 }
2170 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 return PyLong_FromLong(count);
2172 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002173
2174error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002175 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002176 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002177 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002179}
2180
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002181/*[clinic input]
2182_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002184Does the SSL shutdown handshake with the remote end.
2185
2186Returns the underlying socket object.
2187[clinic start generated code]*/
2188
2189static PyObject *
2190_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2191/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002192{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 int err, ssl_err, sockstate, nonblocking;
2194 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002195 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002196 _PyTime_t timeout, deadline = 0;
2197 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002198
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002199 if (sock != NULL) {
2200 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002201 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002202 _setSSLError("Underlying socket connection gone",
2203 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2204 return NULL;
2205 }
2206 Py_INCREF(sock);
2207
2208 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002209 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002210 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2211 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213
Victor Stinner14690702015-04-06 22:46:13 +02002214 timeout = GET_SOCKET_TIMEOUT(sock);
2215 has_timeout = (timeout > 0);
2216 if (has_timeout)
2217 deadline = _PyTime_GetMonotonicClock() + timeout;
2218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 while (1) {
2220 PySSL_BEGIN_ALLOW_THREADS
2221 /* Disable read-ahead so that unwrap can work correctly.
2222 * Otherwise OpenSSL might read in too much data,
2223 * eating clear text data that happens to be
2224 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002225 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 * function is used and the shutdown_seen_zero != 0
2227 * condition is met.
2228 */
2229 if (self->shutdown_seen_zero)
2230 SSL_set_read_ahead(self->ssl, 0);
2231 err = SSL_shutdown(self->ssl);
2232 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002233
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2235 if (err > 0)
2236 break;
2237 if (err == 0) {
2238 /* Don't loop endlessly; instead preserve legacy
2239 behaviour of trying SSL_shutdown() only twice.
2240 This looks necessary for OpenSSL < 0.9.8m */
2241 if (++zeros > 1)
2242 break;
2243 /* Shutdown was sent, now try receiving */
2244 self->shutdown_seen_zero = 1;
2245 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002246 }
2247
Victor Stinner14690702015-04-06 22:46:13 +02002248 if (has_timeout)
2249 timeout = deadline - _PyTime_GetMonotonicClock();
2250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 /* Possibly retry shutdown until timeout or failure */
2252 ssl_err = SSL_get_error(self->ssl, err);
2253 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002254 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002256 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 else
2258 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2261 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002262 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 "The read operation timed out");
2264 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002265 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002267 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 }
2269 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2270 PyErr_SetString(PySSLErrorObject,
2271 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002272 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 }
2274 else if (sockstate != SOCKET_OPERATION_OK)
2275 /* Retain the SSL error code */
2276 break;
2277 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002278
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002279 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002280 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002283 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002284 /* It's already INCREF'ed */
2285 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002286 else
2287 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002288
2289error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002290 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002291 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002292}
2293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002294/*[clinic input]
2295_ssl._SSLSocket.tls_unique_cb
2296
2297Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2298
2299If the TLS handshake is not yet complete, None is returned.
2300[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002301
Antoine Pitroud6494802011-07-21 01:11:30 +02002302static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002303_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2304/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002305{
2306 PyObject *retval = NULL;
2307 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002308 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002309
2310 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2311 /* if session is resumed XOR we are the client */
2312 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2313 }
2314 else {
2315 /* if a new session XOR we are the server */
2316 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2317 }
2318
2319 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002320 if (len == 0)
2321 Py_RETURN_NONE;
2322
2323 retval = PyBytes_FromStringAndSize(buf, len);
2324
2325 return retval;
2326}
2327
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002328static PyGetSetDef ssl_getsetlist[] = {
2329 {"context", (getter) PySSL_get_context,
2330 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002331 {"server_side", (getter) PySSL_get_server_side, NULL,
2332 PySSL_get_server_side_doc},
2333 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2334 PySSL_get_server_hostname_doc},
2335 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2336 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002337 {NULL}, /* sentinel */
2338};
2339
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002340static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002341 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2342 _SSL__SSLSOCKET_WRITE_METHODDEF
2343 _SSL__SSLSOCKET_READ_METHODDEF
2344 _SSL__SSLSOCKET_PENDING_METHODDEF
2345 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2346 _SSL__SSLSOCKET_CIPHER_METHODDEF
2347 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2348 _SSL__SSLSOCKET_VERSION_METHODDEF
2349 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2350 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2351 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2352 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2353 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002355};
2356
Antoine Pitrou152efa22010-05-16 18:19:27 +00002357static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002359 "_ssl._SSLSocket", /*tp_name*/
2360 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 0, /*tp_itemsize*/
2362 /* methods */
2363 (destructor)PySSL_dealloc, /*tp_dealloc*/
2364 0, /*tp_print*/
2365 0, /*tp_getattr*/
2366 0, /*tp_setattr*/
2367 0, /*tp_reserved*/
2368 0, /*tp_repr*/
2369 0, /*tp_as_number*/
2370 0, /*tp_as_sequence*/
2371 0, /*tp_as_mapping*/
2372 0, /*tp_hash*/
2373 0, /*tp_call*/
2374 0, /*tp_str*/
2375 0, /*tp_getattro*/
2376 0, /*tp_setattro*/
2377 0, /*tp_as_buffer*/
2378 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2379 0, /*tp_doc*/
2380 0, /*tp_traverse*/
2381 0, /*tp_clear*/
2382 0, /*tp_richcompare*/
2383 0, /*tp_weaklistoffset*/
2384 0, /*tp_iter*/
2385 0, /*tp_iternext*/
2386 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002387 0, /*tp_members*/
2388 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002389};
2390
Antoine Pitrou152efa22010-05-16 18:19:27 +00002391
2392/*
2393 * _SSLContext objects
2394 */
2395
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002396/*[clinic input]
2397@classmethod
2398_ssl._SSLContext.__new__
2399 protocol as proto_version: int
2400 /
2401[clinic start generated code]*/
2402
Antoine Pitrou152efa22010-05-16 18:19:27 +00002403static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002404_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2405/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002406{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002407 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002408 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002409 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002410#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002411 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002412#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002413
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414 PySSL_BEGIN_ALLOW_THREADS
2415 if (proto_version == PY_SSL_VERSION_TLS1)
2416 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002417#if HAVE_TLSv1_2
2418 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2419 ctx = SSL_CTX_new(TLSv1_1_method());
2420 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2421 ctx = SSL_CTX_new(TLSv1_2_method());
2422#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002423#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002424 else if (proto_version == PY_SSL_VERSION_SSL3)
2425 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002426#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002427#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002428 else if (proto_version == PY_SSL_VERSION_SSL2)
2429 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002430#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002431 else if (proto_version == PY_SSL_VERSION_TLS)
2432 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002433 else
2434 proto_version = -1;
2435 PySSL_END_ALLOW_THREADS
2436
2437 if (proto_version == -1) {
2438 PyErr_SetString(PyExc_ValueError,
2439 "invalid protocol version");
2440 return NULL;
2441 }
2442 if (ctx == NULL) {
2443 PyErr_SetString(PySSLErrorObject,
2444 "failed to allocate SSL context");
2445 return NULL;
2446 }
2447
2448 assert(type != NULL && type->tp_alloc != NULL);
2449 self = (PySSLContext *) type->tp_alloc(type, 0);
2450 if (self == NULL) {
2451 SSL_CTX_free(ctx);
2452 return NULL;
2453 }
2454 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002455#ifdef OPENSSL_NPN_NEGOTIATED
2456 self->npn_protocols = NULL;
2457#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002458#ifdef HAVE_ALPN
2459 self->alpn_protocols = NULL;
2460#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002461#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002462 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002463#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002464 /* Don't check host name by default */
2465 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002466 /* Defaults */
2467 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002468 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2469 if (proto_version != PY_SSL_VERSION_SSL2)
2470 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002471 if (proto_version != PY_SSL_VERSION_SSL3)
2472 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002473 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002474
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002475#if defined(SSL_MODE_RELEASE_BUFFERS)
2476 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2477 usage for no cost at all. However, don't do this for OpenSSL versions
2478 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2479 2014-0198. I can't find exactly which beta fixed this CVE, so be
2480 conservative and assume it wasn't fixed until release. We do this check
2481 at runtime to avoid problems from the dynamic linker.
2482 See #25672 for more on this. */
2483 libver = SSLeay();
2484 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2485 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2486 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2487 }
2488#endif
2489
2490
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002491#ifndef OPENSSL_NO_ECDH
2492 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2493 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002494 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2495 */
2496#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002497 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2498#else
2499 {
2500 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2501 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2502 EC_KEY_free(key);
2503 }
2504#endif
2505#endif
2506
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002507#define SID_CTX "Python"
2508 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2509 sizeof(SID_CTX));
2510#undef SID_CTX
2511
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002512#ifdef X509_V_FLAG_TRUSTED_FIRST
2513 {
2514 /* Improve trust chain building when cross-signed intermediate
2515 certificates are present. See https://bugs.python.org/issue23476. */
2516 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2517 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2518 }
2519#endif
2520
Antoine Pitrou152efa22010-05-16 18:19:27 +00002521 return (PyObject *)self;
2522}
2523
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524static int
2525context_traverse(PySSLContext *self, visitproc visit, void *arg)
2526{
2527#ifndef OPENSSL_NO_TLSEXT
2528 Py_VISIT(self->set_hostname);
2529#endif
2530 return 0;
2531}
2532
2533static int
2534context_clear(PySSLContext *self)
2535{
2536#ifndef OPENSSL_NO_TLSEXT
2537 Py_CLEAR(self->set_hostname);
2538#endif
2539 return 0;
2540}
2541
Antoine Pitrou152efa22010-05-16 18:19:27 +00002542static void
2543context_dealloc(PySSLContext *self)
2544{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002545 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002546 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002547#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002548 PyMem_FREE(self->npn_protocols);
2549#endif
2550#ifdef HAVE_ALPN
2551 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002552#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002553 Py_TYPE(self)->tp_free(self);
2554}
2555
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002556/*[clinic input]
2557_ssl._SSLContext.set_ciphers
2558 cipherlist: str
2559 /
2560[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002561
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002562static PyObject *
2563_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2564/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2565{
2566 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002567 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002568 /* Clearing the error queue is necessary on some OpenSSL versions,
2569 otherwise the error will be reported again when another SSL call
2570 is done. */
2571 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002572 PyErr_SetString(PySSLErrorObject,
2573 "No cipher can be selected.");
2574 return NULL;
2575 }
2576 Py_RETURN_NONE;
2577}
2578
Christian Heimes25bfcd52016-09-06 00:04:45 +02002579#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2580/*[clinic input]
2581_ssl._SSLContext.get_ciphers
2582[clinic start generated code]*/
2583
2584static PyObject *
2585_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2586/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2587{
2588 SSL *ssl = NULL;
2589 STACK_OF(SSL_CIPHER) *sk = NULL;
2590 SSL_CIPHER *cipher;
2591 int i=0;
2592 PyObject *result = NULL, *dct;
2593
2594 ssl = SSL_new(self->ctx);
2595 if (ssl == NULL) {
2596 _setSSLError(NULL, 0, __FILE__, __LINE__);
2597 goto exit;
2598 }
2599 sk = SSL_get_ciphers(ssl);
2600
2601 result = PyList_New(sk_SSL_CIPHER_num(sk));
2602 if (result == NULL) {
2603 goto exit;
2604 }
2605
2606 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2607 cipher = sk_SSL_CIPHER_value(sk, i);
2608 dct = cipher_to_dict(cipher);
2609 if (dct == NULL) {
2610 Py_CLEAR(result);
2611 goto exit;
2612 }
2613 PyList_SET_ITEM(result, i, dct);
2614 }
2615
2616 exit:
2617 if (ssl != NULL)
2618 SSL_free(ssl);
2619 return result;
2620
2621}
2622#endif
2623
2624
Benjamin Petersonc54de472015-01-28 12:06:39 -05002625#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002626static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002627do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2628 const unsigned char *server_protocols, unsigned int server_protocols_len,
2629 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002630{
Benjamin Peterson88615022015-01-23 17:30:26 -05002631 int ret;
2632 if (client_protocols == NULL) {
2633 client_protocols = (unsigned char *)"";
2634 client_protocols_len = 0;
2635 }
2636 if (server_protocols == NULL) {
2637 server_protocols = (unsigned char *)"";
2638 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002639 }
2640
Benjamin Peterson88615022015-01-23 17:30:26 -05002641 ret = SSL_select_next_proto(out, outlen,
2642 server_protocols, server_protocols_len,
2643 client_protocols, client_protocols_len);
2644 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2645 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002646
2647 return SSL_TLSEXT_ERR_OK;
2648}
2649
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002650/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2651static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002652_advertiseNPN_cb(SSL *s,
2653 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002654 void *args)
2655{
2656 PySSLContext *ssl_ctx = (PySSLContext *) args;
2657
2658 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002659 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002660 *len = 0;
2661 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002662 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002663 *len = ssl_ctx->npn_protocols_len;
2664 }
2665
2666 return SSL_TLSEXT_ERR_OK;
2667}
2668/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2669static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002670_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002671 unsigned char **out, unsigned char *outlen,
2672 const unsigned char *server, unsigned int server_len,
2673 void *args)
2674{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002675 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002676 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002677 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002678}
2679#endif
2680
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002681/*[clinic input]
2682_ssl._SSLContext._set_npn_protocols
2683 protos: Py_buffer
2684 /
2685[clinic start generated code]*/
2686
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002687static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002688_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2689 Py_buffer *protos)
2690/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002691{
2692#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002693 PyMem_Free(self->npn_protocols);
2694 self->npn_protocols = PyMem_Malloc(protos->len);
2695 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002696 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002697 memcpy(self->npn_protocols, protos->buf, protos->len);
2698 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002699
2700 /* set both server and client callbacks, because the context can
2701 * be used to create both types of sockets */
2702 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2703 _advertiseNPN_cb,
2704 self);
2705 SSL_CTX_set_next_proto_select_cb(self->ctx,
2706 _selectNPN_cb,
2707 self);
2708
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002709 Py_RETURN_NONE;
2710#else
2711 PyErr_SetString(PyExc_NotImplementedError,
2712 "The NPN extension requires OpenSSL 1.0.1 or later.");
2713 return NULL;
2714#endif
2715}
2716
Benjamin Petersoncca27322015-01-23 16:35:37 -05002717#ifdef HAVE_ALPN
2718static int
2719_selectALPN_cb(SSL *s,
2720 const unsigned char **out, unsigned char *outlen,
2721 const unsigned char *client_protocols, unsigned int client_protocols_len,
2722 void *args)
2723{
2724 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002725 return do_protocol_selection(1, (unsigned char **)out, outlen,
2726 ctx->alpn_protocols, ctx->alpn_protocols_len,
2727 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002728}
2729#endif
2730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002731/*[clinic input]
2732_ssl._SSLContext._set_alpn_protocols
2733 protos: Py_buffer
2734 /
2735[clinic start generated code]*/
2736
Benjamin Petersoncca27322015-01-23 16:35:37 -05002737static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002738_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2739 Py_buffer *protos)
2740/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002741{
2742#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002743 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002744 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002745 if (!self->alpn_protocols)
2746 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002747 memcpy(self->alpn_protocols, protos->buf, protos->len);
2748 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002749
2750 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2751 return PyErr_NoMemory();
2752 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2753
Benjamin Petersoncca27322015-01-23 16:35:37 -05002754 Py_RETURN_NONE;
2755#else
2756 PyErr_SetString(PyExc_NotImplementedError,
2757 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2758 return NULL;
2759#endif
2760}
2761
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762static PyObject *
2763get_verify_mode(PySSLContext *self, void *c)
2764{
2765 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2766 case SSL_VERIFY_NONE:
2767 return PyLong_FromLong(PY_SSL_CERT_NONE);
2768 case SSL_VERIFY_PEER:
2769 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2770 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2771 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2772 }
2773 PyErr_SetString(PySSLErrorObject,
2774 "invalid return value from SSL_CTX_get_verify_mode");
2775 return NULL;
2776}
2777
2778static int
2779set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2780{
2781 int n, mode;
2782 if (!PyArg_Parse(arg, "i", &n))
2783 return -1;
2784 if (n == PY_SSL_CERT_NONE)
2785 mode = SSL_VERIFY_NONE;
2786 else if (n == PY_SSL_CERT_OPTIONAL)
2787 mode = SSL_VERIFY_PEER;
2788 else if (n == PY_SSL_CERT_REQUIRED)
2789 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2790 else {
2791 PyErr_SetString(PyExc_ValueError,
2792 "invalid value for verify_mode");
2793 return -1;
2794 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002795 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2796 PyErr_SetString(PyExc_ValueError,
2797 "Cannot set verify_mode to CERT_NONE when "
2798 "check_hostname is enabled.");
2799 return -1;
2800 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 SSL_CTX_set_verify(self->ctx, mode, NULL);
2802 return 0;
2803}
2804
2805static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002806get_verify_flags(PySSLContext *self, void *c)
2807{
2808 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002809 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002810 unsigned long flags;
2811
2812 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002813 param = X509_STORE_get0_param(store);
2814 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002815 return PyLong_FromUnsignedLong(flags);
2816}
2817
2818static int
2819set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2820{
2821 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002822 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002823 unsigned long new_flags, flags, set, clear;
2824
2825 if (!PyArg_Parse(arg, "k", &new_flags))
2826 return -1;
2827 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002828 param = X509_STORE_get0_param(store);
2829 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002830 clear = flags & ~new_flags;
2831 set = ~flags & new_flags;
2832 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02002833 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01002834 _setSSLError(NULL, 0, __FILE__, __LINE__);
2835 return -1;
2836 }
2837 }
2838 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02002839 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01002840 _setSSLError(NULL, 0, __FILE__, __LINE__);
2841 return -1;
2842 }
2843 }
2844 return 0;
2845}
2846
2847static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002848get_options(PySSLContext *self, void *c)
2849{
2850 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2851}
2852
2853static int
2854set_options(PySSLContext *self, PyObject *arg, void *c)
2855{
2856 long new_opts, opts, set, clear;
2857 if (!PyArg_Parse(arg, "l", &new_opts))
2858 return -1;
2859 opts = SSL_CTX_get_options(self->ctx);
2860 clear = opts & ~new_opts;
2861 set = ~opts & new_opts;
2862 if (clear) {
2863#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2864 SSL_CTX_clear_options(self->ctx, clear);
2865#else
2866 PyErr_SetString(PyExc_ValueError,
2867 "can't clear options before OpenSSL 0.9.8m");
2868 return -1;
2869#endif
2870 }
2871 if (set)
2872 SSL_CTX_set_options(self->ctx, set);
2873 return 0;
2874}
2875
Christian Heimes1aa9a752013-12-02 02:41:19 +01002876static PyObject *
2877get_check_hostname(PySSLContext *self, void *c)
2878{
2879 return PyBool_FromLong(self->check_hostname);
2880}
2881
2882static int
2883set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2884{
2885 int check_hostname;
2886 if (!PyArg_Parse(arg, "p", &check_hostname))
2887 return -1;
2888 if (check_hostname &&
2889 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2890 PyErr_SetString(PyExc_ValueError,
2891 "check_hostname needs a SSL context with either "
2892 "CERT_OPTIONAL or CERT_REQUIRED");
2893 return -1;
2894 }
2895 self->check_hostname = check_hostname;
2896 return 0;
2897}
2898
2899
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002900typedef struct {
2901 PyThreadState *thread_state;
2902 PyObject *callable;
2903 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002904 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002905 int error;
2906} _PySSLPasswordInfo;
2907
2908static int
2909_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2910 const char *bad_type_error)
2911{
2912 /* Set the password and size fields of a _PySSLPasswordInfo struct
2913 from a unicode, bytes, or byte array object.
2914 The password field will be dynamically allocated and must be freed
2915 by the caller */
2916 PyObject *password_bytes = NULL;
2917 const char *data = NULL;
2918 Py_ssize_t size;
2919
2920 if (PyUnicode_Check(password)) {
2921 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2922 if (!password_bytes) {
2923 goto error;
2924 }
2925 data = PyBytes_AS_STRING(password_bytes);
2926 size = PyBytes_GET_SIZE(password_bytes);
2927 } else if (PyBytes_Check(password)) {
2928 data = PyBytes_AS_STRING(password);
2929 size = PyBytes_GET_SIZE(password);
2930 } else if (PyByteArray_Check(password)) {
2931 data = PyByteArray_AS_STRING(password);
2932 size = PyByteArray_GET_SIZE(password);
2933 } else {
2934 PyErr_SetString(PyExc_TypeError, bad_type_error);
2935 goto error;
2936 }
2937
Victor Stinner9ee02032013-06-23 15:08:23 +02002938 if (size > (Py_ssize_t)INT_MAX) {
2939 PyErr_Format(PyExc_ValueError,
2940 "password cannot be longer than %d bytes", INT_MAX);
2941 goto error;
2942 }
2943
Victor Stinner11ebff22013-07-07 17:07:52 +02002944 PyMem_Free(pw_info->password);
2945 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002946 if (!pw_info->password) {
2947 PyErr_SetString(PyExc_MemoryError,
2948 "unable to allocate password buffer");
2949 goto error;
2950 }
2951 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002952 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002953
2954 Py_XDECREF(password_bytes);
2955 return 1;
2956
2957error:
2958 Py_XDECREF(password_bytes);
2959 return 0;
2960}
2961
2962static int
2963_password_callback(char *buf, int size, int rwflag, void *userdata)
2964{
2965 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2966 PyObject *fn_ret = NULL;
2967
2968 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2969
2970 if (pw_info->callable) {
2971 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2972 if (!fn_ret) {
2973 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2974 core python API, so we could use it to add a frame here */
2975 goto error;
2976 }
2977
2978 if (!_pwinfo_set(pw_info, fn_ret,
2979 "password callback must return a string")) {
2980 goto error;
2981 }
2982 Py_CLEAR(fn_ret);
2983 }
2984
2985 if (pw_info->size > size) {
2986 PyErr_Format(PyExc_ValueError,
2987 "password cannot be longer than %d bytes", size);
2988 goto error;
2989 }
2990
2991 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2992 memcpy(buf, pw_info->password, pw_info->size);
2993 return pw_info->size;
2994
2995error:
2996 Py_XDECREF(fn_ret);
2997 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2998 pw_info->error = 1;
2999 return -1;
3000}
3001
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003002/*[clinic input]
3003_ssl._SSLContext.load_cert_chain
3004 certfile: object
3005 keyfile: object = NULL
3006 password: object = NULL
3007
3008[clinic start generated code]*/
3009
Antoine Pitroub5218772010-05-21 09:56:06 +00003010static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003011_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3012 PyObject *keyfile, PyObject *password)
3013/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003014{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003015 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003016 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3017 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003018 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019 int r;
3020
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003021 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003022 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003023 if (keyfile == Py_None)
3024 keyfile = NULL;
3025 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3026 PyErr_SetString(PyExc_TypeError,
3027 "certfile should be a valid filesystem path");
3028 return NULL;
3029 }
3030 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3031 PyErr_SetString(PyExc_TypeError,
3032 "keyfile should be a valid filesystem path");
3033 goto error;
3034 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003035 if (password && password != Py_None) {
3036 if (PyCallable_Check(password)) {
3037 pw_info.callable = password;
3038 } else if (!_pwinfo_set(&pw_info, password,
3039 "password should be a string or callable")) {
3040 goto error;
3041 }
3042 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3043 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3044 }
3045 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003046 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3047 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003048 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003049 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003050 if (pw_info.error) {
3051 ERR_clear_error();
3052 /* the password callback has already set the error information */
3053 }
3054 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003055 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003056 PyErr_SetFromErrno(PyExc_IOError);
3057 }
3058 else {
3059 _setSSLError(NULL, 0, __FILE__, __LINE__);
3060 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003061 goto error;
3062 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003063 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003064 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003065 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3066 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003067 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3068 Py_CLEAR(keyfile_bytes);
3069 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003070 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003071 if (pw_info.error) {
3072 ERR_clear_error();
3073 /* the password callback has already set the error information */
3074 }
3075 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003076 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003077 PyErr_SetFromErrno(PyExc_IOError);
3078 }
3079 else {
3080 _setSSLError(NULL, 0, __FILE__, __LINE__);
3081 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003082 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003084 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003086 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087 if (r != 1) {
3088 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003089 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003091 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3092 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003093 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003094 Py_RETURN_NONE;
3095
3096error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003097 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3098 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003099 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100 Py_XDECREF(keyfile_bytes);
3101 Py_XDECREF(certfile_bytes);
3102 return NULL;
3103}
3104
Christian Heimesefff7062013-11-21 03:35:02 +01003105/* internal helper function, returns -1 on error
3106 */
3107static int
3108_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3109 int filetype)
3110{
3111 BIO *biobuf = NULL;
3112 X509_STORE *store;
3113 int retval = 0, err, loaded = 0;
3114
3115 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3116
3117 if (len <= 0) {
3118 PyErr_SetString(PyExc_ValueError,
3119 "Empty certificate data");
3120 return -1;
3121 } else if (len > INT_MAX) {
3122 PyErr_SetString(PyExc_OverflowError,
3123 "Certificate data is too long.");
3124 return -1;
3125 }
3126
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003127 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003128 if (biobuf == NULL) {
3129 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3130 return -1;
3131 }
3132
3133 store = SSL_CTX_get_cert_store(self->ctx);
3134 assert(store != NULL);
3135
3136 while (1) {
3137 X509 *cert = NULL;
3138 int r;
3139
3140 if (filetype == SSL_FILETYPE_ASN1) {
3141 cert = d2i_X509_bio(biobuf, NULL);
3142 } else {
3143 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003144 SSL_CTX_get_default_passwd_cb(self->ctx),
3145 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3146 );
Christian Heimesefff7062013-11-21 03:35:02 +01003147 }
3148 if (cert == NULL) {
3149 break;
3150 }
3151 r = X509_STORE_add_cert(store, cert);
3152 X509_free(cert);
3153 if (!r) {
3154 err = ERR_peek_last_error();
3155 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3156 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3157 /* cert already in hash table, not an error */
3158 ERR_clear_error();
3159 } else {
3160 break;
3161 }
3162 }
3163 loaded++;
3164 }
3165
3166 err = ERR_peek_last_error();
3167 if ((filetype == SSL_FILETYPE_ASN1) &&
3168 (loaded > 0) &&
3169 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3170 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3171 /* EOF ASN1 file, not an error */
3172 ERR_clear_error();
3173 retval = 0;
3174 } else if ((filetype == SSL_FILETYPE_PEM) &&
3175 (loaded > 0) &&
3176 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3177 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3178 /* EOF PEM file, not an error */
3179 ERR_clear_error();
3180 retval = 0;
3181 } else {
3182 _setSSLError(NULL, 0, __FILE__, __LINE__);
3183 retval = -1;
3184 }
3185
3186 BIO_free(biobuf);
3187 return retval;
3188}
3189
3190
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003191/*[clinic input]
3192_ssl._SSLContext.load_verify_locations
3193 cafile: object = NULL
3194 capath: object = NULL
3195 cadata: object = NULL
3196
3197[clinic start generated code]*/
3198
Antoine Pitrou152efa22010-05-16 18:19:27 +00003199static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003200_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3201 PyObject *cafile,
3202 PyObject *capath,
3203 PyObject *cadata)
3204/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003205{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003206 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3207 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003208 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003209
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003210 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211 if (cafile == Py_None)
3212 cafile = NULL;
3213 if (capath == Py_None)
3214 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003215 if (cadata == Py_None)
3216 cadata = NULL;
3217
3218 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003219 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003220 "cafile, capath and cadata cannot be all omitted");
3221 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003222 }
3223 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3224 PyErr_SetString(PyExc_TypeError,
3225 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003226 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003227 }
3228 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003229 PyErr_SetString(PyExc_TypeError,
3230 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003231 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003232 }
Christian Heimesefff7062013-11-21 03:35:02 +01003233
3234 /* validata cadata type and load cadata */
3235 if (cadata) {
3236 Py_buffer buf;
3237 PyObject *cadata_ascii = NULL;
3238
3239 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3240 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3241 PyBuffer_Release(&buf);
3242 PyErr_SetString(PyExc_TypeError,
3243 "cadata should be a contiguous buffer with "
3244 "a single dimension");
3245 goto error;
3246 }
3247 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3248 PyBuffer_Release(&buf);
3249 if (r == -1) {
3250 goto error;
3251 }
3252 } else {
3253 PyErr_Clear();
3254 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3255 if (cadata_ascii == NULL) {
3256 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003257 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003258 "bytes-like object");
3259 goto error;
3260 }
3261 r = _add_ca_certs(self,
3262 PyBytes_AS_STRING(cadata_ascii),
3263 PyBytes_GET_SIZE(cadata_ascii),
3264 SSL_FILETYPE_PEM);
3265 Py_DECREF(cadata_ascii);
3266 if (r == -1) {
3267 goto error;
3268 }
3269 }
3270 }
3271
3272 /* load cafile or capath */
3273 if (cafile || capath) {
3274 if (cafile)
3275 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3276 if (capath)
3277 capath_buf = PyBytes_AS_STRING(capath_bytes);
3278 PySSL_BEGIN_ALLOW_THREADS
3279 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3280 PySSL_END_ALLOW_THREADS
3281 if (r != 1) {
3282 ok = 0;
3283 if (errno != 0) {
3284 ERR_clear_error();
3285 PyErr_SetFromErrno(PyExc_IOError);
3286 }
3287 else {
3288 _setSSLError(NULL, 0, __FILE__, __LINE__);
3289 }
3290 goto error;
3291 }
3292 }
3293 goto end;
3294
3295 error:
3296 ok = 0;
3297 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 Py_XDECREF(cafile_bytes);
3299 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003300 if (ok) {
3301 Py_RETURN_NONE;
3302 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003303 return NULL;
3304 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003305}
3306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003307/*[clinic input]
3308_ssl._SSLContext.load_dh_params
3309 path as filepath: object
3310 /
3311
3312[clinic start generated code]*/
3313
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003315_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3316/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003317{
3318 FILE *f;
3319 DH *dh;
3320
Victor Stinnerdaf45552013-08-28 00:53:59 +02003321 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003322 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003323 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003324
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003325 errno = 0;
3326 PySSL_BEGIN_ALLOW_THREADS
3327 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003328 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003329 PySSL_END_ALLOW_THREADS
3330 if (dh == NULL) {
3331 if (errno != 0) {
3332 ERR_clear_error();
3333 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3334 }
3335 else {
3336 _setSSLError(NULL, 0, __FILE__, __LINE__);
3337 }
3338 return NULL;
3339 }
3340 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3341 _setSSLError(NULL, 0, __FILE__, __LINE__);
3342 DH_free(dh);
3343 Py_RETURN_NONE;
3344}
3345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003346/*[clinic input]
3347_ssl._SSLContext._wrap_socket
3348 sock: object(subclass_of="PySocketModule.Sock_Type")
3349 server_side: int
3350 server_hostname as hostname_obj: object = None
3351
3352[clinic start generated code]*/
3353
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003354static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003355_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3356 int server_side, PyObject *hostname_obj)
3357/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003358{
Antoine Pitroud5323212010-10-22 18:19:07 +00003359 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003360 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003361
Antoine Pitroud5323212010-10-22 18:19:07 +00003362 /* server_hostname is either None (or absent), or to be encoded
3363 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003364 if (hostname_obj != Py_None) {
3365 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003366 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003367 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003368
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003369 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3370 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003371 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003372 if (hostname != NULL)
3373 PyMem_Free(hostname);
3374 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003375}
3376
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003377/*[clinic input]
3378_ssl._SSLContext._wrap_bio
3379 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3380 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3381 server_side: int
3382 server_hostname as hostname_obj: object = None
3383
3384[clinic start generated code]*/
3385
Antoine Pitroub0182c82010-10-12 20:09:02 +00003386static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003387_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3388 PySSLMemoryBIO *outgoing, int server_side,
3389 PyObject *hostname_obj)
3390/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003391{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003392 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003393 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003394
3395 /* server_hostname is either None (or absent), or to be encoded
3396 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003397 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003398 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3399 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003400 }
3401
3402 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3403 incoming, outgoing);
3404
3405 PyMem_Free(hostname);
3406 return res;
3407}
3408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003409/*[clinic input]
3410_ssl._SSLContext.session_stats
3411[clinic start generated code]*/
3412
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003413static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003414_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3415/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003416{
3417 int r;
3418 PyObject *value, *stats = PyDict_New();
3419 if (!stats)
3420 return NULL;
3421
3422#define ADD_STATS(SSL_NAME, KEY_NAME) \
3423 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3424 if (value == NULL) \
3425 goto error; \
3426 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3427 Py_DECREF(value); \
3428 if (r < 0) \
3429 goto error;
3430
3431 ADD_STATS(number, "number");
3432 ADD_STATS(connect, "connect");
3433 ADD_STATS(connect_good, "connect_good");
3434 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3435 ADD_STATS(accept, "accept");
3436 ADD_STATS(accept_good, "accept_good");
3437 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3438 ADD_STATS(accept, "accept");
3439 ADD_STATS(hits, "hits");
3440 ADD_STATS(misses, "misses");
3441 ADD_STATS(timeouts, "timeouts");
3442 ADD_STATS(cache_full, "cache_full");
3443
3444#undef ADD_STATS
3445
3446 return stats;
3447
3448error:
3449 Py_DECREF(stats);
3450 return NULL;
3451}
3452
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003453/*[clinic input]
3454_ssl._SSLContext.set_default_verify_paths
3455[clinic start generated code]*/
3456
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003457static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003458_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3459/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003460{
3461 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3462 _setSSLError(NULL, 0, __FILE__, __LINE__);
3463 return NULL;
3464 }
3465 Py_RETURN_NONE;
3466}
3467
Antoine Pitrou501da612011-12-21 09:27:41 +01003468#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003469/*[clinic input]
3470_ssl._SSLContext.set_ecdh_curve
3471 name: object
3472 /
3473
3474[clinic start generated code]*/
3475
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003476static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003477_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3478/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003479{
3480 PyObject *name_bytes;
3481 int nid;
3482 EC_KEY *key;
3483
3484 if (!PyUnicode_FSConverter(name, &name_bytes))
3485 return NULL;
3486 assert(PyBytes_Check(name_bytes));
3487 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3488 Py_DECREF(name_bytes);
3489 if (nid == 0) {
3490 PyErr_Format(PyExc_ValueError,
3491 "unknown elliptic curve name %R", name);
3492 return NULL;
3493 }
3494 key = EC_KEY_new_by_curve_name(nid);
3495 if (key == NULL) {
3496 _setSSLError(NULL, 0, __FILE__, __LINE__);
3497 return NULL;
3498 }
3499 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3500 EC_KEY_free(key);
3501 Py_RETURN_NONE;
3502}
Antoine Pitrou501da612011-12-21 09:27:41 +01003503#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003504
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003505#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003506static int
3507_servername_callback(SSL *s, int *al, void *args)
3508{
3509 int ret;
3510 PySSLContext *ssl_ctx = (PySSLContext *) args;
3511 PySSLSocket *ssl;
3512 PyObject *servername_o;
3513 PyObject *servername_idna;
3514 PyObject *result;
3515 /* The high-level ssl.SSLSocket object */
3516 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003517 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003518#ifdef WITH_THREAD
3519 PyGILState_STATE gstate = PyGILState_Ensure();
3520#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003521
3522 if (ssl_ctx->set_hostname == NULL) {
3523 /* remove race condition in this the call back while if removing the
3524 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003525#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003526 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003527#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003528 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003529 }
3530
3531 ssl = SSL_get_app_data(s);
3532 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003533
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003534 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003535 * SSL connection and that has a .context attribute that can be changed to
3536 * identify the requested hostname. Since the official API is the Python
3537 * level API we want to pass the callback a Python level object rather than
3538 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3539 * SSLObject) that will be passed. Otherwise if there's a socket then that
3540 * will be passed. If both do not exist only then the C-level object is
3541 * passed. */
3542 if (ssl->owner)
3543 ssl_socket = PyWeakref_GetObject(ssl->owner);
3544 else if (ssl->Socket)
3545 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3546 else
3547 ssl_socket = (PyObject *) ssl;
3548
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003549 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003550 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003551 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003552
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003553 if (servername == NULL) {
3554 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3555 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003556 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003557 else {
3558 servername_o = PyBytes_FromString(servername);
3559 if (servername_o == NULL) {
3560 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3561 goto error;
3562 }
3563 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3564 if (servername_idna == NULL) {
3565 PyErr_WriteUnraisable(servername_o);
3566 Py_DECREF(servername_o);
3567 goto error;
3568 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003569 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003570 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3571 servername_idna, ssl_ctx, NULL);
3572 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003573 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003574 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003575
3576 if (result == NULL) {
3577 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3578 *al = SSL_AD_HANDSHAKE_FAILURE;
3579 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3580 }
3581 else {
3582 if (result != Py_None) {
3583 *al = (int) PyLong_AsLong(result);
3584 if (PyErr_Occurred()) {
3585 PyErr_WriteUnraisable(result);
3586 *al = SSL_AD_INTERNAL_ERROR;
3587 }
3588 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3589 }
3590 else {
3591 ret = SSL_TLSEXT_ERR_OK;
3592 }
3593 Py_DECREF(result);
3594 }
3595
Stefan Krah20d60802013-01-17 17:07:17 +01003596#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003597 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003598#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003599 return ret;
3600
3601error:
3602 Py_DECREF(ssl_socket);
3603 *al = SSL_AD_INTERNAL_ERROR;
3604 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003605#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003606 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003607#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003608 return ret;
3609}
Antoine Pitroua5963382013-03-30 16:39:00 +01003610#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003611
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003612/*[clinic input]
3613_ssl._SSLContext.set_servername_callback
3614 method as cb: object
3615 /
3616
3617Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3618
3619If the argument is None then the callback is disabled. The method is called
3620with the SSLSocket, the server name as a string, and the SSLContext object.
3621See RFC 6066 for details of the SNI extension.
3622[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003623
3624static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003625_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3626/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003627{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003628#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003629 Py_CLEAR(self->set_hostname);
3630 if (cb == Py_None) {
3631 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3632 }
3633 else {
3634 if (!PyCallable_Check(cb)) {
3635 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3636 PyErr_SetString(PyExc_TypeError,
3637 "not a callable object");
3638 return NULL;
3639 }
3640 Py_INCREF(cb);
3641 self->set_hostname = cb;
3642 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3643 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3644 }
3645 Py_RETURN_NONE;
3646#else
3647 PyErr_SetString(PyExc_NotImplementedError,
3648 "The TLS extension servername callback, "
3649 "SSL_CTX_set_tlsext_servername_callback, "
3650 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003651 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003652#endif
3653}
3654
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003655/*[clinic input]
3656_ssl._SSLContext.cert_store_stats
3657
3658Returns quantities of loaded X.509 certificates.
3659
3660X.509 certificates with a CA extension and certificate revocation lists
3661inside the context's cert store.
3662
3663NOTE: Certificates in a capath directory aren't loaded unless they have
3664been used at least once.
3665[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003666
3667static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003668_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3669/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003670{
3671 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003672 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003673 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003674 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003675
3676 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003677 objs = X509_STORE_get0_objects(store);
3678 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3679 obj = sk_X509_OBJECT_value(objs, i);
3680 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003681 case X509_LU_X509:
3682 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003683 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003684 ca++;
3685 }
3686 break;
3687 case X509_LU_CRL:
3688 crl++;
3689 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003690 default:
3691 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3692 * As far as I can tell they are internal states and never
3693 * stored in a cert store */
3694 break;
3695 }
3696 }
3697 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3698 "x509_ca", ca);
3699}
3700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003701/*[clinic input]
3702_ssl._SSLContext.get_ca_certs
3703 binary_form: bool = False
3704
3705Returns a list of dicts with information of loaded CA certs.
3706
3707If the optional argument is True, returns a DER-encoded copy of the CA
3708certificate.
3709
3710NOTE: Certificates in a capath directory aren't loaded unless they have
3711been used at least once.
3712[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003713
3714static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003715_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3716/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003717{
3718 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003719 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003720 PyObject *ci = NULL, *rlist = NULL;
3721 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003722
3723 if ((rlist = PyList_New(0)) == NULL) {
3724 return NULL;
3725 }
3726
3727 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003728 objs = X509_STORE_get0_objects(store);
3729 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003730 X509_OBJECT *obj;
3731 X509 *cert;
3732
Christian Heimes598894f2016-09-05 23:19:05 +02003733 obj = sk_X509_OBJECT_value(objs, i);
3734 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003735 /* not a x509 cert */
3736 continue;
3737 }
3738 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003739 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003740 if (!X509_check_ca(cert)) {
3741 continue;
3742 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003743 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003744 ci = _certificate_to_der(cert);
3745 } else {
3746 ci = _decode_certificate(cert);
3747 }
3748 if (ci == NULL) {
3749 goto error;
3750 }
3751 if (PyList_Append(rlist, ci) == -1) {
3752 goto error;
3753 }
3754 Py_CLEAR(ci);
3755 }
3756 return rlist;
3757
3758 error:
3759 Py_XDECREF(ci);
3760 Py_XDECREF(rlist);
3761 return NULL;
3762}
3763
3764
Antoine Pitrou152efa22010-05-16 18:19:27 +00003765static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003766 {"check_hostname", (getter) get_check_hostname,
3767 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003768 {"options", (getter) get_options,
3769 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003770 {"verify_flags", (getter) get_verify_flags,
3771 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003772 {"verify_mode", (getter) get_verify_mode,
3773 (setter) set_verify_mode, NULL},
3774 {NULL}, /* sentinel */
3775};
3776
3777static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003778 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3779 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3780 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3781 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3782 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3783 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3784 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3785 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3786 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3787 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3788 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3789 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3790 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3791 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003792 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003793 {NULL, NULL} /* sentinel */
3794};
3795
3796static PyTypeObject PySSLContext_Type = {
3797 PyVarObject_HEAD_INIT(NULL, 0)
3798 "_ssl._SSLContext", /*tp_name*/
3799 sizeof(PySSLContext), /*tp_basicsize*/
3800 0, /*tp_itemsize*/
3801 (destructor)context_dealloc, /*tp_dealloc*/
3802 0, /*tp_print*/
3803 0, /*tp_getattr*/
3804 0, /*tp_setattr*/
3805 0, /*tp_reserved*/
3806 0, /*tp_repr*/
3807 0, /*tp_as_number*/
3808 0, /*tp_as_sequence*/
3809 0, /*tp_as_mapping*/
3810 0, /*tp_hash*/
3811 0, /*tp_call*/
3812 0, /*tp_str*/
3813 0, /*tp_getattro*/
3814 0, /*tp_setattro*/
3815 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003816 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003817 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003818 (traverseproc) context_traverse, /*tp_traverse*/
3819 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003820 0, /*tp_richcompare*/
3821 0, /*tp_weaklistoffset*/
3822 0, /*tp_iter*/
3823 0, /*tp_iternext*/
3824 context_methods, /*tp_methods*/
3825 0, /*tp_members*/
3826 context_getsetlist, /*tp_getset*/
3827 0, /*tp_base*/
3828 0, /*tp_dict*/
3829 0, /*tp_descr_get*/
3830 0, /*tp_descr_set*/
3831 0, /*tp_dictoffset*/
3832 0, /*tp_init*/
3833 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003834 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003835};
3836
3837
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003838/*
3839 * MemoryBIO objects
3840 */
3841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003842/*[clinic input]
3843@classmethod
3844_ssl.MemoryBIO.__new__
3845
3846[clinic start generated code]*/
3847
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003848static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003849_ssl_MemoryBIO_impl(PyTypeObject *type)
3850/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003851{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003852 BIO *bio;
3853 PySSLMemoryBIO *self;
3854
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003855 bio = BIO_new(BIO_s_mem());
3856 if (bio == NULL) {
3857 PyErr_SetString(PySSLErrorObject,
3858 "failed to allocate BIO");
3859 return NULL;
3860 }
3861 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3862 * just that no data is currently available. The SSL routines should retry
3863 * the read, which we can achieve by calling BIO_set_retry_read(). */
3864 BIO_set_retry_read(bio);
3865 BIO_set_mem_eof_return(bio, -1);
3866
3867 assert(type != NULL && type->tp_alloc != NULL);
3868 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3869 if (self == NULL) {
3870 BIO_free(bio);
3871 return NULL;
3872 }
3873 self->bio = bio;
3874 self->eof_written = 0;
3875
3876 return (PyObject *) self;
3877}
3878
3879static void
3880memory_bio_dealloc(PySSLMemoryBIO *self)
3881{
3882 BIO_free(self->bio);
3883 Py_TYPE(self)->tp_free(self);
3884}
3885
3886static PyObject *
3887memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3888{
3889 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3890}
3891
3892PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3893"The number of bytes pending in the memory BIO.");
3894
3895static PyObject *
3896memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3897{
3898 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3899 && self->eof_written);
3900}
3901
3902PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3903"Whether the memory BIO is at EOF.");
3904
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003905/*[clinic input]
3906_ssl.MemoryBIO.read
3907 size as len: int = -1
3908 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003909
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003910Read up to size bytes from the memory BIO.
3911
3912If size is not specified, read the entire buffer.
3913If the return value is an empty bytes instance, this means either
3914EOF or that no data is available. Use the "eof" property to
3915distinguish between the two.
3916[clinic start generated code]*/
3917
3918static PyObject *
3919_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3920/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3921{
3922 int avail, nbytes;
3923 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003924
3925 avail = BIO_ctrl_pending(self->bio);
3926 if ((len < 0) || (len > avail))
3927 len = avail;
3928
3929 result = PyBytes_FromStringAndSize(NULL, len);
3930 if ((result == NULL) || (len == 0))
3931 return result;
3932
3933 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3934 /* There should never be any short reads but check anyway. */
3935 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3936 Py_DECREF(result);
3937 return NULL;
3938 }
3939
3940 return result;
3941}
3942
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003943/*[clinic input]
3944_ssl.MemoryBIO.write
3945 b: Py_buffer
3946 /
3947
3948Writes the bytes b into the memory BIO.
3949
3950Returns the number of bytes written.
3951[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003952
3953static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003954_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3955/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003956{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003957 int nbytes;
3958
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003959 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003960 PyErr_Format(PyExc_OverflowError,
3961 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003962 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003963 }
3964
3965 if (self->eof_written) {
3966 PyErr_SetString(PySSLErrorObject,
3967 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003968 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003969 }
3970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003971 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003972 if (nbytes < 0) {
3973 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003974 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003975 }
3976
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003977 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003978}
3979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003980/*[clinic input]
3981_ssl.MemoryBIO.write_eof
3982
3983Write an EOF marker to the memory BIO.
3984
3985When all data has been read, the "eof" property will be True.
3986[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003987
3988static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003989_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3990/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003991{
3992 self->eof_written = 1;
3993 /* After an EOF is written, a zero return from read() should be a real EOF
3994 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3995 BIO_clear_retry_flags(self->bio);
3996 BIO_set_mem_eof_return(self->bio, 0);
3997
3998 Py_RETURN_NONE;
3999}
4000
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004001static PyGetSetDef memory_bio_getsetlist[] = {
4002 {"pending", (getter) memory_bio_get_pending, NULL,
4003 PySSL_memory_bio_pending_doc},
4004 {"eof", (getter) memory_bio_get_eof, NULL,
4005 PySSL_memory_bio_eof_doc},
4006 {NULL}, /* sentinel */
4007};
4008
4009static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004010 _SSL_MEMORYBIO_READ_METHODDEF
4011 _SSL_MEMORYBIO_WRITE_METHODDEF
4012 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004013 {NULL, NULL} /* sentinel */
4014};
4015
4016static PyTypeObject PySSLMemoryBIO_Type = {
4017 PyVarObject_HEAD_INIT(NULL, 0)
4018 "_ssl.MemoryBIO", /*tp_name*/
4019 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4020 0, /*tp_itemsize*/
4021 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4022 0, /*tp_print*/
4023 0, /*tp_getattr*/
4024 0, /*tp_setattr*/
4025 0, /*tp_reserved*/
4026 0, /*tp_repr*/
4027 0, /*tp_as_number*/
4028 0, /*tp_as_sequence*/
4029 0, /*tp_as_mapping*/
4030 0, /*tp_hash*/
4031 0, /*tp_call*/
4032 0, /*tp_str*/
4033 0, /*tp_getattro*/
4034 0, /*tp_setattro*/
4035 0, /*tp_as_buffer*/
4036 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4037 0, /*tp_doc*/
4038 0, /*tp_traverse*/
4039 0, /*tp_clear*/
4040 0, /*tp_richcompare*/
4041 0, /*tp_weaklistoffset*/
4042 0, /*tp_iter*/
4043 0, /*tp_iternext*/
4044 memory_bio_methods, /*tp_methods*/
4045 0, /*tp_members*/
4046 memory_bio_getsetlist, /*tp_getset*/
4047 0, /*tp_base*/
4048 0, /*tp_dict*/
4049 0, /*tp_descr_get*/
4050 0, /*tp_descr_set*/
4051 0, /*tp_dictoffset*/
4052 0, /*tp_init*/
4053 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004054 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004055};
4056
Antoine Pitrou152efa22010-05-16 18:19:27 +00004057
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004058/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004059/*[clinic input]
4060_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004061 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062 entropy: double
4063 /
4064
4065Mix string into the OpenSSL PRNG state.
4066
4067entropy (a float) is a lower bound on the entropy contained in
4068string. See RFC 1750.
4069[clinic start generated code]*/
4070
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004071static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004072_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4073/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004074{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004075 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004076 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004078 buf = (const char *)view->buf;
4079 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004080 do {
4081 written = Py_MIN(len, INT_MAX);
4082 RAND_add(buf, (int)written, entropy);
4083 buf += written;
4084 len -= written;
4085 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004086 Py_INCREF(Py_None);
4087 return Py_None;
4088}
4089
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004090static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004091PySSL_RAND(int len, int pseudo)
4092{
4093 int ok;
4094 PyObject *bytes;
4095 unsigned long err;
4096 const char *errstr;
4097 PyObject *v;
4098
Victor Stinner1e81a392013-12-19 16:47:04 +01004099 if (len < 0) {
4100 PyErr_SetString(PyExc_ValueError, "num must be positive");
4101 return NULL;
4102 }
4103
Victor Stinner99c8b162011-05-24 12:05:19 +02004104 bytes = PyBytes_FromStringAndSize(NULL, len);
4105 if (bytes == NULL)
4106 return NULL;
4107 if (pseudo) {
4108 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4109 if (ok == 0 || ok == 1)
4110 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4111 }
4112 else {
4113 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4114 if (ok == 1)
4115 return bytes;
4116 }
4117 Py_DECREF(bytes);
4118
4119 err = ERR_get_error();
4120 errstr = ERR_reason_error_string(err);
4121 v = Py_BuildValue("(ks)", err, errstr);
4122 if (v != NULL) {
4123 PyErr_SetObject(PySSLErrorObject, v);
4124 Py_DECREF(v);
4125 }
4126 return NULL;
4127}
4128
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129/*[clinic input]
4130_ssl.RAND_bytes
4131 n: int
4132 /
4133
4134Generate n cryptographically strong pseudo-random bytes.
4135[clinic start generated code]*/
4136
Victor Stinner99c8b162011-05-24 12:05:19 +02004137static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004138_ssl_RAND_bytes_impl(PyObject *module, int n)
4139/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004140{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004141 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004142}
4143
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004144/*[clinic input]
4145_ssl.RAND_pseudo_bytes
4146 n: int
4147 /
4148
4149Generate n pseudo-random bytes.
4150
4151Return a pair (bytes, is_cryptographic). is_cryptographic is True
4152if the bytes generated are cryptographically strong.
4153[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004154
4155static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004156_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4157/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004158{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004160}
4161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162/*[clinic input]
4163_ssl.RAND_status
4164
4165Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4166
4167It is necessary to seed the PRNG with RAND_add() on some platforms before
4168using the ssl() function.
4169[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004170
4171static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004172_ssl_RAND_status_impl(PyObject *module)
4173/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004174{
Christian Heimes217cfd12007-12-02 14:31:20 +00004175 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004176}
4177
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004178#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004179/*[clinic input]
4180_ssl.RAND_egd
4181 path: object(converter="PyUnicode_FSConverter")
4182 /
4183
4184Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4185
4186Returns number of bytes read. Raises SSLError if connection to EGD
4187fails or if it does not provide enough data to seed PRNG.
4188[clinic start generated code]*/
4189
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004190static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004191_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4192/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004193{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004195 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004196 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004197 PyErr_SetString(PySSLErrorObject,
4198 "EGD connection failed or EGD did not return "
4199 "enough data to seed the PRNG");
4200 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004201 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004202 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004203}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004204#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004205
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207
4208/*[clinic input]
4209_ssl.get_default_verify_paths
4210
4211Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4212
4213The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4214[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004215
4216static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004217_ssl_get_default_verify_paths_impl(PyObject *module)
4218/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004219{
4220 PyObject *ofile_env = NULL;
4221 PyObject *ofile = NULL;
4222 PyObject *odir_env = NULL;
4223 PyObject *odir = NULL;
4224
Benjamin Petersond113c962015-07-18 10:59:13 -07004225#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004226 const char *tmp = (info); \
4227 target = NULL; \
4228 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4229 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4230 target = PyBytes_FromString(tmp); } \
4231 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004232 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004233
Benjamin Petersond113c962015-07-18 10:59:13 -07004234 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4235 CONVERT(X509_get_default_cert_file(), ofile);
4236 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4237 CONVERT(X509_get_default_cert_dir(), odir);
4238#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004239
Christian Heimes200bb1b2013-06-14 15:14:29 +02004240 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004241
4242 error:
4243 Py_XDECREF(ofile_env);
4244 Py_XDECREF(ofile);
4245 Py_XDECREF(odir_env);
4246 Py_XDECREF(odir);
4247 return NULL;
4248}
4249
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004250static PyObject*
4251asn1obj2py(ASN1_OBJECT *obj)
4252{
4253 int nid;
4254 const char *ln, *sn;
4255 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004256 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004257
4258 nid = OBJ_obj2nid(obj);
4259 if (nid == NID_undef) {
4260 PyErr_Format(PyExc_ValueError, "Unknown object");
4261 return NULL;
4262 }
4263 sn = OBJ_nid2sn(nid);
4264 ln = OBJ_nid2ln(nid);
4265 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4266 if (buflen < 0) {
4267 _setSSLError(NULL, 0, __FILE__, __LINE__);
4268 return NULL;
4269 }
4270 if (buflen) {
4271 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4272 } else {
4273 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4274 }
4275}
4276
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004277/*[clinic input]
4278_ssl.txt2obj
4279 txt: str
4280 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004282Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4283
4284By default objects are looked up by OID. With name=True short and
4285long name are also matched.
4286[clinic start generated code]*/
4287
4288static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004289_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4290/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004291{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004292 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004293 ASN1_OBJECT *obj;
4294
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004295 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4296 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004297 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004298 return NULL;
4299 }
4300 result = asn1obj2py(obj);
4301 ASN1_OBJECT_free(obj);
4302 return result;
4303}
4304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004305/*[clinic input]
4306_ssl.nid2obj
4307 nid: int
4308 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004309
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004310Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4311[clinic start generated code]*/
4312
4313static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004314_ssl_nid2obj_impl(PyObject *module, int nid)
4315/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004316{
4317 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004318 ASN1_OBJECT *obj;
4319
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004320 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004321 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004322 return NULL;
4323 }
4324 obj = OBJ_nid2obj(nid);
4325 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004326 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004327 return NULL;
4328 }
4329 result = asn1obj2py(obj);
4330 ASN1_OBJECT_free(obj);
4331 return result;
4332}
4333
Christian Heimes46bebee2013-06-09 19:03:31 +02004334#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004335
4336static PyObject*
4337certEncodingType(DWORD encodingType)
4338{
4339 static PyObject *x509_asn = NULL;
4340 static PyObject *pkcs_7_asn = NULL;
4341
4342 if (x509_asn == NULL) {
4343 x509_asn = PyUnicode_InternFromString("x509_asn");
4344 if (x509_asn == NULL)
4345 return NULL;
4346 }
4347 if (pkcs_7_asn == NULL) {
4348 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4349 if (pkcs_7_asn == NULL)
4350 return NULL;
4351 }
4352 switch(encodingType) {
4353 case X509_ASN_ENCODING:
4354 Py_INCREF(x509_asn);
4355 return x509_asn;
4356 case PKCS_7_ASN_ENCODING:
4357 Py_INCREF(pkcs_7_asn);
4358 return pkcs_7_asn;
4359 default:
4360 return PyLong_FromLong(encodingType);
4361 }
4362}
4363
4364static PyObject*
4365parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4366{
4367 CERT_ENHKEY_USAGE *usage;
4368 DWORD size, error, i;
4369 PyObject *retval;
4370
4371 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4372 error = GetLastError();
4373 if (error == CRYPT_E_NOT_FOUND) {
4374 Py_RETURN_TRUE;
4375 }
4376 return PyErr_SetFromWindowsErr(error);
4377 }
4378
4379 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4380 if (usage == NULL) {
4381 return PyErr_NoMemory();
4382 }
4383
4384 /* Now get the actual enhanced usage property */
4385 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4386 PyMem_Free(usage);
4387 error = GetLastError();
4388 if (error == CRYPT_E_NOT_FOUND) {
4389 Py_RETURN_TRUE;
4390 }
4391 return PyErr_SetFromWindowsErr(error);
4392 }
4393 retval = PySet_New(NULL);
4394 if (retval == NULL) {
4395 goto error;
4396 }
4397 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4398 if (usage->rgpszUsageIdentifier[i]) {
4399 PyObject *oid;
4400 int err;
4401 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4402 if (oid == NULL) {
4403 Py_CLEAR(retval);
4404 goto error;
4405 }
4406 err = PySet_Add(retval, oid);
4407 Py_DECREF(oid);
4408 if (err == -1) {
4409 Py_CLEAR(retval);
4410 goto error;
4411 }
4412 }
4413 }
4414 error:
4415 PyMem_Free(usage);
4416 return retval;
4417}
4418
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004419/*[clinic input]
4420_ssl.enum_certificates
4421 store_name: str
4422
4423Retrieve certificates from Windows' cert store.
4424
4425store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4426more cert storages, too. The function returns a list of (bytes,
4427encoding_type, trust) tuples. The encoding_type flag can be interpreted
4428with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4429a set of OIDs or the boolean True.
4430[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004431
Christian Heimes46bebee2013-06-09 19:03:31 +02004432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004433_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4434/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004435{
Christian Heimes46bebee2013-06-09 19:03:31 +02004436 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004437 PCCERT_CONTEXT pCertCtx = NULL;
4438 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004439 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004440
Christian Heimes44109d72013-11-22 01:51:30 +01004441 result = PyList_New(0);
4442 if (result == NULL) {
4443 return NULL;
4444 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004445 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4446 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4447 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004448 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004449 Py_DECREF(result);
4450 return PyErr_SetFromWindowsErr(GetLastError());
4451 }
4452
Christian Heimes44109d72013-11-22 01:51:30 +01004453 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4454 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4455 pCertCtx->cbCertEncoded);
4456 if (!cert) {
4457 Py_CLEAR(result);
4458 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004459 }
Christian Heimes44109d72013-11-22 01:51:30 +01004460 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4461 Py_CLEAR(result);
4462 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004463 }
Christian Heimes44109d72013-11-22 01:51:30 +01004464 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4465 if (keyusage == Py_True) {
4466 Py_DECREF(keyusage);
4467 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004468 }
Christian Heimes44109d72013-11-22 01:51:30 +01004469 if (keyusage == NULL) {
4470 Py_CLEAR(result);
4471 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004472 }
Christian Heimes44109d72013-11-22 01:51:30 +01004473 if ((tup = PyTuple_New(3)) == NULL) {
4474 Py_CLEAR(result);
4475 break;
4476 }
4477 PyTuple_SET_ITEM(tup, 0, cert);
4478 cert = NULL;
4479 PyTuple_SET_ITEM(tup, 1, enc);
4480 enc = NULL;
4481 PyTuple_SET_ITEM(tup, 2, keyusage);
4482 keyusage = NULL;
4483 if (PyList_Append(result, tup) < 0) {
4484 Py_CLEAR(result);
4485 break;
4486 }
4487 Py_CLEAR(tup);
4488 }
4489 if (pCertCtx) {
4490 /* loop ended with an error, need to clean up context manually */
4491 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004492 }
4493
4494 /* In error cases cert, enc and tup may not be NULL */
4495 Py_XDECREF(cert);
4496 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004497 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004498 Py_XDECREF(tup);
4499
4500 if (!CertCloseStore(hStore, 0)) {
4501 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004502 Py_XDECREF(result);
4503 return PyErr_SetFromWindowsErr(GetLastError());
4504 }
4505 return result;
4506}
4507
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004508/*[clinic input]
4509_ssl.enum_crls
4510 store_name: str
4511
4512Retrieve CRLs from Windows' cert store.
4513
4514store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4515more cert storages, too. The function returns a list of (bytes,
4516encoding_type) tuples. The encoding_type flag can be interpreted with
4517X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4518[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004519
4520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004521_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4522/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004523{
Christian Heimes44109d72013-11-22 01:51:30 +01004524 HCERTSTORE hStore = NULL;
4525 PCCRL_CONTEXT pCrlCtx = NULL;
4526 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4527 PyObject *result = NULL;
4528
Christian Heimes44109d72013-11-22 01:51:30 +01004529 result = PyList_New(0);
4530 if (result == NULL) {
4531 return NULL;
4532 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004533 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4534 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4535 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004536 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004537 Py_DECREF(result);
4538 return PyErr_SetFromWindowsErr(GetLastError());
4539 }
Christian Heimes44109d72013-11-22 01:51:30 +01004540
4541 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4542 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4543 pCrlCtx->cbCrlEncoded);
4544 if (!crl) {
4545 Py_CLEAR(result);
4546 break;
4547 }
4548 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4549 Py_CLEAR(result);
4550 break;
4551 }
4552 if ((tup = PyTuple_New(2)) == NULL) {
4553 Py_CLEAR(result);
4554 break;
4555 }
4556 PyTuple_SET_ITEM(tup, 0, crl);
4557 crl = NULL;
4558 PyTuple_SET_ITEM(tup, 1, enc);
4559 enc = NULL;
4560
4561 if (PyList_Append(result, tup) < 0) {
4562 Py_CLEAR(result);
4563 break;
4564 }
4565 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004566 }
Christian Heimes44109d72013-11-22 01:51:30 +01004567 if (pCrlCtx) {
4568 /* loop ended with an error, need to clean up context manually */
4569 CertFreeCRLContext(pCrlCtx);
4570 }
4571
4572 /* In error cases cert, enc and tup may not be NULL */
4573 Py_XDECREF(crl);
4574 Py_XDECREF(enc);
4575 Py_XDECREF(tup);
4576
4577 if (!CertCloseStore(hStore, 0)) {
4578 /* This error case might shadow another exception.*/
4579 Py_XDECREF(result);
4580 return PyErr_SetFromWindowsErr(GetLastError());
4581 }
4582 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004583}
Christian Heimes44109d72013-11-22 01:51:30 +01004584
4585#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004586
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004587/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004588static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004589 _SSL__TEST_DECODE_CERT_METHODDEF
4590 _SSL_RAND_ADD_METHODDEF
4591 _SSL_RAND_BYTES_METHODDEF
4592 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4593 _SSL_RAND_EGD_METHODDEF
4594 _SSL_RAND_STATUS_METHODDEF
4595 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4596 _SSL_ENUM_CERTIFICATES_METHODDEF
4597 _SSL_ENUM_CRLS_METHODDEF
4598 _SSL_TXT2OBJ_METHODDEF
4599 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004600 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004601};
4602
4603
Christian Heimes598894f2016-09-05 23:19:05 +02004604#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004605
4606/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004607 * of the Python C thread library
4608 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4609 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004610
4611static PyThread_type_lock *_ssl_locks = NULL;
4612
Christian Heimes4d98ca92013-08-19 17:36:29 +02004613#if OPENSSL_VERSION_NUMBER >= 0x10000000
4614/* use new CRYPTO_THREADID API. */
4615static void
4616_ssl_threadid_callback(CRYPTO_THREADID *id)
4617{
4618 CRYPTO_THREADID_set_numeric(id,
4619 (unsigned long)PyThread_get_thread_ident());
4620}
4621#else
4622/* deprecated CRYPTO_set_id_callback() API. */
4623static unsigned long
4624_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004625 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004626}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004627#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004628
Bill Janssen6e027db2007-11-15 22:23:56 +00004629static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004630 (int mode, int n, const char *file, int line) {
4631 /* this function is needed to perform locking on shared data
4632 structures. (Note that OpenSSL uses a number of global data
4633 structures that will be implicitly shared whenever multiple
4634 threads use OpenSSL.) Multi-threaded applications will
4635 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004636
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004637 locking_function() must be able to handle up to
4638 CRYPTO_num_locks() different mutex locks. It sets the n-th
4639 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004641 file and line are the file number of the function setting the
4642 lock. They can be useful for debugging.
4643 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004645 if ((_ssl_locks == NULL) ||
4646 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4647 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004649 if (mode & CRYPTO_LOCK) {
4650 PyThread_acquire_lock(_ssl_locks[n], 1);
4651 } else {
4652 PyThread_release_lock(_ssl_locks[n]);
4653 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004654}
4655
4656static int _setup_ssl_threads(void) {
4657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004658 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004660 if (_ssl_locks == NULL) {
4661 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004662 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4663 if (_ssl_locks == NULL) {
4664 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004665 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004666 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004667 memset(_ssl_locks, 0,
4668 sizeof(PyThread_type_lock) * _ssl_locks_count);
4669 for (i = 0; i < _ssl_locks_count; i++) {
4670 _ssl_locks[i] = PyThread_allocate_lock();
4671 if (_ssl_locks[i] == NULL) {
4672 unsigned int j;
4673 for (j = 0; j < i; j++) {
4674 PyThread_free_lock(_ssl_locks[j]);
4675 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004676 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004677 return 0;
4678 }
4679 }
4680 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004681#if OPENSSL_VERSION_NUMBER >= 0x10000000
4682 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4683#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004684 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004685#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004686 }
4687 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004688}
4689
Christian Heimes598894f2016-09-05 23:19:05 +02004690#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004692PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004693"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004694for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004695
Martin v. Löwis1a214512008-06-11 05:26:20 +00004696
4697static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004698 PyModuleDef_HEAD_INIT,
4699 "_ssl",
4700 module_doc,
4701 -1,
4702 PySSL_methods,
4703 NULL,
4704 NULL,
4705 NULL,
4706 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004707};
4708
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004709
4710static void
4711parse_openssl_version(unsigned long libver,
4712 unsigned int *major, unsigned int *minor,
4713 unsigned int *fix, unsigned int *patch,
4714 unsigned int *status)
4715{
4716 *status = libver & 0xF;
4717 libver >>= 4;
4718 *patch = libver & 0xFF;
4719 libver >>= 8;
4720 *fix = libver & 0xFF;
4721 libver >>= 8;
4722 *minor = libver & 0xFF;
4723 libver >>= 8;
4724 *major = libver & 0xFF;
4725}
4726
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004727PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004728PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004729{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004730 PyObject *m, *d, *r;
4731 unsigned long libver;
4732 unsigned int major, minor, fix, patch, status;
4733 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004734 struct py_ssl_error_code *errcode;
4735 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004736
Antoine Pitrou152efa22010-05-16 18:19:27 +00004737 if (PyType_Ready(&PySSLContext_Type) < 0)
4738 return NULL;
4739 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004740 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4742 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004743
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004744 m = PyModule_Create(&_sslmodule);
4745 if (m == NULL)
4746 return NULL;
4747 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004749 /* Load _socket module and its C API */
4750 socket_api = PySocketModule_ImportModuleAndAPI();
4751 if (!socket_api)
4752 return NULL;
4753 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004755 /* Init OpenSSL */
4756 SSL_load_error_strings();
4757 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004758#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02004759#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004760 /* note that this will start threading if not already started */
4761 if (!_setup_ssl_threads()) {
4762 return NULL;
4763 }
Christian Heimes598894f2016-09-05 23:19:05 +02004764#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4765 /* OpenSSL 1.1.0 builtin thread support is enabled */
4766 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004767#endif
Christian Heimes598894f2016-09-05 23:19:05 +02004768#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004769 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004770
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004771 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004772 sslerror_type_slots[0].pfunc = PyExc_OSError;
4773 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004774 if (PySSLErrorObject == NULL)
4775 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004776
Antoine Pitrou41032a62011-10-27 23:56:55 +02004777 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4778 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4779 PySSLErrorObject, NULL);
4780 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4781 "ssl.SSLWantReadError", SSLWantReadError_doc,
4782 PySSLErrorObject, NULL);
4783 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4784 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4785 PySSLErrorObject, NULL);
4786 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4787 "ssl.SSLSyscallError", SSLSyscallError_doc,
4788 PySSLErrorObject, NULL);
4789 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4790 "ssl.SSLEOFError", SSLEOFError_doc,
4791 PySSLErrorObject, NULL);
4792 if (PySSLZeroReturnErrorObject == NULL
4793 || PySSLWantReadErrorObject == NULL
4794 || PySSLWantWriteErrorObject == NULL
4795 || PySSLSyscallErrorObject == NULL
4796 || PySSLEOFErrorObject == NULL)
4797 return NULL;
4798 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4799 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4800 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4801 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4802 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4803 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004804 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004805 if (PyDict_SetItemString(d, "_SSLContext",
4806 (PyObject *)&PySSLContext_Type) != 0)
4807 return NULL;
4808 if (PyDict_SetItemString(d, "_SSLSocket",
4809 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004810 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004811 if (PyDict_SetItemString(d, "MemoryBIO",
4812 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4813 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004814 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4815 PY_SSL_ERROR_ZERO_RETURN);
4816 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4817 PY_SSL_ERROR_WANT_READ);
4818 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4819 PY_SSL_ERROR_WANT_WRITE);
4820 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4821 PY_SSL_ERROR_WANT_X509_LOOKUP);
4822 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4823 PY_SSL_ERROR_SYSCALL);
4824 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4825 PY_SSL_ERROR_SSL);
4826 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4827 PY_SSL_ERROR_WANT_CONNECT);
4828 /* non ssl.h errorcodes */
4829 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4830 PY_SSL_ERROR_EOF);
4831 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4832 PY_SSL_ERROR_INVALID_ERROR_CODE);
4833 /* cert requirements */
4834 PyModule_AddIntConstant(m, "CERT_NONE",
4835 PY_SSL_CERT_NONE);
4836 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4837 PY_SSL_CERT_OPTIONAL);
4838 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4839 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004840 /* CRL verification for verification_flags */
4841 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4842 0);
4843 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4844 X509_V_FLAG_CRL_CHECK);
4845 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4846 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4847 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4848 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004849#ifdef X509_V_FLAG_TRUSTED_FIRST
4850 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4851 X509_V_FLAG_TRUSTED_FIRST);
4852#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004853
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004854 /* Alert Descriptions from ssl.h */
4855 /* note RESERVED constants no longer intended for use have been removed */
4856 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4857
4858#define ADD_AD_CONSTANT(s) \
4859 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4860 SSL_AD_##s)
4861
4862 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4863 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4864 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4865 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4866 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4867 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4868 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4869 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4870 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4871 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4872 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4873 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4874 ADD_AD_CONSTANT(UNKNOWN_CA);
4875 ADD_AD_CONSTANT(ACCESS_DENIED);
4876 ADD_AD_CONSTANT(DECODE_ERROR);
4877 ADD_AD_CONSTANT(DECRYPT_ERROR);
4878 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4879 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4880 ADD_AD_CONSTANT(INTERNAL_ERROR);
4881 ADD_AD_CONSTANT(USER_CANCELLED);
4882 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004883 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004884#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4885 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4886#endif
4887#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4888 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4889#endif
4890#ifdef SSL_AD_UNRECOGNIZED_NAME
4891 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4892#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004893#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4894 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4895#endif
4896#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4897 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4898#endif
4899#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4900 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4901#endif
4902
4903#undef ADD_AD_CONSTANT
4904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004905 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004906#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004907 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4908 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004909#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004910#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004911 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4912 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004913#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004914 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02004915 PY_SSL_VERSION_TLS);
4916 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4917 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004918 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4919 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004920#if HAVE_TLSv1_2
4921 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4922 PY_SSL_VERSION_TLS1_1);
4923 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4924 PY_SSL_VERSION_TLS1_2);
4925#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004926
Antoine Pitroub5218772010-05-21 09:56:06 +00004927 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004928 PyModule_AddIntConstant(m, "OP_ALL",
4929 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004930 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4931 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4932 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004933#if HAVE_TLSv1_2
4934 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4935 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4936#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004937 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4938 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004939 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004940#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004941 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004942#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004943#ifdef SSL_OP_NO_COMPRESSION
4944 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4945 SSL_OP_NO_COMPRESSION);
4946#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004947
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004948#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004949 r = Py_True;
4950#else
4951 r = Py_False;
4952#endif
4953 Py_INCREF(r);
4954 PyModule_AddObject(m, "HAS_SNI", r);
4955
Antoine Pitroud6494802011-07-21 01:11:30 +02004956 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004957 Py_INCREF(r);
4958 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4959
Antoine Pitrou501da612011-12-21 09:27:41 +01004960#ifdef OPENSSL_NO_ECDH
4961 r = Py_False;
4962#else
4963 r = Py_True;
4964#endif
4965 Py_INCREF(r);
4966 PyModule_AddObject(m, "HAS_ECDH", r);
4967
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004968#ifdef OPENSSL_NPN_NEGOTIATED
4969 r = Py_True;
4970#else
4971 r = Py_False;
4972#endif
4973 Py_INCREF(r);
4974 PyModule_AddObject(m, "HAS_NPN", r);
4975
Benjamin Petersoncca27322015-01-23 16:35:37 -05004976#ifdef HAVE_ALPN
4977 r = Py_True;
4978#else
4979 r = Py_False;
4980#endif
4981 Py_INCREF(r);
4982 PyModule_AddObject(m, "HAS_ALPN", r);
4983
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004984 /* Mappings for error codes */
4985 err_codes_to_names = PyDict_New();
4986 err_names_to_codes = PyDict_New();
4987 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4988 return NULL;
4989 errcode = error_codes;
4990 while (errcode->mnemonic != NULL) {
4991 PyObject *mnemo, *key;
4992 mnemo = PyUnicode_FromString(errcode->mnemonic);
4993 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4994 if (mnemo == NULL || key == NULL)
4995 return NULL;
4996 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4997 return NULL;
4998 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4999 return NULL;
5000 Py_DECREF(key);
5001 Py_DECREF(mnemo);
5002 errcode++;
5003 }
5004 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5005 return NULL;
5006 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5007 return NULL;
5008
5009 lib_codes_to_names = PyDict_New();
5010 if (lib_codes_to_names == NULL)
5011 return NULL;
5012 libcode = library_codes;
5013 while (libcode->library != NULL) {
5014 PyObject *mnemo, *key;
5015 key = PyLong_FromLong(libcode->code);
5016 mnemo = PyUnicode_FromString(libcode->library);
5017 if (key == NULL || mnemo == NULL)
5018 return NULL;
5019 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5020 return NULL;
5021 Py_DECREF(key);
5022 Py_DECREF(mnemo);
5023 libcode++;
5024 }
5025 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5026 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005028 /* OpenSSL version */
5029 /* SSLeay() gives us the version of the library linked against,
5030 which could be different from the headers version.
5031 */
5032 libver = SSLeay();
5033 r = PyLong_FromUnsignedLong(libver);
5034 if (r == NULL)
5035 return NULL;
5036 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5037 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005038 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005039 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5040 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5041 return NULL;
5042 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5043 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5044 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005045
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005046 libver = OPENSSL_VERSION_NUMBER;
5047 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5048 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5049 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5050 return NULL;
5051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005052 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005053}