blob: dcfa95ae82b0c487fac8b633e5fda44372dff5ea [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 Heimes824f7f32013-08-17 00:54:47 +02001010 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001012 switch (gntype) {
1013 /* check for new general name type */
1014 case GEN_OTHERNAME:
1015 case GEN_X400:
1016 case GEN_EDIPARTY:
1017 case GEN_IPADD:
1018 case GEN_RID:
1019 break;
1020 default:
1021 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1022 "Unknown general name type %d",
1023 gntype) == -1) {
1024 goto fail;
1025 }
1026 break;
1027 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 (void) BIO_reset(biobuf);
1029 GENERAL_NAME_print(biobuf, name);
1030 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1031 if (len < 0) {
1032 _setSSLError(NULL, 0, __FILE__, __LINE__);
1033 goto fail;
1034 }
1035 vptr = strchr(buf, ':');
1036 if (vptr == NULL)
1037 goto fail;
1038 t = PyTuple_New(2);
1039 if (t == NULL)
1040 goto fail;
1041 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1042 if (v == NULL) {
1043 Py_DECREF(t);
1044 goto fail;
1045 }
1046 PyTuple_SET_ITEM(t, 0, v);
1047 v = PyUnicode_FromStringAndSize((vptr + 1),
1048 (len - (vptr - buf + 1)));
1049 if (v == NULL) {
1050 Py_DECREF(t);
1051 goto fail;
1052 }
1053 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001054 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 if (PyList_Append(peer_alt_names, t) < 0) {
1060 Py_DECREF(t);
1061 goto fail;
1062 }
1063 Py_DECREF(t);
1064 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001065 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 }
1067 BIO_free(biobuf);
1068 if (peer_alt_names != Py_None) {
1069 v = PyList_AsTuple(peer_alt_names);
1070 Py_DECREF(peer_alt_names);
1071 return v;
1072 } else {
1073 return peer_alt_names;
1074 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001075
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076
1077 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 if (biobuf != NULL)
1079 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 if (peer_alt_names != Py_None) {
1082 Py_XDECREF(peer_alt_names);
1083 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001086}
1087
1088static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001089_get_aia_uri(X509 *certificate, int nid) {
1090 PyObject *lst = NULL, *ostr = NULL;
1091 int i, result;
1092 AUTHORITY_INFO_ACCESS *info;
1093
1094 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001095 if (info == NULL)
1096 return Py_None;
1097 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1098 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001099 return Py_None;
1100 }
1101
1102 if ((lst = PyList_New(0)) == NULL) {
1103 goto fail;
1104 }
1105
1106 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1107 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1108 ASN1_IA5STRING *uri;
1109
1110 if ((OBJ_obj2nid(ad->method) != nid) ||
1111 (ad->location->type != GEN_URI)) {
1112 continue;
1113 }
1114 uri = ad->location->d.uniformResourceIdentifier;
1115 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1116 uri->length);
1117 if (ostr == NULL) {
1118 goto fail;
1119 }
1120 result = PyList_Append(lst, ostr);
1121 Py_DECREF(ostr);
1122 if (result < 0) {
1123 goto fail;
1124 }
1125 }
1126 AUTHORITY_INFO_ACCESS_free(info);
1127
1128 /* convert to tuple or None */
1129 if (PyList_Size(lst) == 0) {
1130 Py_DECREF(lst);
1131 return Py_None;
1132 } else {
1133 PyObject *tup;
1134 tup = PyList_AsTuple(lst);
1135 Py_DECREF(lst);
1136 return tup;
1137 }
1138
1139 fail:
1140 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001141 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001142 return NULL;
1143}
1144
1145static PyObject *
1146_get_crl_dp(X509 *certificate) {
1147 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001148 int i, j;
1149 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001150
Christian Heimes598894f2016-09-05 23:19:05 +02001151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001152 /* Calls x509v3_cache_extensions and sets up crldp */
1153 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001154#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001155 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001156
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001157 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001158 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001159
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001160 lst = PyList_New(0);
1161 if (lst == NULL)
1162 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001163
1164 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1165 DIST_POINT *dp;
1166 STACK_OF(GENERAL_NAME) *gns;
1167
1168 dp = sk_DIST_POINT_value(dps, i);
1169 gns = dp->distpoint->name.fullname;
1170
1171 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1172 GENERAL_NAME *gn;
1173 ASN1_IA5STRING *uri;
1174 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001175 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001176
1177 gn = sk_GENERAL_NAME_value(gns, j);
1178 if (gn->type != GEN_URI) {
1179 continue;
1180 }
1181 uri = gn->d.uniformResourceIdentifier;
1182 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1183 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001184 if (ouri == NULL)
1185 goto done;
1186
1187 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001188 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001189 if (err < 0)
1190 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001191 }
1192 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001193
1194 /* Convert to tuple. */
1195 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1196
1197 done:
1198 Py_XDECREF(lst);
1199#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001200 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001201#endif
1202 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001203}
1204
1205static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001206_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 PyObject *retval = NULL;
1209 BIO *biobuf = NULL;
1210 PyObject *peer;
1211 PyObject *peer_alt_names = NULL;
1212 PyObject *issuer;
1213 PyObject *version;
1214 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001215 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 ASN1_INTEGER *serialNumber;
1217 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001218 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 ASN1_TIME *notBefore, *notAfter;
1220 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 retval = PyDict_New();
1223 if (retval == NULL)
1224 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 peer = _create_tuple_for_X509_NAME(
1227 X509_get_subject_name(certificate));
1228 if (peer == NULL)
1229 goto fail0;
1230 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1231 Py_DECREF(peer);
1232 goto fail0;
1233 }
1234 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001235
Antoine Pitroufb046912010-11-09 20:21:19 +00001236 issuer = _create_tuple_for_X509_NAME(
1237 X509_get_issuer_name(certificate));
1238 if (issuer == NULL)
1239 goto fail0;
1240 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001242 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001244 Py_DECREF(issuer);
1245
1246 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001247 if (version == NULL)
1248 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001249 if (PyDict_SetItemString(retval, "version", version) < 0) {
1250 Py_DECREF(version);
1251 goto fail0;
1252 }
1253 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 /* get a memory buffer */
1256 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001257
Antoine Pitroufb046912010-11-09 20:21:19 +00001258 (void) BIO_reset(biobuf);
1259 serialNumber = X509_get_serialNumber(certificate);
1260 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1261 i2a_ASN1_INTEGER(biobuf, serialNumber);
1262 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1263 if (len < 0) {
1264 _setSSLError(NULL, 0, __FILE__, __LINE__);
1265 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001267 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1268 if (sn_obj == NULL)
1269 goto fail1;
1270 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1271 Py_DECREF(sn_obj);
1272 goto fail1;
1273 }
1274 Py_DECREF(sn_obj);
1275
1276 (void) BIO_reset(biobuf);
1277 notBefore = X509_get_notBefore(certificate);
1278 ASN1_TIME_print(biobuf, notBefore);
1279 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1280 if (len < 0) {
1281 _setSSLError(NULL, 0, __FILE__, __LINE__);
1282 goto fail1;
1283 }
1284 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1285 if (pnotBefore == NULL)
1286 goto fail1;
1287 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1288 Py_DECREF(pnotBefore);
1289 goto fail1;
1290 }
1291 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 (void) BIO_reset(biobuf);
1294 notAfter = X509_get_notAfter(certificate);
1295 ASN1_TIME_print(biobuf, notAfter);
1296 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1297 if (len < 0) {
1298 _setSSLError(NULL, 0, __FILE__, __LINE__);
1299 goto fail1;
1300 }
1301 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1302 if (pnotAfter == NULL)
1303 goto fail1;
1304 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1305 Py_DECREF(pnotAfter);
1306 goto fail1;
1307 }
1308 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 peer_alt_names = _get_peer_alt_names(certificate);
1313 if (peer_alt_names == NULL)
1314 goto fail1;
1315 else if (peer_alt_names != Py_None) {
1316 if (PyDict_SetItemString(retval, "subjectAltName",
1317 peer_alt_names) < 0) {
1318 Py_DECREF(peer_alt_names);
1319 goto fail1;
1320 }
1321 Py_DECREF(peer_alt_names);
1322 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001323
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001324 /* Authority Information Access: OCSP URIs */
1325 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1326 if (obj == NULL) {
1327 goto fail1;
1328 } else if (obj != Py_None) {
1329 result = PyDict_SetItemString(retval, "OCSP", obj);
1330 Py_DECREF(obj);
1331 if (result < 0) {
1332 goto fail1;
1333 }
1334 }
1335
1336 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1337 if (obj == NULL) {
1338 goto fail1;
1339 } else if (obj != Py_None) {
1340 result = PyDict_SetItemString(retval, "caIssuers", obj);
1341 Py_DECREF(obj);
1342 if (result < 0) {
1343 goto fail1;
1344 }
1345 }
1346
1347 /* CDP (CRL distribution points) */
1348 obj = _get_crl_dp(certificate);
1349 if (obj == NULL) {
1350 goto fail1;
1351 } else if (obj != Py_None) {
1352 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1353 Py_DECREF(obj);
1354 if (result < 0) {
1355 goto fail1;
1356 }
1357 }
1358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 BIO_free(biobuf);
1360 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001361
1362 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 if (biobuf != NULL)
1364 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001365 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 Py_XDECREF(retval);
1367 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001368}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001369
Christian Heimes9a5395a2013-06-17 15:44:12 +02001370static PyObject *
1371_certificate_to_der(X509 *certificate)
1372{
1373 unsigned char *bytes_buf = NULL;
1374 int len;
1375 PyObject *retval;
1376
1377 bytes_buf = NULL;
1378 len = i2d_X509(certificate, &bytes_buf);
1379 if (len < 0) {
1380 _setSSLError(NULL, 0, __FILE__, __LINE__);
1381 return NULL;
1382 }
1383 /* this is actually an immutable bytes sequence */
1384 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1385 OPENSSL_free(bytes_buf);
1386 return retval;
1387}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001389/*[clinic input]
1390_ssl._test_decode_cert
1391 path: object(converter="PyUnicode_FSConverter")
1392 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001394[clinic start generated code]*/
1395
1396static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001397_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1398/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001399{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 X509 *x=NULL;
1402 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1405 PyErr_SetString(PySSLErrorObject,
1406 "Can't malloc memory to read file");
1407 goto fail0;
1408 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001410 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 PyErr_SetString(PySSLErrorObject,
1412 "Can't open file");
1413 goto fail0;
1414 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001415
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1417 if (x == NULL) {
1418 PyErr_SetString(PySSLErrorObject,
1419 "Error decoding PEM-encoded file");
1420 goto fail0;
1421 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422
Antoine Pitroufb046912010-11-09 20:21:19 +00001423 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001424 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425
1426 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001427 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 if (cert != NULL) BIO_free(cert);
1429 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001430}
1431
1432
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001433/*[clinic input]
1434_ssl._SSLSocket.peer_certificate
1435 der as binary_mode: bool = False
1436 /
1437
1438Returns the certificate for the peer.
1439
1440If no certificate was provided, returns None. If a certificate was
1441provided, but not validated, returns an empty dictionary. Otherwise
1442returns a dict containing information about the peer certificate.
1443
1444If the optional argument is True, returns a DER-encoded copy of the
1445peer certificate, or None if no certificate was provided. This will
1446return the certificate even if it wasn't validated.
1447[clinic start generated code]*/
1448
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001450_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1451/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001452{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001454
Antoine Pitrou20b85552013-09-29 19:50:53 +02001455 if (!self->handshake_done) {
1456 PyErr_SetString(PyExc_ValueError,
1457 "handshake not done yet");
1458 return NULL;
1459 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 if (!self->peer_cert)
1461 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001462
Antoine Pitrou721738f2012-08-15 23:20:39 +02001463 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001465 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001467 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001468 if ((verification & SSL_VERIFY_PEER) == 0)
1469 return PyDict_New();
1470 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001471 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473}
1474
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001475static PyObject *
1476cipher_to_tuple(const SSL_CIPHER *cipher)
1477{
1478 const char *cipher_name, *cipher_protocol;
1479 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 if (retval == NULL)
1481 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001483 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001485 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 PyTuple_SET_ITEM(retval, 0, Py_None);
1487 } else {
1488 v = PyUnicode_FromString(cipher_name);
1489 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001490 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 PyTuple_SET_ITEM(retval, 0, v);
1492 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001493
1494 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001496 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 PyTuple_SET_ITEM(retval, 1, Py_None);
1498 } else {
1499 v = PyUnicode_FromString(cipher_protocol);
1500 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001501 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 PyTuple_SET_ITEM(retval, 1, v);
1503 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001504
1505 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001507 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001511
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001512 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 Py_DECREF(retval);
1514 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515}
1516
Christian Heimes25bfcd52016-09-06 00:04:45 +02001517#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1518static PyObject *
1519cipher_to_dict(const SSL_CIPHER *cipher)
1520{
1521 const char *cipher_name, *cipher_protocol;
1522
1523 unsigned long cipher_id;
1524 int alg_bits, strength_bits, len;
1525 char buf[512] = {0};
1526#if OPENSSL_VERSION_1_1
1527 int aead, nid;
1528 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1529#endif
1530 PyObject *retval;
1531
1532 retval = PyDict_New();
1533 if (retval == NULL) {
1534 goto error;
1535 }
1536
1537 /* can be NULL */
1538 cipher_name = SSL_CIPHER_get_name(cipher);
1539 cipher_protocol = SSL_CIPHER_get_version(cipher);
1540 cipher_id = SSL_CIPHER_get_id(cipher);
1541 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1542 len = strlen(buf);
1543 if (len > 1 && buf[len-1] == '\n')
1544 buf[len-1] = '\0';
1545 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1546
1547#if OPENSSL_VERSION_1_1
1548 aead = SSL_CIPHER_is_aead(cipher);
1549 nid = SSL_CIPHER_get_cipher_nid(cipher);
1550 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1551 nid = SSL_CIPHER_get_digest_nid(cipher);
1552 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1553 nid = SSL_CIPHER_get_kx_nid(cipher);
1554 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1555 nid = SSL_CIPHER_get_auth_nid(cipher);
1556 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1557#endif
1558
1559 retval = Py_BuildValue(
1560 "{sksssssssisi"
1561#if OPENSSL_VERSION_1_1
1562 "sOssssssss"
1563#endif
1564 "}",
1565 "id", cipher_id,
1566 "name", cipher_name,
1567 "protocol", cipher_protocol,
1568 "description", buf,
1569 "strength_bits", strength_bits,
1570 "alg_bits", alg_bits
1571#if OPENSSL_VERSION_1_1
1572 ,"aead", aead ? Py_True : Py_False,
1573 "symmetric", skcipher,
1574 "digest", digest,
1575 "kea", kx,
1576 "auth", auth
1577#endif
1578 );
1579 return retval;
1580
1581 error:
1582 Py_XDECREF(retval);
1583 return NULL;
1584}
1585#endif
1586
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001587/*[clinic input]
1588_ssl._SSLSocket.shared_ciphers
1589[clinic start generated code]*/
1590
1591static PyObject *
1592_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1593/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001594{
1595 STACK_OF(SSL_CIPHER) *ciphers;
1596 int i;
1597 PyObject *res;
1598
Christian Heimes598894f2016-09-05 23:19:05 +02001599 ciphers = SSL_get_ciphers(self->ssl);
1600 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001601 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001602 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1603 if (!res)
1604 return NULL;
1605 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1606 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1607 if (!tup) {
1608 Py_DECREF(res);
1609 return NULL;
1610 }
1611 PyList_SET_ITEM(res, i, tup);
1612 }
1613 return res;
1614}
1615
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001616/*[clinic input]
1617_ssl._SSLSocket.cipher
1618[clinic start generated code]*/
1619
1620static PyObject *
1621_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1622/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001623{
1624 const SSL_CIPHER *current;
1625
1626 if (self->ssl == NULL)
1627 Py_RETURN_NONE;
1628 current = SSL_get_current_cipher(self->ssl);
1629 if (current == NULL)
1630 Py_RETURN_NONE;
1631 return cipher_to_tuple(current);
1632}
1633
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001634/*[clinic input]
1635_ssl._SSLSocket.version
1636[clinic start generated code]*/
1637
1638static PyObject *
1639_ssl__SSLSocket_version_impl(PySSLSocket *self)
1640/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001641{
1642 const char *version;
1643
1644 if (self->ssl == NULL)
1645 Py_RETURN_NONE;
1646 version = SSL_get_version(self->ssl);
1647 if (!strcmp(version, "unknown"))
1648 Py_RETURN_NONE;
1649 return PyUnicode_FromString(version);
1650}
1651
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001652#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001653/*[clinic input]
1654_ssl._SSLSocket.selected_npn_protocol
1655[clinic start generated code]*/
1656
1657static PyObject *
1658_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1659/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1660{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001661 const unsigned char *out;
1662 unsigned int outlen;
1663
Victor Stinner4569cd52013-06-23 14:58:43 +02001664 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001665 &out, &outlen);
1666
1667 if (out == NULL)
1668 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001669 return PyUnicode_FromStringAndSize((char *)out, outlen);
1670}
1671#endif
1672
1673#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001674/*[clinic input]
1675_ssl._SSLSocket.selected_alpn_protocol
1676[clinic start generated code]*/
1677
1678static PyObject *
1679_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1680/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1681{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001682 const unsigned char *out;
1683 unsigned int outlen;
1684
1685 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1686
1687 if (out == NULL)
1688 Py_RETURN_NONE;
1689 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001690}
1691#endif
1692
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001693/*[clinic input]
1694_ssl._SSLSocket.compression
1695[clinic start generated code]*/
1696
1697static PyObject *
1698_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1699/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1700{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001701#ifdef OPENSSL_NO_COMP
1702 Py_RETURN_NONE;
1703#else
1704 const COMP_METHOD *comp_method;
1705 const char *short_name;
1706
1707 if (self->ssl == NULL)
1708 Py_RETURN_NONE;
1709 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001710 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001711 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001712 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001713 if (short_name == NULL)
1714 Py_RETURN_NONE;
1715 return PyUnicode_DecodeFSDefault(short_name);
1716#endif
1717}
1718
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001719static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1720 Py_INCREF(self->ctx);
1721 return self->ctx;
1722}
1723
1724static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1725 void *closure) {
1726
1727 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001728#if !HAVE_SNI
1729 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1730 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001731 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001732#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001733 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001734 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001735 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001736#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001737 } else {
1738 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1739 return -1;
1740 }
1741
1742 return 0;
1743}
1744
1745PyDoc_STRVAR(PySSL_set_context_doc,
1746"_setter_context(ctx)\n\
1747\
1748This changes the context associated with the SSLSocket. This is typically\n\
1749used from within a callback function set by the set_servername_callback\n\
1750on the SSLContext to change the certificate information associated with the\n\
1751SSLSocket before the cryptographic exchange handshake messages\n");
1752
1753
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001754static PyObject *
1755PySSL_get_server_side(PySSLSocket *self, void *c)
1756{
1757 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1758}
1759
1760PyDoc_STRVAR(PySSL_get_server_side_doc,
1761"Whether this is a server-side socket.");
1762
1763static PyObject *
1764PySSL_get_server_hostname(PySSLSocket *self, void *c)
1765{
1766 if (self->server_hostname == NULL)
1767 Py_RETURN_NONE;
1768 Py_INCREF(self->server_hostname);
1769 return self->server_hostname;
1770}
1771
1772PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1773"The currently set server hostname (for SNI).");
1774
1775static PyObject *
1776PySSL_get_owner(PySSLSocket *self, void *c)
1777{
1778 PyObject *owner;
1779
1780 if (self->owner == NULL)
1781 Py_RETURN_NONE;
1782
1783 owner = PyWeakref_GetObject(self->owner);
1784 Py_INCREF(owner);
1785 return owner;
1786}
1787
1788static int
1789PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1790{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001791 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001792 if (self->owner == NULL)
1793 return -1;
1794 return 0;
1795}
1796
1797PyDoc_STRVAR(PySSL_get_owner_doc,
1798"The Python-level owner of this object.\
1799Passed as \"self\" in servername callback.");
1800
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001801
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001803{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 if (self->peer_cert) /* Possible not to have one? */
1805 X509_free (self->peer_cert);
1806 if (self->ssl)
1807 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001809 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001810 Py_XDECREF(self->server_hostname);
1811 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001813}
1814
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001815/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001816 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001817 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001818 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001819
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001820static int
Victor Stinner14690702015-04-06 22:46:13 +02001821PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001822{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001823 int rc;
1824#ifdef HAVE_POLL
1825 struct pollfd pollfd;
1826 _PyTime_t ms;
1827#else
1828 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 fd_set fds;
1830 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001831#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001834 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001836 else if (timeout < 0) {
1837 if (s->sock_timeout > 0)
1838 return SOCKET_HAS_TIMED_OUT;
1839 else
1840 return SOCKET_IS_BLOCKING;
1841 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001844 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 /* Prefer poll, if available, since you can poll() any fd
1848 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001849#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001850 pollfd.fd = s->sock_fd;
1851 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001852
Victor Stinner14690702015-04-06 22:46:13 +02001853 /* timeout is in seconds, poll() uses milliseconds */
1854 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001855 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001856
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001857 PySSL_BEGIN_ALLOW_THREADS
1858 rc = poll(&pollfd, 1, (int)ms);
1859 PySSL_END_ALLOW_THREADS
1860#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001862 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001864
Victor Stinner14690702015-04-06 22:46:13 +02001865 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 FD_ZERO(&fds);
1868 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001869
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001870 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001872 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001874 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001876 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001878#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1881 (when we are able to write or when there's something to read) */
1882 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001883}
1884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001885/*[clinic input]
1886_ssl._SSLSocket.write
1887 b: Py_buffer
1888 /
1889
1890Writes the bytes-like object b into the SSL object.
1891
1892Returns the number of bytes written.
1893[clinic start generated code]*/
1894
1895static PyObject *
1896_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1897/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001898{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 int len;
1900 int sockstate;
1901 int err;
1902 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001903 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001904 _PyTime_t timeout, deadline = 0;
1905 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001906
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001907 if (sock != NULL) {
1908 if (((PyObject*)sock) == Py_None) {
1909 _setSSLError("Underlying socket connection gone",
1910 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1911 return NULL;
1912 }
1913 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 }
1915
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001916 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001917 PyErr_Format(PyExc_OverflowError,
1918 "string longer than %d bytes", INT_MAX);
1919 goto error;
1920 }
1921
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001922 if (sock != NULL) {
1923 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001924 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001925 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1926 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1927 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928
Victor Stinner14690702015-04-06 22:46:13 +02001929 timeout = GET_SOCKET_TIMEOUT(sock);
1930 has_timeout = (timeout > 0);
1931 if (has_timeout)
1932 deadline = _PyTime_GetMonotonicClock() + timeout;
1933
1934 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001936 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001937 "The write operation timed out");
1938 goto error;
1939 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1940 PyErr_SetString(PySSLErrorObject,
1941 "Underlying socket has been closed.");
1942 goto error;
1943 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1944 PyErr_SetString(PySSLErrorObject,
1945 "Underlying socket too large for select().");
1946 goto error;
1947 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001951 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 err = SSL_get_error(self->ssl, len);
1953 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001954
1955 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001957
Victor Stinner14690702015-04-06 22:46:13 +02001958 if (has_timeout)
1959 timeout = deadline - _PyTime_GetMonotonicClock();
1960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001962 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001964 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 } else {
1966 sockstate = SOCKET_OPERATION_OK;
1967 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001970 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 "The write operation timed out");
1972 goto error;
1973 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1974 PyErr_SetString(PySSLErrorObject,
1975 "Underlying socket has been closed.");
1976 goto error;
1977 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1978 break;
1979 }
1980 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001981
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001982 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 if (len > 0)
1984 return PyLong_FromLong(len);
1985 else
1986 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001987
1988error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001989 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001990 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001991}
1992
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001993/*[clinic input]
1994_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001995
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001996Returns the number of already decrypted bytes available for read, pending on the connection.
1997[clinic start generated code]*/
1998
1999static PyObject *
2000_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2001/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002002{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 PySSL_BEGIN_ALLOW_THREADS
2006 count = SSL_pending(self->ssl);
2007 PySSL_END_ALLOW_THREADS
2008 if (count < 0)
2009 return PySSL_SetError(self, count, __FILE__, __LINE__);
2010 else
2011 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002012}
2013
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002014/*[clinic input]
2015_ssl._SSLSocket.read
2016 size as len: int
2017 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002018 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002019 ]
2020 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002021
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002022Read up to size bytes from the SSL socket.
2023[clinic start generated code]*/
2024
2025static PyObject *
2026_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2027 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002028/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002029{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002030 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002031 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002032 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002033 int sockstate;
2034 int err;
2035 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002036 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002037 _PyTime_t timeout, deadline = 0;
2038 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002039
Martin Panter5503d472016-03-27 05:35:19 +00002040 if (!group_right_1 && len < 0) {
2041 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2042 return NULL;
2043 }
2044
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002045 if (sock != NULL) {
2046 if (((PyObject*)sock) == Py_None) {
2047 _setSSLError("Underlying socket connection gone",
2048 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2049 return NULL;
2050 }
2051 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 }
2053
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002054 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002055 dest = PyBytes_FromStringAndSize(NULL, len);
2056 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002057 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002058 if (len == 0) {
2059 Py_XDECREF(sock);
2060 return dest;
2061 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002062 mem = PyBytes_AS_STRING(dest);
2063 }
2064 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065 mem = buffer->buf;
2066 if (len <= 0 || len > buffer->len) {
2067 len = (int) buffer->len;
2068 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002069 PyErr_SetString(PyExc_OverflowError,
2070 "maximum length can't fit in a C 'int'");
2071 goto error;
2072 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002073 if (len == 0) {
2074 count = 0;
2075 goto done;
2076 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002077 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 }
2079
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002080 if (sock != NULL) {
2081 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002082 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002083 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2084 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2085 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086
Victor Stinner14690702015-04-06 22:46:13 +02002087 timeout = GET_SOCKET_TIMEOUT(sock);
2088 has_timeout = (timeout > 0);
2089 if (has_timeout)
2090 deadline = _PyTime_GetMonotonicClock() + timeout;
2091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002092 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 PySSL_BEGIN_ALLOW_THREADS
2094 count = SSL_read(self->ssl, mem, len);
2095 err = SSL_get_error(self->ssl, count);
2096 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 if (PyErr_CheckSignals())
2099 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002100
Victor Stinner14690702015-04-06 22:46:13 +02002101 if (has_timeout)
2102 timeout = deadline - _PyTime_GetMonotonicClock();
2103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002104 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002105 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002107 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002108 } else if (err == SSL_ERROR_ZERO_RETURN &&
2109 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002110 {
2111 count = 0;
2112 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002114 else
2115 sockstate = SOCKET_OPERATION_OK;
2116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002117 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002118 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 "The read operation timed out");
2120 goto error;
2121 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2122 break;
2123 }
2124 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002126 if (count <= 0) {
2127 PySSL_SetError(self, count, __FILE__, __LINE__);
2128 goto error;
2129 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002130
2131done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002132 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002133 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002134 _PyBytes_Resize(&dest, count);
2135 return dest;
2136 }
2137 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 return PyLong_FromLong(count);
2139 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002140
2141error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002143 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002144 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002146}
2147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002148/*[clinic input]
2149_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002151Does the SSL shutdown handshake with the remote end.
2152
2153Returns the underlying socket object.
2154[clinic start generated code]*/
2155
2156static PyObject *
2157_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2158/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002159{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 int err, ssl_err, sockstate, nonblocking;
2161 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002162 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002163 _PyTime_t timeout, deadline = 0;
2164 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002165
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002166 if (sock != NULL) {
2167 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002168 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002169 _setSSLError("Underlying socket connection gone",
2170 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2171 return NULL;
2172 }
2173 Py_INCREF(sock);
2174
2175 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002176 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002177 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2178 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180
Victor Stinner14690702015-04-06 22:46:13 +02002181 timeout = GET_SOCKET_TIMEOUT(sock);
2182 has_timeout = (timeout > 0);
2183 if (has_timeout)
2184 deadline = _PyTime_GetMonotonicClock() + timeout;
2185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 while (1) {
2187 PySSL_BEGIN_ALLOW_THREADS
2188 /* Disable read-ahead so that unwrap can work correctly.
2189 * Otherwise OpenSSL might read in too much data,
2190 * eating clear text data that happens to be
2191 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002192 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 * function is used and the shutdown_seen_zero != 0
2194 * condition is met.
2195 */
2196 if (self->shutdown_seen_zero)
2197 SSL_set_read_ahead(self->ssl, 0);
2198 err = SSL_shutdown(self->ssl);
2199 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2202 if (err > 0)
2203 break;
2204 if (err == 0) {
2205 /* Don't loop endlessly; instead preserve legacy
2206 behaviour of trying SSL_shutdown() only twice.
2207 This looks necessary for OpenSSL < 0.9.8m */
2208 if (++zeros > 1)
2209 break;
2210 /* Shutdown was sent, now try receiving */
2211 self->shutdown_seen_zero = 1;
2212 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002213 }
2214
Victor Stinner14690702015-04-06 22:46:13 +02002215 if (has_timeout)
2216 timeout = deadline - _PyTime_GetMonotonicClock();
2217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002218 /* Possibly retry shutdown until timeout or failure */
2219 ssl_err = SSL_get_error(self->ssl, err);
2220 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002221 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002223 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 else
2225 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2228 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002229 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 "The read operation timed out");
2231 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002232 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002234 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 }
2236 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2237 PyErr_SetString(PySSLErrorObject,
2238 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002239 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 }
2241 else if (sockstate != SOCKET_OPERATION_OK)
2242 /* Retain the SSL error code */
2243 break;
2244 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002245
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002246 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002247 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002250 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002251 /* It's already INCREF'ed */
2252 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002253 else
2254 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002255
2256error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002257 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002258 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002259}
2260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002261/*[clinic input]
2262_ssl._SSLSocket.tls_unique_cb
2263
2264Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2265
2266If the TLS handshake is not yet complete, None is returned.
2267[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002268
Antoine Pitroud6494802011-07-21 01:11:30 +02002269static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002270_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2271/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002272{
2273 PyObject *retval = NULL;
2274 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002275 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002276
2277 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2278 /* if session is resumed XOR we are the client */
2279 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2280 }
2281 else {
2282 /* if a new session XOR we are the server */
2283 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2284 }
2285
2286 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002287 if (len == 0)
2288 Py_RETURN_NONE;
2289
2290 retval = PyBytes_FromStringAndSize(buf, len);
2291
2292 return retval;
2293}
2294
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002295static PyGetSetDef ssl_getsetlist[] = {
2296 {"context", (getter) PySSL_get_context,
2297 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002298 {"server_side", (getter) PySSL_get_server_side, NULL,
2299 PySSL_get_server_side_doc},
2300 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2301 PySSL_get_server_hostname_doc},
2302 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2303 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002304 {NULL}, /* sentinel */
2305};
2306
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002307static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002308 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2309 _SSL__SSLSOCKET_WRITE_METHODDEF
2310 _SSL__SSLSOCKET_READ_METHODDEF
2311 _SSL__SSLSOCKET_PENDING_METHODDEF
2312 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2313 _SSL__SSLSOCKET_CIPHER_METHODDEF
2314 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2315 _SSL__SSLSOCKET_VERSION_METHODDEF
2316 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2317 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2318 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2319 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2320 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002322};
2323
Antoine Pitrou152efa22010-05-16 18:19:27 +00002324static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002326 "_ssl._SSLSocket", /*tp_name*/
2327 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 0, /*tp_itemsize*/
2329 /* methods */
2330 (destructor)PySSL_dealloc, /*tp_dealloc*/
2331 0, /*tp_print*/
2332 0, /*tp_getattr*/
2333 0, /*tp_setattr*/
2334 0, /*tp_reserved*/
2335 0, /*tp_repr*/
2336 0, /*tp_as_number*/
2337 0, /*tp_as_sequence*/
2338 0, /*tp_as_mapping*/
2339 0, /*tp_hash*/
2340 0, /*tp_call*/
2341 0, /*tp_str*/
2342 0, /*tp_getattro*/
2343 0, /*tp_setattro*/
2344 0, /*tp_as_buffer*/
2345 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2346 0, /*tp_doc*/
2347 0, /*tp_traverse*/
2348 0, /*tp_clear*/
2349 0, /*tp_richcompare*/
2350 0, /*tp_weaklistoffset*/
2351 0, /*tp_iter*/
2352 0, /*tp_iternext*/
2353 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002354 0, /*tp_members*/
2355 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002356};
2357
Antoine Pitrou152efa22010-05-16 18:19:27 +00002358
2359/*
2360 * _SSLContext objects
2361 */
2362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002363/*[clinic input]
2364@classmethod
2365_ssl._SSLContext.__new__
2366 protocol as proto_version: int
2367 /
2368[clinic start generated code]*/
2369
Antoine Pitrou152efa22010-05-16 18:19:27 +00002370static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2372/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002373{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002374 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002375 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002376 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002377#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002378 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002379#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002380
Antoine Pitrou152efa22010-05-16 18:19:27 +00002381 PySSL_BEGIN_ALLOW_THREADS
2382 if (proto_version == PY_SSL_VERSION_TLS1)
2383 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002384#if HAVE_TLSv1_2
2385 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2386 ctx = SSL_CTX_new(TLSv1_1_method());
2387 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2388 ctx = SSL_CTX_new(TLSv1_2_method());
2389#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002390#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002391 else if (proto_version == PY_SSL_VERSION_SSL3)
2392 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002393#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002394#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002395 else if (proto_version == PY_SSL_VERSION_SSL2)
2396 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002397#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002398 else if (proto_version == PY_SSL_VERSION_TLS)
2399 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 else
2401 proto_version = -1;
2402 PySSL_END_ALLOW_THREADS
2403
2404 if (proto_version == -1) {
2405 PyErr_SetString(PyExc_ValueError,
2406 "invalid protocol version");
2407 return NULL;
2408 }
2409 if (ctx == NULL) {
2410 PyErr_SetString(PySSLErrorObject,
2411 "failed to allocate SSL context");
2412 return NULL;
2413 }
2414
2415 assert(type != NULL && type->tp_alloc != NULL);
2416 self = (PySSLContext *) type->tp_alloc(type, 0);
2417 if (self == NULL) {
2418 SSL_CTX_free(ctx);
2419 return NULL;
2420 }
2421 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002422#ifdef OPENSSL_NPN_NEGOTIATED
2423 self->npn_protocols = NULL;
2424#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002425#ifdef HAVE_ALPN
2426 self->alpn_protocols = NULL;
2427#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002428#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002429 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002430#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002431 /* Don't check host name by default */
2432 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002433 /* Defaults */
2434 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002435 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2436 if (proto_version != PY_SSL_VERSION_SSL2)
2437 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002438 if (proto_version != PY_SSL_VERSION_SSL3)
2439 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002440 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002441
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002442#if defined(SSL_MODE_RELEASE_BUFFERS)
2443 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2444 usage for no cost at all. However, don't do this for OpenSSL versions
2445 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2446 2014-0198. I can't find exactly which beta fixed this CVE, so be
2447 conservative and assume it wasn't fixed until release. We do this check
2448 at runtime to avoid problems from the dynamic linker.
2449 See #25672 for more on this. */
2450 libver = SSLeay();
2451 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2452 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2453 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2454 }
2455#endif
2456
2457
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002458#ifndef OPENSSL_NO_ECDH
2459 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2460 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002461 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2462 */
2463#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002464 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2465#else
2466 {
2467 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2468 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2469 EC_KEY_free(key);
2470 }
2471#endif
2472#endif
2473
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002474#define SID_CTX "Python"
2475 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2476 sizeof(SID_CTX));
2477#undef SID_CTX
2478
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002479#ifdef X509_V_FLAG_TRUSTED_FIRST
2480 {
2481 /* Improve trust chain building when cross-signed intermediate
2482 certificates are present. See https://bugs.python.org/issue23476. */
2483 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2484 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2485 }
2486#endif
2487
Antoine Pitrou152efa22010-05-16 18:19:27 +00002488 return (PyObject *)self;
2489}
2490
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002491static int
2492context_traverse(PySSLContext *self, visitproc visit, void *arg)
2493{
2494#ifndef OPENSSL_NO_TLSEXT
2495 Py_VISIT(self->set_hostname);
2496#endif
2497 return 0;
2498}
2499
2500static int
2501context_clear(PySSLContext *self)
2502{
2503#ifndef OPENSSL_NO_TLSEXT
2504 Py_CLEAR(self->set_hostname);
2505#endif
2506 return 0;
2507}
2508
Antoine Pitrou152efa22010-05-16 18:19:27 +00002509static void
2510context_dealloc(PySSLContext *self)
2511{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002512 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002513 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002514#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002515 PyMem_FREE(self->npn_protocols);
2516#endif
2517#ifdef HAVE_ALPN
2518 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002519#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002520 Py_TYPE(self)->tp_free(self);
2521}
2522
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002523/*[clinic input]
2524_ssl._SSLContext.set_ciphers
2525 cipherlist: str
2526 /
2527[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002528
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002529static PyObject *
2530_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2531/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2532{
2533 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002534 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002535 /* Clearing the error queue is necessary on some OpenSSL versions,
2536 otherwise the error will be reported again when another SSL call
2537 is done. */
2538 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002539 PyErr_SetString(PySSLErrorObject,
2540 "No cipher can be selected.");
2541 return NULL;
2542 }
2543 Py_RETURN_NONE;
2544}
2545
Christian Heimes25bfcd52016-09-06 00:04:45 +02002546#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2547/*[clinic input]
2548_ssl._SSLContext.get_ciphers
2549[clinic start generated code]*/
2550
2551static PyObject *
2552_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2553/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2554{
2555 SSL *ssl = NULL;
2556 STACK_OF(SSL_CIPHER) *sk = NULL;
2557 SSL_CIPHER *cipher;
2558 int i=0;
2559 PyObject *result = NULL, *dct;
2560
2561 ssl = SSL_new(self->ctx);
2562 if (ssl == NULL) {
2563 _setSSLError(NULL, 0, __FILE__, __LINE__);
2564 goto exit;
2565 }
2566 sk = SSL_get_ciphers(ssl);
2567
2568 result = PyList_New(sk_SSL_CIPHER_num(sk));
2569 if (result == NULL) {
2570 goto exit;
2571 }
2572
2573 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2574 cipher = sk_SSL_CIPHER_value(sk, i);
2575 dct = cipher_to_dict(cipher);
2576 if (dct == NULL) {
2577 Py_CLEAR(result);
2578 goto exit;
2579 }
2580 PyList_SET_ITEM(result, i, dct);
2581 }
2582
2583 exit:
2584 if (ssl != NULL)
2585 SSL_free(ssl);
2586 return result;
2587
2588}
2589#endif
2590
2591
Benjamin Petersonc54de472015-01-28 12:06:39 -05002592#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002593static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002594do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2595 const unsigned char *server_protocols, unsigned int server_protocols_len,
2596 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002597{
Benjamin Peterson88615022015-01-23 17:30:26 -05002598 int ret;
2599 if (client_protocols == NULL) {
2600 client_protocols = (unsigned char *)"";
2601 client_protocols_len = 0;
2602 }
2603 if (server_protocols == NULL) {
2604 server_protocols = (unsigned char *)"";
2605 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002606 }
2607
Benjamin Peterson88615022015-01-23 17:30:26 -05002608 ret = SSL_select_next_proto(out, outlen,
2609 server_protocols, server_protocols_len,
2610 client_protocols, client_protocols_len);
2611 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2612 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002613
2614 return SSL_TLSEXT_ERR_OK;
2615}
2616
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002617/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2618static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002619_advertiseNPN_cb(SSL *s,
2620 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002621 void *args)
2622{
2623 PySSLContext *ssl_ctx = (PySSLContext *) args;
2624
2625 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002626 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002627 *len = 0;
2628 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002629 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002630 *len = ssl_ctx->npn_protocols_len;
2631 }
2632
2633 return SSL_TLSEXT_ERR_OK;
2634}
2635/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2636static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002637_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002638 unsigned char **out, unsigned char *outlen,
2639 const unsigned char *server, unsigned int server_len,
2640 void *args)
2641{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002642 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002643 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002644 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002645}
2646#endif
2647
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002648/*[clinic input]
2649_ssl._SSLContext._set_npn_protocols
2650 protos: Py_buffer
2651 /
2652[clinic start generated code]*/
2653
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002654static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002655_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2656 Py_buffer *protos)
2657/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002658{
2659#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002660 PyMem_Free(self->npn_protocols);
2661 self->npn_protocols = PyMem_Malloc(protos->len);
2662 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002663 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002664 memcpy(self->npn_protocols, protos->buf, protos->len);
2665 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002666
2667 /* set both server and client callbacks, because the context can
2668 * be used to create both types of sockets */
2669 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2670 _advertiseNPN_cb,
2671 self);
2672 SSL_CTX_set_next_proto_select_cb(self->ctx,
2673 _selectNPN_cb,
2674 self);
2675
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002676 Py_RETURN_NONE;
2677#else
2678 PyErr_SetString(PyExc_NotImplementedError,
2679 "The NPN extension requires OpenSSL 1.0.1 or later.");
2680 return NULL;
2681#endif
2682}
2683
Benjamin Petersoncca27322015-01-23 16:35:37 -05002684#ifdef HAVE_ALPN
2685static int
2686_selectALPN_cb(SSL *s,
2687 const unsigned char **out, unsigned char *outlen,
2688 const unsigned char *client_protocols, unsigned int client_protocols_len,
2689 void *args)
2690{
2691 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002692 return do_protocol_selection(1, (unsigned char **)out, outlen,
2693 ctx->alpn_protocols, ctx->alpn_protocols_len,
2694 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002695}
2696#endif
2697
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002698/*[clinic input]
2699_ssl._SSLContext._set_alpn_protocols
2700 protos: Py_buffer
2701 /
2702[clinic start generated code]*/
2703
Benjamin Petersoncca27322015-01-23 16:35:37 -05002704static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002705_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2706 Py_buffer *protos)
2707/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002708{
2709#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002710 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002711 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002712 if (!self->alpn_protocols)
2713 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002714 memcpy(self->alpn_protocols, protos->buf, protos->len);
2715 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002716
2717 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2718 return PyErr_NoMemory();
2719 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2720
Benjamin Petersoncca27322015-01-23 16:35:37 -05002721 Py_RETURN_NONE;
2722#else
2723 PyErr_SetString(PyExc_NotImplementedError,
2724 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2725 return NULL;
2726#endif
2727}
2728
Antoine Pitrou152efa22010-05-16 18:19:27 +00002729static PyObject *
2730get_verify_mode(PySSLContext *self, void *c)
2731{
2732 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2733 case SSL_VERIFY_NONE:
2734 return PyLong_FromLong(PY_SSL_CERT_NONE);
2735 case SSL_VERIFY_PEER:
2736 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2737 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2738 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2739 }
2740 PyErr_SetString(PySSLErrorObject,
2741 "invalid return value from SSL_CTX_get_verify_mode");
2742 return NULL;
2743}
2744
2745static int
2746set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2747{
2748 int n, mode;
2749 if (!PyArg_Parse(arg, "i", &n))
2750 return -1;
2751 if (n == PY_SSL_CERT_NONE)
2752 mode = SSL_VERIFY_NONE;
2753 else if (n == PY_SSL_CERT_OPTIONAL)
2754 mode = SSL_VERIFY_PEER;
2755 else if (n == PY_SSL_CERT_REQUIRED)
2756 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2757 else {
2758 PyErr_SetString(PyExc_ValueError,
2759 "invalid value for verify_mode");
2760 return -1;
2761 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002762 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2763 PyErr_SetString(PyExc_ValueError,
2764 "Cannot set verify_mode to CERT_NONE when "
2765 "check_hostname is enabled.");
2766 return -1;
2767 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002768 SSL_CTX_set_verify(self->ctx, mode, NULL);
2769 return 0;
2770}
2771
2772static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002773get_verify_flags(PySSLContext *self, void *c)
2774{
2775 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002776 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002777 unsigned long flags;
2778
2779 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002780 param = X509_STORE_get0_param(store);
2781 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002782 return PyLong_FromUnsignedLong(flags);
2783}
2784
2785static int
2786set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2787{
2788 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002789 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002790 unsigned long new_flags, flags, set, clear;
2791
2792 if (!PyArg_Parse(arg, "k", &new_flags))
2793 return -1;
2794 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002795 param = X509_STORE_get0_param(store);
2796 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002797 clear = flags & ~new_flags;
2798 set = ~flags & new_flags;
2799 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02002800 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01002801 _setSSLError(NULL, 0, __FILE__, __LINE__);
2802 return -1;
2803 }
2804 }
2805 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02002806 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01002807 _setSSLError(NULL, 0, __FILE__, __LINE__);
2808 return -1;
2809 }
2810 }
2811 return 0;
2812}
2813
2814static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002815get_options(PySSLContext *self, void *c)
2816{
2817 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2818}
2819
2820static int
2821set_options(PySSLContext *self, PyObject *arg, void *c)
2822{
2823 long new_opts, opts, set, clear;
2824 if (!PyArg_Parse(arg, "l", &new_opts))
2825 return -1;
2826 opts = SSL_CTX_get_options(self->ctx);
2827 clear = opts & ~new_opts;
2828 set = ~opts & new_opts;
2829 if (clear) {
2830#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2831 SSL_CTX_clear_options(self->ctx, clear);
2832#else
2833 PyErr_SetString(PyExc_ValueError,
2834 "can't clear options before OpenSSL 0.9.8m");
2835 return -1;
2836#endif
2837 }
2838 if (set)
2839 SSL_CTX_set_options(self->ctx, set);
2840 return 0;
2841}
2842
Christian Heimes1aa9a752013-12-02 02:41:19 +01002843static PyObject *
2844get_check_hostname(PySSLContext *self, void *c)
2845{
2846 return PyBool_FromLong(self->check_hostname);
2847}
2848
2849static int
2850set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2851{
2852 int check_hostname;
2853 if (!PyArg_Parse(arg, "p", &check_hostname))
2854 return -1;
2855 if (check_hostname &&
2856 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2857 PyErr_SetString(PyExc_ValueError,
2858 "check_hostname needs a SSL context with either "
2859 "CERT_OPTIONAL or CERT_REQUIRED");
2860 return -1;
2861 }
2862 self->check_hostname = check_hostname;
2863 return 0;
2864}
2865
2866
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002867typedef struct {
2868 PyThreadState *thread_state;
2869 PyObject *callable;
2870 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002871 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002872 int error;
2873} _PySSLPasswordInfo;
2874
2875static int
2876_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2877 const char *bad_type_error)
2878{
2879 /* Set the password and size fields of a _PySSLPasswordInfo struct
2880 from a unicode, bytes, or byte array object.
2881 The password field will be dynamically allocated and must be freed
2882 by the caller */
2883 PyObject *password_bytes = NULL;
2884 const char *data = NULL;
2885 Py_ssize_t size;
2886
2887 if (PyUnicode_Check(password)) {
2888 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2889 if (!password_bytes) {
2890 goto error;
2891 }
2892 data = PyBytes_AS_STRING(password_bytes);
2893 size = PyBytes_GET_SIZE(password_bytes);
2894 } else if (PyBytes_Check(password)) {
2895 data = PyBytes_AS_STRING(password);
2896 size = PyBytes_GET_SIZE(password);
2897 } else if (PyByteArray_Check(password)) {
2898 data = PyByteArray_AS_STRING(password);
2899 size = PyByteArray_GET_SIZE(password);
2900 } else {
2901 PyErr_SetString(PyExc_TypeError, bad_type_error);
2902 goto error;
2903 }
2904
Victor Stinner9ee02032013-06-23 15:08:23 +02002905 if (size > (Py_ssize_t)INT_MAX) {
2906 PyErr_Format(PyExc_ValueError,
2907 "password cannot be longer than %d bytes", INT_MAX);
2908 goto error;
2909 }
2910
Victor Stinner11ebff22013-07-07 17:07:52 +02002911 PyMem_Free(pw_info->password);
2912 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002913 if (!pw_info->password) {
2914 PyErr_SetString(PyExc_MemoryError,
2915 "unable to allocate password buffer");
2916 goto error;
2917 }
2918 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002919 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002920
2921 Py_XDECREF(password_bytes);
2922 return 1;
2923
2924error:
2925 Py_XDECREF(password_bytes);
2926 return 0;
2927}
2928
2929static int
2930_password_callback(char *buf, int size, int rwflag, void *userdata)
2931{
2932 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2933 PyObject *fn_ret = NULL;
2934
2935 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2936
2937 if (pw_info->callable) {
2938 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2939 if (!fn_ret) {
2940 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2941 core python API, so we could use it to add a frame here */
2942 goto error;
2943 }
2944
2945 if (!_pwinfo_set(pw_info, fn_ret,
2946 "password callback must return a string")) {
2947 goto error;
2948 }
2949 Py_CLEAR(fn_ret);
2950 }
2951
2952 if (pw_info->size > size) {
2953 PyErr_Format(PyExc_ValueError,
2954 "password cannot be longer than %d bytes", size);
2955 goto error;
2956 }
2957
2958 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2959 memcpy(buf, pw_info->password, pw_info->size);
2960 return pw_info->size;
2961
2962error:
2963 Py_XDECREF(fn_ret);
2964 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2965 pw_info->error = 1;
2966 return -1;
2967}
2968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002969/*[clinic input]
2970_ssl._SSLContext.load_cert_chain
2971 certfile: object
2972 keyfile: object = NULL
2973 password: object = NULL
2974
2975[clinic start generated code]*/
2976
Antoine Pitroub5218772010-05-21 09:56:06 +00002977static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002978_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2979 PyObject *keyfile, PyObject *password)
2980/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02002983 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2984 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002985 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986 int r;
2987
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002988 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002989 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002990 if (keyfile == Py_None)
2991 keyfile = NULL;
2992 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2993 PyErr_SetString(PyExc_TypeError,
2994 "certfile should be a valid filesystem path");
2995 return NULL;
2996 }
2997 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2998 PyErr_SetString(PyExc_TypeError,
2999 "keyfile should be a valid filesystem path");
3000 goto error;
3001 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003002 if (password && password != Py_None) {
3003 if (PyCallable_Check(password)) {
3004 pw_info.callable = password;
3005 } else if (!_pwinfo_set(&pw_info, password,
3006 "password should be a string or callable")) {
3007 goto error;
3008 }
3009 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3010 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3011 }
3012 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003013 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3014 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003015 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003016 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003017 if (pw_info.error) {
3018 ERR_clear_error();
3019 /* the password callback has already set the error information */
3020 }
3021 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003022 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003023 PyErr_SetFromErrno(PyExc_IOError);
3024 }
3025 else {
3026 _setSSLError(NULL, 0, __FILE__, __LINE__);
3027 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003028 goto error;
3029 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003030 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003031 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003032 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3033 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003034 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3035 Py_CLEAR(keyfile_bytes);
3036 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003037 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003038 if (pw_info.error) {
3039 ERR_clear_error();
3040 /* the password callback has already set the error information */
3041 }
3042 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003043 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003044 PyErr_SetFromErrno(PyExc_IOError);
3045 }
3046 else {
3047 _setSSLError(NULL, 0, __FILE__, __LINE__);
3048 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003049 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003050 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003051 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003052 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003053 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003054 if (r != 1) {
3055 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003056 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003057 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003058 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3059 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003060 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003061 Py_RETURN_NONE;
3062
3063error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003064 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3065 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003066 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003067 Py_XDECREF(keyfile_bytes);
3068 Py_XDECREF(certfile_bytes);
3069 return NULL;
3070}
3071
Christian Heimesefff7062013-11-21 03:35:02 +01003072/* internal helper function, returns -1 on error
3073 */
3074static int
3075_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3076 int filetype)
3077{
3078 BIO *biobuf = NULL;
3079 X509_STORE *store;
3080 int retval = 0, err, loaded = 0;
3081
3082 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3083
3084 if (len <= 0) {
3085 PyErr_SetString(PyExc_ValueError,
3086 "Empty certificate data");
3087 return -1;
3088 } else if (len > INT_MAX) {
3089 PyErr_SetString(PyExc_OverflowError,
3090 "Certificate data is too long.");
3091 return -1;
3092 }
3093
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003094 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003095 if (biobuf == NULL) {
3096 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3097 return -1;
3098 }
3099
3100 store = SSL_CTX_get_cert_store(self->ctx);
3101 assert(store != NULL);
3102
3103 while (1) {
3104 X509 *cert = NULL;
3105 int r;
3106
3107 if (filetype == SSL_FILETYPE_ASN1) {
3108 cert = d2i_X509_bio(biobuf, NULL);
3109 } else {
3110 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003111 SSL_CTX_get_default_passwd_cb(self->ctx),
3112 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3113 );
Christian Heimesefff7062013-11-21 03:35:02 +01003114 }
3115 if (cert == NULL) {
3116 break;
3117 }
3118 r = X509_STORE_add_cert(store, cert);
3119 X509_free(cert);
3120 if (!r) {
3121 err = ERR_peek_last_error();
3122 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3123 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3124 /* cert already in hash table, not an error */
3125 ERR_clear_error();
3126 } else {
3127 break;
3128 }
3129 }
3130 loaded++;
3131 }
3132
3133 err = ERR_peek_last_error();
3134 if ((filetype == SSL_FILETYPE_ASN1) &&
3135 (loaded > 0) &&
3136 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3137 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3138 /* EOF ASN1 file, not an error */
3139 ERR_clear_error();
3140 retval = 0;
3141 } else if ((filetype == SSL_FILETYPE_PEM) &&
3142 (loaded > 0) &&
3143 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3144 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3145 /* EOF PEM file, not an error */
3146 ERR_clear_error();
3147 retval = 0;
3148 } else {
3149 _setSSLError(NULL, 0, __FILE__, __LINE__);
3150 retval = -1;
3151 }
3152
3153 BIO_free(biobuf);
3154 return retval;
3155}
3156
3157
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003158/*[clinic input]
3159_ssl._SSLContext.load_verify_locations
3160 cafile: object = NULL
3161 capath: object = NULL
3162 cadata: object = NULL
3163
3164[clinic start generated code]*/
3165
Antoine Pitrou152efa22010-05-16 18:19:27 +00003166static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003167_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3168 PyObject *cafile,
3169 PyObject *capath,
3170 PyObject *cadata)
3171/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003172{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003173 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3174 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003175 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003176
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003177 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003178 if (cafile == Py_None)
3179 cafile = NULL;
3180 if (capath == Py_None)
3181 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003182 if (cadata == Py_None)
3183 cadata = NULL;
3184
3185 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003187 "cafile, capath and cadata cannot be all omitted");
3188 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003189 }
3190 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3191 PyErr_SetString(PyExc_TypeError,
3192 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003193 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003194 }
3195 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003196 PyErr_SetString(PyExc_TypeError,
3197 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003198 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003199 }
Christian Heimesefff7062013-11-21 03:35:02 +01003200
3201 /* validata cadata type and load cadata */
3202 if (cadata) {
3203 Py_buffer buf;
3204 PyObject *cadata_ascii = NULL;
3205
3206 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3207 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3208 PyBuffer_Release(&buf);
3209 PyErr_SetString(PyExc_TypeError,
3210 "cadata should be a contiguous buffer with "
3211 "a single dimension");
3212 goto error;
3213 }
3214 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3215 PyBuffer_Release(&buf);
3216 if (r == -1) {
3217 goto error;
3218 }
3219 } else {
3220 PyErr_Clear();
3221 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3222 if (cadata_ascii == NULL) {
3223 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003224 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003225 "bytes-like object");
3226 goto error;
3227 }
3228 r = _add_ca_certs(self,
3229 PyBytes_AS_STRING(cadata_ascii),
3230 PyBytes_GET_SIZE(cadata_ascii),
3231 SSL_FILETYPE_PEM);
3232 Py_DECREF(cadata_ascii);
3233 if (r == -1) {
3234 goto error;
3235 }
3236 }
3237 }
3238
3239 /* load cafile or capath */
3240 if (cafile || capath) {
3241 if (cafile)
3242 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3243 if (capath)
3244 capath_buf = PyBytes_AS_STRING(capath_bytes);
3245 PySSL_BEGIN_ALLOW_THREADS
3246 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3247 PySSL_END_ALLOW_THREADS
3248 if (r != 1) {
3249 ok = 0;
3250 if (errno != 0) {
3251 ERR_clear_error();
3252 PyErr_SetFromErrno(PyExc_IOError);
3253 }
3254 else {
3255 _setSSLError(NULL, 0, __FILE__, __LINE__);
3256 }
3257 goto error;
3258 }
3259 }
3260 goto end;
3261
3262 error:
3263 ok = 0;
3264 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003265 Py_XDECREF(cafile_bytes);
3266 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003267 if (ok) {
3268 Py_RETURN_NONE;
3269 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003270 return NULL;
3271 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003272}
3273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003274/*[clinic input]
3275_ssl._SSLContext.load_dh_params
3276 path as filepath: object
3277 /
3278
3279[clinic start generated code]*/
3280
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003282_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3283/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003284{
3285 FILE *f;
3286 DH *dh;
3287
Victor Stinnerdaf45552013-08-28 00:53:59 +02003288 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003289 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003290 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003291
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003292 errno = 0;
3293 PySSL_BEGIN_ALLOW_THREADS
3294 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003295 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003296 PySSL_END_ALLOW_THREADS
3297 if (dh == NULL) {
3298 if (errno != 0) {
3299 ERR_clear_error();
3300 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3301 }
3302 else {
3303 _setSSLError(NULL, 0, __FILE__, __LINE__);
3304 }
3305 return NULL;
3306 }
3307 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3308 _setSSLError(NULL, 0, __FILE__, __LINE__);
3309 DH_free(dh);
3310 Py_RETURN_NONE;
3311}
3312
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003313/*[clinic input]
3314_ssl._SSLContext._wrap_socket
3315 sock: object(subclass_of="PySocketModule.Sock_Type")
3316 server_side: int
3317 server_hostname as hostname_obj: object = None
3318
3319[clinic start generated code]*/
3320
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003321static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003322_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3323 int server_side, PyObject *hostname_obj)
3324/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325{
Antoine Pitroud5323212010-10-22 18:19:07 +00003326 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003327 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328
Antoine Pitroud5323212010-10-22 18:19:07 +00003329 /* server_hostname is either None (or absent), or to be encoded
3330 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003331 if (hostname_obj != Py_None) {
3332 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003333 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003334 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003336 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3337 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003338 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003339 if (hostname != NULL)
3340 PyMem_Free(hostname);
3341 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003342}
3343
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003344/*[clinic input]
3345_ssl._SSLContext._wrap_bio
3346 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3347 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3348 server_side: int
3349 server_hostname as hostname_obj: object = None
3350
3351[clinic start generated code]*/
3352
Antoine Pitroub0182c82010-10-12 20:09:02 +00003353static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003354_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3355 PySSLMemoryBIO *outgoing, int server_side,
3356 PyObject *hostname_obj)
3357/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003358{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003359 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003360 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003361
3362 /* server_hostname is either None (or absent), or to be encoded
3363 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003364 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003365 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3366 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003367 }
3368
3369 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3370 incoming, outgoing);
3371
3372 PyMem_Free(hostname);
3373 return res;
3374}
3375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003376/*[clinic input]
3377_ssl._SSLContext.session_stats
3378[clinic start generated code]*/
3379
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003380static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003381_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3382/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003383{
3384 int r;
3385 PyObject *value, *stats = PyDict_New();
3386 if (!stats)
3387 return NULL;
3388
3389#define ADD_STATS(SSL_NAME, KEY_NAME) \
3390 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3391 if (value == NULL) \
3392 goto error; \
3393 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3394 Py_DECREF(value); \
3395 if (r < 0) \
3396 goto error;
3397
3398 ADD_STATS(number, "number");
3399 ADD_STATS(connect, "connect");
3400 ADD_STATS(connect_good, "connect_good");
3401 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3402 ADD_STATS(accept, "accept");
3403 ADD_STATS(accept_good, "accept_good");
3404 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3405 ADD_STATS(accept, "accept");
3406 ADD_STATS(hits, "hits");
3407 ADD_STATS(misses, "misses");
3408 ADD_STATS(timeouts, "timeouts");
3409 ADD_STATS(cache_full, "cache_full");
3410
3411#undef ADD_STATS
3412
3413 return stats;
3414
3415error:
3416 Py_DECREF(stats);
3417 return NULL;
3418}
3419
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003420/*[clinic input]
3421_ssl._SSLContext.set_default_verify_paths
3422[clinic start generated code]*/
3423
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003424static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003425_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3426/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003427{
3428 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3429 _setSSLError(NULL, 0, __FILE__, __LINE__);
3430 return NULL;
3431 }
3432 Py_RETURN_NONE;
3433}
3434
Antoine Pitrou501da612011-12-21 09:27:41 +01003435#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003436/*[clinic input]
3437_ssl._SSLContext.set_ecdh_curve
3438 name: object
3439 /
3440
3441[clinic start generated code]*/
3442
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003443static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003444_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3445/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003446{
3447 PyObject *name_bytes;
3448 int nid;
3449 EC_KEY *key;
3450
3451 if (!PyUnicode_FSConverter(name, &name_bytes))
3452 return NULL;
3453 assert(PyBytes_Check(name_bytes));
3454 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3455 Py_DECREF(name_bytes);
3456 if (nid == 0) {
3457 PyErr_Format(PyExc_ValueError,
3458 "unknown elliptic curve name %R", name);
3459 return NULL;
3460 }
3461 key = EC_KEY_new_by_curve_name(nid);
3462 if (key == NULL) {
3463 _setSSLError(NULL, 0, __FILE__, __LINE__);
3464 return NULL;
3465 }
3466 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3467 EC_KEY_free(key);
3468 Py_RETURN_NONE;
3469}
Antoine Pitrou501da612011-12-21 09:27:41 +01003470#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003471
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003472#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003473static int
3474_servername_callback(SSL *s, int *al, void *args)
3475{
3476 int ret;
3477 PySSLContext *ssl_ctx = (PySSLContext *) args;
3478 PySSLSocket *ssl;
3479 PyObject *servername_o;
3480 PyObject *servername_idna;
3481 PyObject *result;
3482 /* The high-level ssl.SSLSocket object */
3483 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003484 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003485#ifdef WITH_THREAD
3486 PyGILState_STATE gstate = PyGILState_Ensure();
3487#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003488
3489 if (ssl_ctx->set_hostname == NULL) {
3490 /* remove race condition in this the call back while if removing the
3491 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003492#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003493 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003494#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003495 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003496 }
3497
3498 ssl = SSL_get_app_data(s);
3499 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003500
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003501 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003502 * SSL connection and that has a .context attribute that can be changed to
3503 * identify the requested hostname. Since the official API is the Python
3504 * level API we want to pass the callback a Python level object rather than
3505 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3506 * SSLObject) that will be passed. Otherwise if there's a socket then that
3507 * will be passed. If both do not exist only then the C-level object is
3508 * passed. */
3509 if (ssl->owner)
3510 ssl_socket = PyWeakref_GetObject(ssl->owner);
3511 else if (ssl->Socket)
3512 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3513 else
3514 ssl_socket = (PyObject *) ssl;
3515
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003516 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003517 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003518 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003519
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003520 if (servername == NULL) {
3521 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3522 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003523 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003524 else {
3525 servername_o = PyBytes_FromString(servername);
3526 if (servername_o == NULL) {
3527 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3528 goto error;
3529 }
3530 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3531 if (servername_idna == NULL) {
3532 PyErr_WriteUnraisable(servername_o);
3533 Py_DECREF(servername_o);
3534 goto error;
3535 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003536 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003537 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3538 servername_idna, ssl_ctx, NULL);
3539 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003540 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003541 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003542
3543 if (result == NULL) {
3544 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3545 *al = SSL_AD_HANDSHAKE_FAILURE;
3546 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3547 }
3548 else {
3549 if (result != Py_None) {
3550 *al = (int) PyLong_AsLong(result);
3551 if (PyErr_Occurred()) {
3552 PyErr_WriteUnraisable(result);
3553 *al = SSL_AD_INTERNAL_ERROR;
3554 }
3555 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3556 }
3557 else {
3558 ret = SSL_TLSEXT_ERR_OK;
3559 }
3560 Py_DECREF(result);
3561 }
3562
Stefan Krah20d60802013-01-17 17:07:17 +01003563#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003564 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003565#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003566 return ret;
3567
3568error:
3569 Py_DECREF(ssl_socket);
3570 *al = SSL_AD_INTERNAL_ERROR;
3571 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003572#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003573 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003574#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003575 return ret;
3576}
Antoine Pitroua5963382013-03-30 16:39:00 +01003577#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003578
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003579/*[clinic input]
3580_ssl._SSLContext.set_servername_callback
3581 method as cb: object
3582 /
3583
3584Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3585
3586If the argument is None then the callback is disabled. The method is called
3587with the SSLSocket, the server name as a string, and the SSLContext object.
3588See RFC 6066 for details of the SNI extension.
3589[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003590
3591static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003592_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3593/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003594{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003595#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003596 Py_CLEAR(self->set_hostname);
3597 if (cb == Py_None) {
3598 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3599 }
3600 else {
3601 if (!PyCallable_Check(cb)) {
3602 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3603 PyErr_SetString(PyExc_TypeError,
3604 "not a callable object");
3605 return NULL;
3606 }
3607 Py_INCREF(cb);
3608 self->set_hostname = cb;
3609 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3610 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3611 }
3612 Py_RETURN_NONE;
3613#else
3614 PyErr_SetString(PyExc_NotImplementedError,
3615 "The TLS extension servername callback, "
3616 "SSL_CTX_set_tlsext_servername_callback, "
3617 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003618 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003619#endif
3620}
3621
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003622/*[clinic input]
3623_ssl._SSLContext.cert_store_stats
3624
3625Returns quantities of loaded X.509 certificates.
3626
3627X.509 certificates with a CA extension and certificate revocation lists
3628inside the context's cert store.
3629
3630NOTE: Certificates in a capath directory aren't loaded unless they have
3631been used at least once.
3632[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003633
3634static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003635_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3636/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003637{
3638 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003639 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003640 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003641 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003642
3643 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003644 objs = X509_STORE_get0_objects(store);
3645 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3646 obj = sk_X509_OBJECT_value(objs, i);
3647 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003648 case X509_LU_X509:
3649 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003650 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003651 ca++;
3652 }
3653 break;
3654 case X509_LU_CRL:
3655 crl++;
3656 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003657 default:
3658 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3659 * As far as I can tell they are internal states and never
3660 * stored in a cert store */
3661 break;
3662 }
3663 }
3664 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3665 "x509_ca", ca);
3666}
3667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003668/*[clinic input]
3669_ssl._SSLContext.get_ca_certs
3670 binary_form: bool = False
3671
3672Returns a list of dicts with information of loaded CA certs.
3673
3674If the optional argument is True, returns a DER-encoded copy of the CA
3675certificate.
3676
3677NOTE: Certificates in a capath directory aren't loaded unless they have
3678been used at least once.
3679[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003680
3681static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003682_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3683/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003684{
3685 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003686 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003687 PyObject *ci = NULL, *rlist = NULL;
3688 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003689
3690 if ((rlist = PyList_New(0)) == NULL) {
3691 return NULL;
3692 }
3693
3694 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003695 objs = X509_STORE_get0_objects(store);
3696 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003697 X509_OBJECT *obj;
3698 X509 *cert;
3699
Christian Heimes598894f2016-09-05 23:19:05 +02003700 obj = sk_X509_OBJECT_value(objs, i);
3701 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003702 /* not a x509 cert */
3703 continue;
3704 }
3705 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003706 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003707 if (!X509_check_ca(cert)) {
3708 continue;
3709 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003710 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003711 ci = _certificate_to_der(cert);
3712 } else {
3713 ci = _decode_certificate(cert);
3714 }
3715 if (ci == NULL) {
3716 goto error;
3717 }
3718 if (PyList_Append(rlist, ci) == -1) {
3719 goto error;
3720 }
3721 Py_CLEAR(ci);
3722 }
3723 return rlist;
3724
3725 error:
3726 Py_XDECREF(ci);
3727 Py_XDECREF(rlist);
3728 return NULL;
3729}
3730
3731
Antoine Pitrou152efa22010-05-16 18:19:27 +00003732static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003733 {"check_hostname", (getter) get_check_hostname,
3734 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003735 {"options", (getter) get_options,
3736 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003737 {"verify_flags", (getter) get_verify_flags,
3738 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003739 {"verify_mode", (getter) get_verify_mode,
3740 (setter) set_verify_mode, NULL},
3741 {NULL}, /* sentinel */
3742};
3743
3744static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003745 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3746 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3747 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3748 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3749 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3750 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3751 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3752 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3753 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3754 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3755 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3756 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3757 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3758 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003759 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003760 {NULL, NULL} /* sentinel */
3761};
3762
3763static PyTypeObject PySSLContext_Type = {
3764 PyVarObject_HEAD_INIT(NULL, 0)
3765 "_ssl._SSLContext", /*tp_name*/
3766 sizeof(PySSLContext), /*tp_basicsize*/
3767 0, /*tp_itemsize*/
3768 (destructor)context_dealloc, /*tp_dealloc*/
3769 0, /*tp_print*/
3770 0, /*tp_getattr*/
3771 0, /*tp_setattr*/
3772 0, /*tp_reserved*/
3773 0, /*tp_repr*/
3774 0, /*tp_as_number*/
3775 0, /*tp_as_sequence*/
3776 0, /*tp_as_mapping*/
3777 0, /*tp_hash*/
3778 0, /*tp_call*/
3779 0, /*tp_str*/
3780 0, /*tp_getattro*/
3781 0, /*tp_setattro*/
3782 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003783 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003784 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003785 (traverseproc) context_traverse, /*tp_traverse*/
3786 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003787 0, /*tp_richcompare*/
3788 0, /*tp_weaklistoffset*/
3789 0, /*tp_iter*/
3790 0, /*tp_iternext*/
3791 context_methods, /*tp_methods*/
3792 0, /*tp_members*/
3793 context_getsetlist, /*tp_getset*/
3794 0, /*tp_base*/
3795 0, /*tp_dict*/
3796 0, /*tp_descr_get*/
3797 0, /*tp_descr_set*/
3798 0, /*tp_dictoffset*/
3799 0, /*tp_init*/
3800 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003801 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003802};
3803
3804
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003805/*
3806 * MemoryBIO objects
3807 */
3808
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003809/*[clinic input]
3810@classmethod
3811_ssl.MemoryBIO.__new__
3812
3813[clinic start generated code]*/
3814
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003815static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003816_ssl_MemoryBIO_impl(PyTypeObject *type)
3817/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003818{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003819 BIO *bio;
3820 PySSLMemoryBIO *self;
3821
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003822 bio = BIO_new(BIO_s_mem());
3823 if (bio == NULL) {
3824 PyErr_SetString(PySSLErrorObject,
3825 "failed to allocate BIO");
3826 return NULL;
3827 }
3828 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3829 * just that no data is currently available. The SSL routines should retry
3830 * the read, which we can achieve by calling BIO_set_retry_read(). */
3831 BIO_set_retry_read(bio);
3832 BIO_set_mem_eof_return(bio, -1);
3833
3834 assert(type != NULL && type->tp_alloc != NULL);
3835 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3836 if (self == NULL) {
3837 BIO_free(bio);
3838 return NULL;
3839 }
3840 self->bio = bio;
3841 self->eof_written = 0;
3842
3843 return (PyObject *) self;
3844}
3845
3846static void
3847memory_bio_dealloc(PySSLMemoryBIO *self)
3848{
3849 BIO_free(self->bio);
3850 Py_TYPE(self)->tp_free(self);
3851}
3852
3853static PyObject *
3854memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3855{
3856 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3857}
3858
3859PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3860"The number of bytes pending in the memory BIO.");
3861
3862static PyObject *
3863memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3864{
3865 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3866 && self->eof_written);
3867}
3868
3869PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3870"Whether the memory BIO is at EOF.");
3871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872/*[clinic input]
3873_ssl.MemoryBIO.read
3874 size as len: int = -1
3875 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877Read up to size bytes from the memory BIO.
3878
3879If size is not specified, read the entire buffer.
3880If the return value is an empty bytes instance, this means either
3881EOF or that no data is available. Use the "eof" property to
3882distinguish between the two.
3883[clinic start generated code]*/
3884
3885static PyObject *
3886_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3887/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3888{
3889 int avail, nbytes;
3890 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003891
3892 avail = BIO_ctrl_pending(self->bio);
3893 if ((len < 0) || (len > avail))
3894 len = avail;
3895
3896 result = PyBytes_FromStringAndSize(NULL, len);
3897 if ((result == NULL) || (len == 0))
3898 return result;
3899
3900 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3901 /* There should never be any short reads but check anyway. */
3902 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3903 Py_DECREF(result);
3904 return NULL;
3905 }
3906
3907 return result;
3908}
3909
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003910/*[clinic input]
3911_ssl.MemoryBIO.write
3912 b: Py_buffer
3913 /
3914
3915Writes the bytes b into the memory BIO.
3916
3917Returns the number of bytes written.
3918[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003919
3920static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003921_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3922/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003923{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003924 int nbytes;
3925
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003926 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003927 PyErr_Format(PyExc_OverflowError,
3928 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003929 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003930 }
3931
3932 if (self->eof_written) {
3933 PyErr_SetString(PySSLErrorObject,
3934 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003936 }
3937
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003938 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003939 if (nbytes < 0) {
3940 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003941 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003942 }
3943
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003944 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003945}
3946
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003947/*[clinic input]
3948_ssl.MemoryBIO.write_eof
3949
3950Write an EOF marker to the memory BIO.
3951
3952When all data has been read, the "eof" property will be True.
3953[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003954
3955static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003956_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3957/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003958{
3959 self->eof_written = 1;
3960 /* After an EOF is written, a zero return from read() should be a real EOF
3961 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3962 BIO_clear_retry_flags(self->bio);
3963 BIO_set_mem_eof_return(self->bio, 0);
3964
3965 Py_RETURN_NONE;
3966}
3967
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003968static PyGetSetDef memory_bio_getsetlist[] = {
3969 {"pending", (getter) memory_bio_get_pending, NULL,
3970 PySSL_memory_bio_pending_doc},
3971 {"eof", (getter) memory_bio_get_eof, NULL,
3972 PySSL_memory_bio_eof_doc},
3973 {NULL}, /* sentinel */
3974};
3975
3976static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003977 _SSL_MEMORYBIO_READ_METHODDEF
3978 _SSL_MEMORYBIO_WRITE_METHODDEF
3979 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003980 {NULL, NULL} /* sentinel */
3981};
3982
3983static PyTypeObject PySSLMemoryBIO_Type = {
3984 PyVarObject_HEAD_INIT(NULL, 0)
3985 "_ssl.MemoryBIO", /*tp_name*/
3986 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3987 0, /*tp_itemsize*/
3988 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3989 0, /*tp_print*/
3990 0, /*tp_getattr*/
3991 0, /*tp_setattr*/
3992 0, /*tp_reserved*/
3993 0, /*tp_repr*/
3994 0, /*tp_as_number*/
3995 0, /*tp_as_sequence*/
3996 0, /*tp_as_mapping*/
3997 0, /*tp_hash*/
3998 0, /*tp_call*/
3999 0, /*tp_str*/
4000 0, /*tp_getattro*/
4001 0, /*tp_setattro*/
4002 0, /*tp_as_buffer*/
4003 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4004 0, /*tp_doc*/
4005 0, /*tp_traverse*/
4006 0, /*tp_clear*/
4007 0, /*tp_richcompare*/
4008 0, /*tp_weaklistoffset*/
4009 0, /*tp_iter*/
4010 0, /*tp_iternext*/
4011 memory_bio_methods, /*tp_methods*/
4012 0, /*tp_members*/
4013 memory_bio_getsetlist, /*tp_getset*/
4014 0, /*tp_base*/
4015 0, /*tp_dict*/
4016 0, /*tp_descr_get*/
4017 0, /*tp_descr_set*/
4018 0, /*tp_dictoffset*/
4019 0, /*tp_init*/
4020 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004021 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004022};
4023
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004025/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004026/*[clinic input]
4027_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004028 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004029 entropy: double
4030 /
4031
4032Mix string into the OpenSSL PRNG state.
4033
4034entropy (a float) is a lower bound on the entropy contained in
4035string. See RFC 1750.
4036[clinic start generated code]*/
4037
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004038static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004039_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4040/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004041{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004042 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004043 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004045 buf = (const char *)view->buf;
4046 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004047 do {
4048 written = Py_MIN(len, INT_MAX);
4049 RAND_add(buf, (int)written, entropy);
4050 buf += written;
4051 len -= written;
4052 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004053 Py_INCREF(Py_None);
4054 return Py_None;
4055}
4056
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004057static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004058PySSL_RAND(int len, int pseudo)
4059{
4060 int ok;
4061 PyObject *bytes;
4062 unsigned long err;
4063 const char *errstr;
4064 PyObject *v;
4065
Victor Stinner1e81a392013-12-19 16:47:04 +01004066 if (len < 0) {
4067 PyErr_SetString(PyExc_ValueError, "num must be positive");
4068 return NULL;
4069 }
4070
Victor Stinner99c8b162011-05-24 12:05:19 +02004071 bytes = PyBytes_FromStringAndSize(NULL, len);
4072 if (bytes == NULL)
4073 return NULL;
4074 if (pseudo) {
4075 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4076 if (ok == 0 || ok == 1)
4077 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4078 }
4079 else {
4080 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4081 if (ok == 1)
4082 return bytes;
4083 }
4084 Py_DECREF(bytes);
4085
4086 err = ERR_get_error();
4087 errstr = ERR_reason_error_string(err);
4088 v = Py_BuildValue("(ks)", err, errstr);
4089 if (v != NULL) {
4090 PyErr_SetObject(PySSLErrorObject, v);
4091 Py_DECREF(v);
4092 }
4093 return NULL;
4094}
4095
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004096/*[clinic input]
4097_ssl.RAND_bytes
4098 n: int
4099 /
4100
4101Generate n cryptographically strong pseudo-random bytes.
4102[clinic start generated code]*/
4103
Victor Stinner99c8b162011-05-24 12:05:19 +02004104static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004105_ssl_RAND_bytes_impl(PyObject *module, int n)
4106/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004107{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004108 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004109}
4110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004111/*[clinic input]
4112_ssl.RAND_pseudo_bytes
4113 n: int
4114 /
4115
4116Generate n pseudo-random bytes.
4117
4118Return a pair (bytes, is_cryptographic). is_cryptographic is True
4119if the bytes generated are cryptographically strong.
4120[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004121
4122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004123_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4124/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004125{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004127}
4128
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129/*[clinic input]
4130_ssl.RAND_status
4131
4132Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4133
4134It is necessary to seed the PRNG with RAND_add() on some platforms before
4135using the ssl() function.
4136[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004137
4138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004139_ssl_RAND_status_impl(PyObject *module)
4140/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004141{
Christian Heimes217cfd12007-12-02 14:31:20 +00004142 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004143}
4144
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004145#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004146/*[clinic input]
4147_ssl.RAND_egd
4148 path: object(converter="PyUnicode_FSConverter")
4149 /
4150
4151Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4152
4153Returns number of bytes read. Raises SSLError if connection to EGD
4154fails or if it does not provide enough data to seed PRNG.
4155[clinic start generated code]*/
4156
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004157static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004158_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4159/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004160{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004161 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004162 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004163 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004164 PyErr_SetString(PySSLErrorObject,
4165 "EGD connection failed or EGD did not return "
4166 "enough data to seed the PRNG");
4167 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004168 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004169 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004170}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004171#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004172
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004173
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174
4175/*[clinic input]
4176_ssl.get_default_verify_paths
4177
4178Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4179
4180The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4181[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004182
4183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004184_ssl_get_default_verify_paths_impl(PyObject *module)
4185/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004186{
4187 PyObject *ofile_env = NULL;
4188 PyObject *ofile = NULL;
4189 PyObject *odir_env = NULL;
4190 PyObject *odir = NULL;
4191
Benjamin Petersond113c962015-07-18 10:59:13 -07004192#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004193 const char *tmp = (info); \
4194 target = NULL; \
4195 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4196 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4197 target = PyBytes_FromString(tmp); } \
4198 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004199 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004200
Benjamin Petersond113c962015-07-18 10:59:13 -07004201 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4202 CONVERT(X509_get_default_cert_file(), ofile);
4203 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4204 CONVERT(X509_get_default_cert_dir(), odir);
4205#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004206
Christian Heimes200bb1b2013-06-14 15:14:29 +02004207 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004208
4209 error:
4210 Py_XDECREF(ofile_env);
4211 Py_XDECREF(ofile);
4212 Py_XDECREF(odir_env);
4213 Py_XDECREF(odir);
4214 return NULL;
4215}
4216
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004217static PyObject*
4218asn1obj2py(ASN1_OBJECT *obj)
4219{
4220 int nid;
4221 const char *ln, *sn;
4222 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004223 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004224
4225 nid = OBJ_obj2nid(obj);
4226 if (nid == NID_undef) {
4227 PyErr_Format(PyExc_ValueError, "Unknown object");
4228 return NULL;
4229 }
4230 sn = OBJ_nid2sn(nid);
4231 ln = OBJ_nid2ln(nid);
4232 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4233 if (buflen < 0) {
4234 _setSSLError(NULL, 0, __FILE__, __LINE__);
4235 return NULL;
4236 }
4237 if (buflen) {
4238 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4239 } else {
4240 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4241 }
4242}
4243
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004244/*[clinic input]
4245_ssl.txt2obj
4246 txt: str
4247 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004249Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4250
4251By default objects are looked up by OID. With name=True short and
4252long name are also matched.
4253[clinic start generated code]*/
4254
4255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004256_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4257/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004258{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004259 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004260 ASN1_OBJECT *obj;
4261
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004262 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4263 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004264 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004265 return NULL;
4266 }
4267 result = asn1obj2py(obj);
4268 ASN1_OBJECT_free(obj);
4269 return result;
4270}
4271
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004272/*[clinic input]
4273_ssl.nid2obj
4274 nid: int
4275 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004276
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004277Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4278[clinic start generated code]*/
4279
4280static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004281_ssl_nid2obj_impl(PyObject *module, int nid)
4282/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004283{
4284 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004285 ASN1_OBJECT *obj;
4286
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004287 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004288 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004289 return NULL;
4290 }
4291 obj = OBJ_nid2obj(nid);
4292 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004293 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004294 return NULL;
4295 }
4296 result = asn1obj2py(obj);
4297 ASN1_OBJECT_free(obj);
4298 return result;
4299}
4300
Christian Heimes46bebee2013-06-09 19:03:31 +02004301#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004302
4303static PyObject*
4304certEncodingType(DWORD encodingType)
4305{
4306 static PyObject *x509_asn = NULL;
4307 static PyObject *pkcs_7_asn = NULL;
4308
4309 if (x509_asn == NULL) {
4310 x509_asn = PyUnicode_InternFromString("x509_asn");
4311 if (x509_asn == NULL)
4312 return NULL;
4313 }
4314 if (pkcs_7_asn == NULL) {
4315 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4316 if (pkcs_7_asn == NULL)
4317 return NULL;
4318 }
4319 switch(encodingType) {
4320 case X509_ASN_ENCODING:
4321 Py_INCREF(x509_asn);
4322 return x509_asn;
4323 case PKCS_7_ASN_ENCODING:
4324 Py_INCREF(pkcs_7_asn);
4325 return pkcs_7_asn;
4326 default:
4327 return PyLong_FromLong(encodingType);
4328 }
4329}
4330
4331static PyObject*
4332parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4333{
4334 CERT_ENHKEY_USAGE *usage;
4335 DWORD size, error, i;
4336 PyObject *retval;
4337
4338 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4339 error = GetLastError();
4340 if (error == CRYPT_E_NOT_FOUND) {
4341 Py_RETURN_TRUE;
4342 }
4343 return PyErr_SetFromWindowsErr(error);
4344 }
4345
4346 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4347 if (usage == NULL) {
4348 return PyErr_NoMemory();
4349 }
4350
4351 /* Now get the actual enhanced usage property */
4352 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4353 PyMem_Free(usage);
4354 error = GetLastError();
4355 if (error == CRYPT_E_NOT_FOUND) {
4356 Py_RETURN_TRUE;
4357 }
4358 return PyErr_SetFromWindowsErr(error);
4359 }
4360 retval = PySet_New(NULL);
4361 if (retval == NULL) {
4362 goto error;
4363 }
4364 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4365 if (usage->rgpszUsageIdentifier[i]) {
4366 PyObject *oid;
4367 int err;
4368 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4369 if (oid == NULL) {
4370 Py_CLEAR(retval);
4371 goto error;
4372 }
4373 err = PySet_Add(retval, oid);
4374 Py_DECREF(oid);
4375 if (err == -1) {
4376 Py_CLEAR(retval);
4377 goto error;
4378 }
4379 }
4380 }
4381 error:
4382 PyMem_Free(usage);
4383 return retval;
4384}
4385
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004386/*[clinic input]
4387_ssl.enum_certificates
4388 store_name: str
4389
4390Retrieve certificates from Windows' cert store.
4391
4392store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4393more cert storages, too. The function returns a list of (bytes,
4394encoding_type, trust) tuples. The encoding_type flag can be interpreted
4395with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4396a set of OIDs or the boolean True.
4397[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004398
Christian Heimes46bebee2013-06-09 19:03:31 +02004399static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004400_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4401/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004402{
Christian Heimes46bebee2013-06-09 19:03:31 +02004403 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004404 PCCERT_CONTEXT pCertCtx = NULL;
4405 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004406 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004407
Christian Heimes44109d72013-11-22 01:51:30 +01004408 result = PyList_New(0);
4409 if (result == NULL) {
4410 return NULL;
4411 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004412 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4413 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4414 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004415 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004416 Py_DECREF(result);
4417 return PyErr_SetFromWindowsErr(GetLastError());
4418 }
4419
Christian Heimes44109d72013-11-22 01:51:30 +01004420 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4421 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4422 pCertCtx->cbCertEncoded);
4423 if (!cert) {
4424 Py_CLEAR(result);
4425 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004426 }
Christian Heimes44109d72013-11-22 01:51:30 +01004427 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4428 Py_CLEAR(result);
4429 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004430 }
Christian Heimes44109d72013-11-22 01:51:30 +01004431 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4432 if (keyusage == Py_True) {
4433 Py_DECREF(keyusage);
4434 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004435 }
Christian Heimes44109d72013-11-22 01:51:30 +01004436 if (keyusage == NULL) {
4437 Py_CLEAR(result);
4438 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004439 }
Christian Heimes44109d72013-11-22 01:51:30 +01004440 if ((tup = PyTuple_New(3)) == NULL) {
4441 Py_CLEAR(result);
4442 break;
4443 }
4444 PyTuple_SET_ITEM(tup, 0, cert);
4445 cert = NULL;
4446 PyTuple_SET_ITEM(tup, 1, enc);
4447 enc = NULL;
4448 PyTuple_SET_ITEM(tup, 2, keyusage);
4449 keyusage = NULL;
4450 if (PyList_Append(result, tup) < 0) {
4451 Py_CLEAR(result);
4452 break;
4453 }
4454 Py_CLEAR(tup);
4455 }
4456 if (pCertCtx) {
4457 /* loop ended with an error, need to clean up context manually */
4458 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004459 }
4460
4461 /* In error cases cert, enc and tup may not be NULL */
4462 Py_XDECREF(cert);
4463 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004464 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004465 Py_XDECREF(tup);
4466
4467 if (!CertCloseStore(hStore, 0)) {
4468 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004469 Py_XDECREF(result);
4470 return PyErr_SetFromWindowsErr(GetLastError());
4471 }
4472 return result;
4473}
4474
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004475/*[clinic input]
4476_ssl.enum_crls
4477 store_name: str
4478
4479Retrieve CRLs from Windows' cert store.
4480
4481store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4482more cert storages, too. The function returns a list of (bytes,
4483encoding_type) tuples. The encoding_type flag can be interpreted with
4484X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4485[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004486
4487static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004488_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4489/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004490{
Christian Heimes44109d72013-11-22 01:51:30 +01004491 HCERTSTORE hStore = NULL;
4492 PCCRL_CONTEXT pCrlCtx = NULL;
4493 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4494 PyObject *result = NULL;
4495
Christian Heimes44109d72013-11-22 01:51:30 +01004496 result = PyList_New(0);
4497 if (result == NULL) {
4498 return NULL;
4499 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004500 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4501 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4502 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004503 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004504 Py_DECREF(result);
4505 return PyErr_SetFromWindowsErr(GetLastError());
4506 }
Christian Heimes44109d72013-11-22 01:51:30 +01004507
4508 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4509 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4510 pCrlCtx->cbCrlEncoded);
4511 if (!crl) {
4512 Py_CLEAR(result);
4513 break;
4514 }
4515 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4516 Py_CLEAR(result);
4517 break;
4518 }
4519 if ((tup = PyTuple_New(2)) == NULL) {
4520 Py_CLEAR(result);
4521 break;
4522 }
4523 PyTuple_SET_ITEM(tup, 0, crl);
4524 crl = NULL;
4525 PyTuple_SET_ITEM(tup, 1, enc);
4526 enc = NULL;
4527
4528 if (PyList_Append(result, tup) < 0) {
4529 Py_CLEAR(result);
4530 break;
4531 }
4532 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004533 }
Christian Heimes44109d72013-11-22 01:51:30 +01004534 if (pCrlCtx) {
4535 /* loop ended with an error, need to clean up context manually */
4536 CertFreeCRLContext(pCrlCtx);
4537 }
4538
4539 /* In error cases cert, enc and tup may not be NULL */
4540 Py_XDECREF(crl);
4541 Py_XDECREF(enc);
4542 Py_XDECREF(tup);
4543
4544 if (!CertCloseStore(hStore, 0)) {
4545 /* This error case might shadow another exception.*/
4546 Py_XDECREF(result);
4547 return PyErr_SetFromWindowsErr(GetLastError());
4548 }
4549 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004550}
Christian Heimes44109d72013-11-22 01:51:30 +01004551
4552#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004553
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004554/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004555static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004556 _SSL__TEST_DECODE_CERT_METHODDEF
4557 _SSL_RAND_ADD_METHODDEF
4558 _SSL_RAND_BYTES_METHODDEF
4559 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4560 _SSL_RAND_EGD_METHODDEF
4561 _SSL_RAND_STATUS_METHODDEF
4562 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4563 _SSL_ENUM_CERTIFICATES_METHODDEF
4564 _SSL_ENUM_CRLS_METHODDEF
4565 _SSL_TXT2OBJ_METHODDEF
4566 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004567 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004568};
4569
4570
Christian Heimes598894f2016-09-05 23:19:05 +02004571#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004572
4573/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004574 * of the Python C thread library
4575 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4576 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577
4578static PyThread_type_lock *_ssl_locks = NULL;
4579
Christian Heimes4d98ca92013-08-19 17:36:29 +02004580#if OPENSSL_VERSION_NUMBER >= 0x10000000
4581/* use new CRYPTO_THREADID API. */
4582static void
4583_ssl_threadid_callback(CRYPTO_THREADID *id)
4584{
4585 CRYPTO_THREADID_set_numeric(id,
4586 (unsigned long)PyThread_get_thread_ident());
4587}
4588#else
4589/* deprecated CRYPTO_set_id_callback() API. */
4590static unsigned long
4591_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004592 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004593}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004594#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004595
Bill Janssen6e027db2007-11-15 22:23:56 +00004596static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004597 (int mode, int n, const char *file, int line) {
4598 /* this function is needed to perform locking on shared data
4599 structures. (Note that OpenSSL uses a number of global data
4600 structures that will be implicitly shared whenever multiple
4601 threads use OpenSSL.) Multi-threaded applications will
4602 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004604 locking_function() must be able to handle up to
4605 CRYPTO_num_locks() different mutex locks. It sets the n-th
4606 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004608 file and line are the file number of the function setting the
4609 lock. They can be useful for debugging.
4610 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004612 if ((_ssl_locks == NULL) ||
4613 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4614 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004616 if (mode & CRYPTO_LOCK) {
4617 PyThread_acquire_lock(_ssl_locks[n], 1);
4618 } else {
4619 PyThread_release_lock(_ssl_locks[n]);
4620 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004621}
4622
4623static int _setup_ssl_threads(void) {
4624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004625 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004627 if (_ssl_locks == NULL) {
4628 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004629 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4630 if (_ssl_locks == NULL) {
4631 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004632 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004633 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004634 memset(_ssl_locks, 0,
4635 sizeof(PyThread_type_lock) * _ssl_locks_count);
4636 for (i = 0; i < _ssl_locks_count; i++) {
4637 _ssl_locks[i] = PyThread_allocate_lock();
4638 if (_ssl_locks[i] == NULL) {
4639 unsigned int j;
4640 for (j = 0; j < i; j++) {
4641 PyThread_free_lock(_ssl_locks[j]);
4642 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004643 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004644 return 0;
4645 }
4646 }
4647 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004648#if OPENSSL_VERSION_NUMBER >= 0x10000000
4649 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4650#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004651 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004652#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004653 }
4654 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004655}
4656
Christian Heimes598894f2016-09-05 23:19:05 +02004657#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004658
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004659PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004660"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004661for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004662
Martin v. Löwis1a214512008-06-11 05:26:20 +00004663
4664static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004665 PyModuleDef_HEAD_INIT,
4666 "_ssl",
4667 module_doc,
4668 -1,
4669 PySSL_methods,
4670 NULL,
4671 NULL,
4672 NULL,
4673 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004674};
4675
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004676
4677static void
4678parse_openssl_version(unsigned long libver,
4679 unsigned int *major, unsigned int *minor,
4680 unsigned int *fix, unsigned int *patch,
4681 unsigned int *status)
4682{
4683 *status = libver & 0xF;
4684 libver >>= 4;
4685 *patch = libver & 0xFF;
4686 libver >>= 8;
4687 *fix = libver & 0xFF;
4688 libver >>= 8;
4689 *minor = libver & 0xFF;
4690 libver >>= 8;
4691 *major = libver & 0xFF;
4692}
4693
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004694PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004695PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004696{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004697 PyObject *m, *d, *r;
4698 unsigned long libver;
4699 unsigned int major, minor, fix, patch, status;
4700 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004701 struct py_ssl_error_code *errcode;
4702 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004703
Antoine Pitrou152efa22010-05-16 18:19:27 +00004704 if (PyType_Ready(&PySSLContext_Type) < 0)
4705 return NULL;
4706 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004707 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004708 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4709 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004711 m = PyModule_Create(&_sslmodule);
4712 if (m == NULL)
4713 return NULL;
4714 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004716 /* Load _socket module and its C API */
4717 socket_api = PySocketModule_ImportModuleAndAPI();
4718 if (!socket_api)
4719 return NULL;
4720 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004722 /* Init OpenSSL */
4723 SSL_load_error_strings();
4724 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004725#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02004726#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004727 /* note that this will start threading if not already started */
4728 if (!_setup_ssl_threads()) {
4729 return NULL;
4730 }
Christian Heimes598894f2016-09-05 23:19:05 +02004731#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4732 /* OpenSSL 1.1.0 builtin thread support is enabled */
4733 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004734#endif
Christian Heimes598894f2016-09-05 23:19:05 +02004735#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004736 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004738 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004739 sslerror_type_slots[0].pfunc = PyExc_OSError;
4740 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004741 if (PySSLErrorObject == NULL)
4742 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004743
Antoine Pitrou41032a62011-10-27 23:56:55 +02004744 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4745 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4746 PySSLErrorObject, NULL);
4747 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4748 "ssl.SSLWantReadError", SSLWantReadError_doc,
4749 PySSLErrorObject, NULL);
4750 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4751 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4752 PySSLErrorObject, NULL);
4753 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4754 "ssl.SSLSyscallError", SSLSyscallError_doc,
4755 PySSLErrorObject, NULL);
4756 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4757 "ssl.SSLEOFError", SSLEOFError_doc,
4758 PySSLErrorObject, NULL);
4759 if (PySSLZeroReturnErrorObject == NULL
4760 || PySSLWantReadErrorObject == NULL
4761 || PySSLWantWriteErrorObject == NULL
4762 || PySSLSyscallErrorObject == NULL
4763 || PySSLEOFErrorObject == NULL)
4764 return NULL;
4765 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4766 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4767 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4768 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4769 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4770 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004771 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004772 if (PyDict_SetItemString(d, "_SSLContext",
4773 (PyObject *)&PySSLContext_Type) != 0)
4774 return NULL;
4775 if (PyDict_SetItemString(d, "_SSLSocket",
4776 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004777 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004778 if (PyDict_SetItemString(d, "MemoryBIO",
4779 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4780 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004781 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4782 PY_SSL_ERROR_ZERO_RETURN);
4783 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4784 PY_SSL_ERROR_WANT_READ);
4785 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4786 PY_SSL_ERROR_WANT_WRITE);
4787 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4788 PY_SSL_ERROR_WANT_X509_LOOKUP);
4789 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4790 PY_SSL_ERROR_SYSCALL);
4791 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4792 PY_SSL_ERROR_SSL);
4793 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4794 PY_SSL_ERROR_WANT_CONNECT);
4795 /* non ssl.h errorcodes */
4796 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4797 PY_SSL_ERROR_EOF);
4798 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4799 PY_SSL_ERROR_INVALID_ERROR_CODE);
4800 /* cert requirements */
4801 PyModule_AddIntConstant(m, "CERT_NONE",
4802 PY_SSL_CERT_NONE);
4803 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4804 PY_SSL_CERT_OPTIONAL);
4805 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4806 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004807 /* CRL verification for verification_flags */
4808 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4809 0);
4810 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4811 X509_V_FLAG_CRL_CHECK);
4812 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4813 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4814 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4815 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004816#ifdef X509_V_FLAG_TRUSTED_FIRST
4817 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4818 X509_V_FLAG_TRUSTED_FIRST);
4819#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004820
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004821 /* Alert Descriptions from ssl.h */
4822 /* note RESERVED constants no longer intended for use have been removed */
4823 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4824
4825#define ADD_AD_CONSTANT(s) \
4826 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4827 SSL_AD_##s)
4828
4829 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4830 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4831 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4832 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4833 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4834 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4835 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4836 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4837 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4838 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4839 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4840 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4841 ADD_AD_CONSTANT(UNKNOWN_CA);
4842 ADD_AD_CONSTANT(ACCESS_DENIED);
4843 ADD_AD_CONSTANT(DECODE_ERROR);
4844 ADD_AD_CONSTANT(DECRYPT_ERROR);
4845 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4846 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4847 ADD_AD_CONSTANT(INTERNAL_ERROR);
4848 ADD_AD_CONSTANT(USER_CANCELLED);
4849 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004850 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004851#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4852 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4853#endif
4854#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4855 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4856#endif
4857#ifdef SSL_AD_UNRECOGNIZED_NAME
4858 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4859#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004860#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4861 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4862#endif
4863#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4864 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4865#endif
4866#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4867 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4868#endif
4869
4870#undef ADD_AD_CONSTANT
4871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004872 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004873#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004874 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4875 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004876#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004877#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004878 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4879 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004880#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004881 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02004882 PY_SSL_VERSION_TLS);
4883 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4884 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004885 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4886 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004887#if HAVE_TLSv1_2
4888 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4889 PY_SSL_VERSION_TLS1_1);
4890 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4891 PY_SSL_VERSION_TLS1_2);
4892#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004893
Antoine Pitroub5218772010-05-21 09:56:06 +00004894 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004895 PyModule_AddIntConstant(m, "OP_ALL",
4896 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004897 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4898 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4899 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004900#if HAVE_TLSv1_2
4901 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4902 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4903#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004904 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4905 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004906 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004907#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004908 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004909#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004910#ifdef SSL_OP_NO_COMPRESSION
4911 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4912 SSL_OP_NO_COMPRESSION);
4913#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004914
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004915#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004916 r = Py_True;
4917#else
4918 r = Py_False;
4919#endif
4920 Py_INCREF(r);
4921 PyModule_AddObject(m, "HAS_SNI", r);
4922
Antoine Pitroud6494802011-07-21 01:11:30 +02004923 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004924 Py_INCREF(r);
4925 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4926
Antoine Pitrou501da612011-12-21 09:27:41 +01004927#ifdef OPENSSL_NO_ECDH
4928 r = Py_False;
4929#else
4930 r = Py_True;
4931#endif
4932 Py_INCREF(r);
4933 PyModule_AddObject(m, "HAS_ECDH", r);
4934
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004935#ifdef OPENSSL_NPN_NEGOTIATED
4936 r = Py_True;
4937#else
4938 r = Py_False;
4939#endif
4940 Py_INCREF(r);
4941 PyModule_AddObject(m, "HAS_NPN", r);
4942
Benjamin Petersoncca27322015-01-23 16:35:37 -05004943#ifdef HAVE_ALPN
4944 r = Py_True;
4945#else
4946 r = Py_False;
4947#endif
4948 Py_INCREF(r);
4949 PyModule_AddObject(m, "HAS_ALPN", r);
4950
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004951 /* Mappings for error codes */
4952 err_codes_to_names = PyDict_New();
4953 err_names_to_codes = PyDict_New();
4954 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4955 return NULL;
4956 errcode = error_codes;
4957 while (errcode->mnemonic != NULL) {
4958 PyObject *mnemo, *key;
4959 mnemo = PyUnicode_FromString(errcode->mnemonic);
4960 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4961 if (mnemo == NULL || key == NULL)
4962 return NULL;
4963 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4964 return NULL;
4965 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4966 return NULL;
4967 Py_DECREF(key);
4968 Py_DECREF(mnemo);
4969 errcode++;
4970 }
4971 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4972 return NULL;
4973 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4974 return NULL;
4975
4976 lib_codes_to_names = PyDict_New();
4977 if (lib_codes_to_names == NULL)
4978 return NULL;
4979 libcode = library_codes;
4980 while (libcode->library != NULL) {
4981 PyObject *mnemo, *key;
4982 key = PyLong_FromLong(libcode->code);
4983 mnemo = PyUnicode_FromString(libcode->library);
4984 if (key == NULL || mnemo == NULL)
4985 return NULL;
4986 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4987 return NULL;
4988 Py_DECREF(key);
4989 Py_DECREF(mnemo);
4990 libcode++;
4991 }
4992 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4993 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004995 /* OpenSSL version */
4996 /* SSLeay() gives us the version of the library linked against,
4997 which could be different from the headers version.
4998 */
4999 libver = SSLeay();
5000 r = PyLong_FromUnsignedLong(libver);
5001 if (r == NULL)
5002 return NULL;
5003 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5004 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005005 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005006 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5007 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5008 return NULL;
5009 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5010 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5011 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005012
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005013 libver = OPENSSL_VERSION_NUMBER;
5014 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5015 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5016 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5017 return NULL;
5018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005019 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005020}