blob: a79c3a888666ebb42a3edb399243de413764ca05 [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 *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000458PySSL_SetError(PySSLSocket *obj, int ret, 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 *
540_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
541
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200542 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200544 else
545 errcode = 0;
546 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000547 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549}
550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551/*
552 * SSL objects
553 */
554
Antoine Pitrou152efa22010-05-16 18:19:27 +0000555static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100556newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000557 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200558 char *server_hostname,
559 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000560{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000561 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100562 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200563 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564
Antoine Pitrou152efa22010-05-16 18:19:27 +0000565 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 if (self == NULL)
567 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 self->peer_cert = NULL;
570 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100572 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200573 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200574 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200575 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700576 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200577 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700578 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
579 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200580 if (hostname == NULL) {
581 Py_DECREF(self);
582 return NULL;
583 }
584 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700585 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200586
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100587 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000588
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 /* Make sure the SSL error state is initialized */
590 (void) ERR_get_state();
591 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000594 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 SSL_set_app_data(self->ssl, self);
597 if (sock) {
598 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
599 } else {
600 /* BIOs are reference counted and SSL_set_bio borrows our reference.
601 * To prevent a double free in memory_bio_dealloc() we need to take an
602 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200603 BIO_up_ref(inbio->bio);
604 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200605 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
606 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200607 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000608#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200609 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000610#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200611 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000612
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100613#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000614 if (server_hostname != NULL)
615 SSL_set_tlsext_host_name(self->ssl, server_hostname);
616#endif
617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 /* If the socket is in non-blocking mode or timeout mode, set the BIO
619 * to non-blocking mode (blocking is the default)
620 */
Victor Stinnere2452312015-03-28 03:00:46 +0100621 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
623 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
624 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 PySSL_BEGIN_ALLOW_THREADS
627 if (socket_type == PY_SSL_CLIENT)
628 SSL_set_connect_state(self->ssl);
629 else
630 SSL_set_accept_state(self->ssl);
631 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000632
Antoine Pitroud6494802011-07-21 01:11:30 +0200633 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200634 if (sock != NULL) {
635 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
636 if (self->Socket == NULL) {
637 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200638 return NULL;
639 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100640 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000642}
643
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000644/* SSL object methods */
645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300646/*[clinic input]
647_ssl._SSLSocket.do_handshake
648[clinic start generated code]*/
649
650static PyObject *
651_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
652/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000653{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 int ret;
655 int err;
656 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200657 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200658 _PyTime_t timeout, deadline = 0;
659 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000660
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 if (sock) {
662 if (((PyObject*)sock) == Py_None) {
663 _setSSLError("Underlying socket connection gone",
664 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
665 return NULL;
666 }
667 Py_INCREF(sock);
668
669 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100670 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200671 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
672 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000674
Victor Stinner14690702015-04-06 22:46:13 +0200675 timeout = GET_SOCKET_TIMEOUT(sock);
676 has_timeout = (timeout > 0);
677 if (has_timeout)
678 deadline = _PyTime_GetMonotonicClock() + timeout;
679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 /* Actually negotiate SSL connection */
681 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000683 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 ret = SSL_do_handshake(self->ssl);
685 err = SSL_get_error(self->ssl, ret);
686 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200687
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000688 if (PyErr_CheckSignals())
689 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200690
Victor Stinner14690702015-04-06 22:46:13 +0200691 if (has_timeout)
692 timeout = deadline - _PyTime_GetMonotonicClock();
693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200695 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200697 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 } else {
699 sockstate = SOCKET_OPERATION_OK;
700 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000703 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000704 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000705 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
707 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000708 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000709 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
711 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000712 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000713 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
715 break;
716 }
717 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200718 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 if (ret < 1)
720 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 if (self->peer_cert)
723 X509_free (self->peer_cert);
724 PySSL_BEGIN_ALLOW_THREADS
725 self->peer_cert = SSL_get_peer_certificate(self->ssl);
726 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200727 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728
729 Py_INCREF(Py_None);
730 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000731
732error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200733 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000734 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000735}
736
Thomas Woutersed03b412007-08-28 21:37:11 +0000737static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 char namebuf[X509_NAME_MAXLEN];
741 int buflen;
742 PyObject *name_obj;
743 PyObject *value_obj;
744 PyObject *attr;
745 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
748 if (buflen < 0) {
749 _setSSLError(NULL, 0, __FILE__, __LINE__);
750 goto fail;
751 }
752 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
753 if (name_obj == NULL)
754 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
757 if (buflen < 0) {
758 _setSSLError(NULL, 0, __FILE__, __LINE__);
759 Py_DECREF(name_obj);
760 goto fail;
761 }
762 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000763 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 OPENSSL_free(valuebuf);
765 if (value_obj == NULL) {
766 Py_DECREF(name_obj);
767 goto fail;
768 }
769 attr = PyTuple_New(2);
770 if (attr == NULL) {
771 Py_DECREF(name_obj);
772 Py_DECREF(value_obj);
773 goto fail;
774 }
775 PyTuple_SET_ITEM(attr, 0, name_obj);
776 PyTuple_SET_ITEM(attr, 1, value_obj);
777 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000778
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000781}
782
783static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000785{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
787 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
788 PyObject *rdnt;
789 PyObject *attr = NULL; /* tuple to hold an attribute */
790 int entry_count = X509_NAME_entry_count(xname);
791 X509_NAME_ENTRY *entry;
792 ASN1_OBJECT *name;
793 ASN1_STRING *value;
794 int index_counter;
795 int rdn_level = -1;
796 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 dn = PyList_New(0);
799 if (dn == NULL)
800 return NULL;
801 /* now create another tuple to hold the top-level RDN */
802 rdn = PyList_New(0);
803 if (rdn == NULL)
804 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 for (index_counter = 0;
807 index_counter < entry_count;
808 index_counter++)
809 {
810 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 /* check to see if we've gotten to a new RDN */
813 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200814 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 /* yes, new RDN */
816 /* add old RDN to DN */
817 rdnt = PyList_AsTuple(rdn);
818 Py_DECREF(rdn);
819 if (rdnt == NULL)
820 goto fail0;
821 retcode = PyList_Append(dn, rdnt);
822 Py_DECREF(rdnt);
823 if (retcode < 0)
824 goto fail0;
825 /* create new RDN */
826 rdn = PyList_New(0);
827 if (rdn == NULL)
828 goto fail0;
829 }
830 }
Christian Heimes598894f2016-09-05 23:19:05 +0200831 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 /* now add this attribute to the current RDN */
834 name = X509_NAME_ENTRY_get_object(entry);
835 value = X509_NAME_ENTRY_get_data(entry);
836 attr = _create_tuple_for_attribute(name, value);
837 /*
838 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
839 entry->set,
840 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
841 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
842 */
843 if (attr == NULL)
844 goto fail1;
845 retcode = PyList_Append(rdn, attr);
846 Py_DECREF(attr);
847 if (retcode < 0)
848 goto fail1;
849 }
850 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100851 if (rdn != NULL) {
852 if (PyList_GET_SIZE(rdn) > 0) {
853 rdnt = PyList_AsTuple(rdn);
854 Py_DECREF(rdn);
855 if (rdnt == NULL)
856 goto fail0;
857 retcode = PyList_Append(dn, rdnt);
858 Py_DECREF(rdnt);
859 if (retcode < 0)
860 goto fail0;
861 }
862 else {
863 Py_DECREF(rdn);
864 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 /* convert list to tuple */
868 rdnt = PyList_AsTuple(dn);
869 Py_DECREF(dn);
870 if (rdnt == NULL)
871 return NULL;
872 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873
874 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
877 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 Py_XDECREF(dn);
879 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880}
881
882static PyObject *
883_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 /* this code follows the procedure outlined in
886 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
887 function to extract the STACK_OF(GENERAL_NAME),
888 then iterates through the stack to add the
889 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 int i, j;
892 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200893 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 X509_EXTENSION *ext = NULL;
895 GENERAL_NAMES *names = NULL;
896 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000897 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 BIO *biobuf = NULL;
899 char buf[2048];
900 char *vptr;
901 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 if (certificate == NULL)
905 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 /* get a memory buffer */
908 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200910 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 while ((i = X509_get_ext_by_NID(
912 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 if (peer_alt_names == Py_None) {
915 peer_alt_names = PyList_New(0);
916 if (peer_alt_names == NULL)
917 goto fail;
918 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 /* now decode the altName */
921 ext = X509_get_ext(certificate, i);
922 if(!(method = X509V3_EXT_get(ext))) {
923 PyErr_SetString
924 (PySSLErrorObject,
925 ERRSTR("No method for internalizing subjectAltName!"));
926 goto fail;
927 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Christian Heimes598894f2016-09-05 23:19:05 +0200929 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (method->it)
931 names = (GENERAL_NAMES*)
932 (ASN1_item_d2i(NULL,
933 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200934 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 ASN1_ITEM_ptr(method->it)));
936 else
937 names = (GENERAL_NAMES*)
938 (method->d2i(NULL,
939 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200940 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200944 int gntype;
945 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200948 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200949 switch (gntype) {
950 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 /* we special-case DirName as a tuple of
952 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 t = PyTuple_New(2);
955 if (t == NULL) {
956 goto fail;
957 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 v = PyUnicode_FromString("DirName");
960 if (v == NULL) {
961 Py_DECREF(t);
962 goto fail;
963 }
964 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 v = _create_tuple_for_X509_NAME (name->d.dirn);
967 if (v == NULL) {
968 Py_DECREF(t);
969 goto fail;
970 }
971 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200972 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Christian Heimes824f7f32013-08-17 00:54:47 +0200974 case GEN_EMAIL:
975 case GEN_DNS:
976 case GEN_URI:
977 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
978 correctly, CVE-2013-4238 */
979 t = PyTuple_New(2);
980 if (t == NULL)
981 goto fail;
982 switch (gntype) {
983 case GEN_EMAIL:
984 v = PyUnicode_FromString("email");
985 as = name->d.rfc822Name;
986 break;
987 case GEN_DNS:
988 v = PyUnicode_FromString("DNS");
989 as = name->d.dNSName;
990 break;
991 case GEN_URI:
992 v = PyUnicode_FromString("URI");
993 as = name->d.uniformResourceIdentifier;
994 break;
995 }
996 if (v == NULL) {
997 Py_DECREF(t);
998 goto fail;
999 }
1000 PyTuple_SET_ITEM(t, 0, v);
1001 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1002 ASN1_STRING_length(as));
1003 if (v == NULL) {
1004 Py_DECREF(t);
1005 goto fail;
1006 }
1007 PyTuple_SET_ITEM(t, 1, v);
1008 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Christian Heimes1c03abd2016-09-06 23:25:35 +02001010 case GEN_RID:
1011 t = PyTuple_New(2);
1012 if (t == NULL)
1013 goto fail;
1014
1015 v = PyUnicode_FromString("Registered ID");
1016 if (v == NULL) {
1017 Py_DECREF(t);
1018 goto fail;
1019 }
1020 PyTuple_SET_ITEM(t, 0, v);
1021
1022 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1023 if (len < 0) {
1024 Py_DECREF(t);
1025 _setSSLError(NULL, 0, __FILE__, __LINE__);
1026 goto fail;
1027 } else if (len >= (int)sizeof(buf)) {
1028 v = PyUnicode_FromString("<INVALID>");
1029 } else {
1030 v = PyUnicode_FromStringAndSize(buf, len);
1031 }
1032 if (v == NULL) {
1033 Py_DECREF(t);
1034 goto fail;
1035 }
1036 PyTuple_SET_ITEM(t, 1, v);
1037 break;
1038
Christian Heimes824f7f32013-08-17 00:54:47 +02001039 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001041 switch (gntype) {
1042 /* check for new general name type */
1043 case GEN_OTHERNAME:
1044 case GEN_X400:
1045 case GEN_EDIPARTY:
1046 case GEN_IPADD:
1047 case GEN_RID:
1048 break;
1049 default:
1050 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1051 "Unknown general name type %d",
1052 gntype) == -1) {
1053 goto fail;
1054 }
1055 break;
1056 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 (void) BIO_reset(biobuf);
1058 GENERAL_NAME_print(biobuf, name);
1059 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1060 if (len < 0) {
1061 _setSSLError(NULL, 0, __FILE__, __LINE__);
1062 goto fail;
1063 }
1064 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001065 if (vptr == NULL) {
1066 PyErr_Format(PyExc_ValueError,
1067 "Invalid value %.200s",
1068 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001070 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 t = PyTuple_New(2);
1072 if (t == NULL)
1073 goto fail;
1074 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1075 if (v == NULL) {
1076 Py_DECREF(t);
1077 goto fail;
1078 }
1079 PyTuple_SET_ITEM(t, 0, v);
1080 v = PyUnicode_FromStringAndSize((vptr + 1),
1081 (len - (vptr - buf + 1)));
1082 if (v == NULL) {
1083 Py_DECREF(t);
1084 goto fail;
1085 }
1086 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001087 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 if (PyList_Append(peer_alt_names, t) < 0) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 Py_DECREF(t);
1097 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001098 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 }
1100 BIO_free(biobuf);
1101 if (peer_alt_names != Py_None) {
1102 v = PyList_AsTuple(peer_alt_names);
1103 Py_DECREF(peer_alt_names);
1104 return v;
1105 } else {
1106 return peer_alt_names;
1107 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001108
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
1110 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 if (biobuf != NULL)
1112 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 if (peer_alt_names != Py_None) {
1115 Py_XDECREF(peer_alt_names);
1116 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119}
1120
1121static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001122_get_aia_uri(X509 *certificate, int nid) {
1123 PyObject *lst = NULL, *ostr = NULL;
1124 int i, result;
1125 AUTHORITY_INFO_ACCESS *info;
1126
1127 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001128 if (info == NULL)
1129 return Py_None;
1130 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1131 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001132 return Py_None;
1133 }
1134
1135 if ((lst = PyList_New(0)) == NULL) {
1136 goto fail;
1137 }
1138
1139 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1140 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1141 ASN1_IA5STRING *uri;
1142
1143 if ((OBJ_obj2nid(ad->method) != nid) ||
1144 (ad->location->type != GEN_URI)) {
1145 continue;
1146 }
1147 uri = ad->location->d.uniformResourceIdentifier;
1148 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1149 uri->length);
1150 if (ostr == NULL) {
1151 goto fail;
1152 }
1153 result = PyList_Append(lst, ostr);
1154 Py_DECREF(ostr);
1155 if (result < 0) {
1156 goto fail;
1157 }
1158 }
1159 AUTHORITY_INFO_ACCESS_free(info);
1160
1161 /* convert to tuple or None */
1162 if (PyList_Size(lst) == 0) {
1163 Py_DECREF(lst);
1164 return Py_None;
1165 } else {
1166 PyObject *tup;
1167 tup = PyList_AsTuple(lst);
1168 Py_DECREF(lst);
1169 return tup;
1170 }
1171
1172 fail:
1173 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001174 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001175 return NULL;
1176}
1177
1178static PyObject *
1179_get_crl_dp(X509 *certificate) {
1180 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001181 int i, j;
1182 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001183
Christian Heimes598894f2016-09-05 23:19:05 +02001184#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001185 /* Calls x509v3_cache_extensions and sets up crldp */
1186 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001187#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001188 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001189
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001190 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001191 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001192
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001193 lst = PyList_New(0);
1194 if (lst == NULL)
1195 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001196
1197 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1198 DIST_POINT *dp;
1199 STACK_OF(GENERAL_NAME) *gns;
1200
1201 dp = sk_DIST_POINT_value(dps, i);
1202 gns = dp->distpoint->name.fullname;
1203
1204 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1205 GENERAL_NAME *gn;
1206 ASN1_IA5STRING *uri;
1207 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001208 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001209
1210 gn = sk_GENERAL_NAME_value(gns, j);
1211 if (gn->type != GEN_URI) {
1212 continue;
1213 }
1214 uri = gn->d.uniformResourceIdentifier;
1215 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1216 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001217 if (ouri == NULL)
1218 goto done;
1219
1220 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001221 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001222 if (err < 0)
1223 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001224 }
1225 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001226
1227 /* Convert to tuple. */
1228 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1229
1230 done:
1231 Py_XDECREF(lst);
1232#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001233 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001234#endif
1235 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001236}
1237
1238static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001239_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 PyObject *retval = NULL;
1242 BIO *biobuf = NULL;
1243 PyObject *peer;
1244 PyObject *peer_alt_names = NULL;
1245 PyObject *issuer;
1246 PyObject *version;
1247 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001248 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 ASN1_INTEGER *serialNumber;
1250 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001251 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 ASN1_TIME *notBefore, *notAfter;
1253 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 retval = PyDict_New();
1256 if (retval == NULL)
1257 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 peer = _create_tuple_for_X509_NAME(
1260 X509_get_subject_name(certificate));
1261 if (peer == NULL)
1262 goto fail0;
1263 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1264 Py_DECREF(peer);
1265 goto fail0;
1266 }
1267 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001268
Antoine Pitroufb046912010-11-09 20:21:19 +00001269 issuer = _create_tuple_for_X509_NAME(
1270 X509_get_issuer_name(certificate));
1271 if (issuer == NULL)
1272 goto fail0;
1273 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001275 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001277 Py_DECREF(issuer);
1278
1279 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001280 if (version == NULL)
1281 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001282 if (PyDict_SetItemString(retval, "version", version) < 0) {
1283 Py_DECREF(version);
1284 goto fail0;
1285 }
1286 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 /* get a memory buffer */
1289 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001290
Antoine Pitroufb046912010-11-09 20:21:19 +00001291 (void) BIO_reset(biobuf);
1292 serialNumber = X509_get_serialNumber(certificate);
1293 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1294 i2a_ASN1_INTEGER(biobuf, serialNumber);
1295 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1296 if (len < 0) {
1297 _setSSLError(NULL, 0, __FILE__, __LINE__);
1298 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001300 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1301 if (sn_obj == NULL)
1302 goto fail1;
1303 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1304 Py_DECREF(sn_obj);
1305 goto fail1;
1306 }
1307 Py_DECREF(sn_obj);
1308
1309 (void) BIO_reset(biobuf);
1310 notBefore = X509_get_notBefore(certificate);
1311 ASN1_TIME_print(biobuf, notBefore);
1312 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1313 if (len < 0) {
1314 _setSSLError(NULL, 0, __FILE__, __LINE__);
1315 goto fail1;
1316 }
1317 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1318 if (pnotBefore == NULL)
1319 goto fail1;
1320 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1321 Py_DECREF(pnotBefore);
1322 goto fail1;
1323 }
1324 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 (void) BIO_reset(biobuf);
1327 notAfter = X509_get_notAfter(certificate);
1328 ASN1_TIME_print(biobuf, notAfter);
1329 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1330 if (len < 0) {
1331 _setSSLError(NULL, 0, __FILE__, __LINE__);
1332 goto fail1;
1333 }
1334 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1335 if (pnotAfter == NULL)
1336 goto fail1;
1337 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1338 Py_DECREF(pnotAfter);
1339 goto fail1;
1340 }
1341 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 peer_alt_names = _get_peer_alt_names(certificate);
1346 if (peer_alt_names == NULL)
1347 goto fail1;
1348 else if (peer_alt_names != Py_None) {
1349 if (PyDict_SetItemString(retval, "subjectAltName",
1350 peer_alt_names) < 0) {
1351 Py_DECREF(peer_alt_names);
1352 goto fail1;
1353 }
1354 Py_DECREF(peer_alt_names);
1355 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001356
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001357 /* Authority Information Access: OCSP URIs */
1358 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1359 if (obj == NULL) {
1360 goto fail1;
1361 } else if (obj != Py_None) {
1362 result = PyDict_SetItemString(retval, "OCSP", obj);
1363 Py_DECREF(obj);
1364 if (result < 0) {
1365 goto fail1;
1366 }
1367 }
1368
1369 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1370 if (obj == NULL) {
1371 goto fail1;
1372 } else if (obj != Py_None) {
1373 result = PyDict_SetItemString(retval, "caIssuers", obj);
1374 Py_DECREF(obj);
1375 if (result < 0) {
1376 goto fail1;
1377 }
1378 }
1379
1380 /* CDP (CRL distribution points) */
1381 obj = _get_crl_dp(certificate);
1382 if (obj == NULL) {
1383 goto fail1;
1384 } else if (obj != Py_None) {
1385 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1386 Py_DECREF(obj);
1387 if (result < 0) {
1388 goto fail1;
1389 }
1390 }
1391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 BIO_free(biobuf);
1393 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001394
1395 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 if (biobuf != NULL)
1397 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001398 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 Py_XDECREF(retval);
1400 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001401}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001402
Christian Heimes9a5395a2013-06-17 15:44:12 +02001403static PyObject *
1404_certificate_to_der(X509 *certificate)
1405{
1406 unsigned char *bytes_buf = NULL;
1407 int len;
1408 PyObject *retval;
1409
1410 bytes_buf = NULL;
1411 len = i2d_X509(certificate, &bytes_buf);
1412 if (len < 0) {
1413 _setSSLError(NULL, 0, __FILE__, __LINE__);
1414 return NULL;
1415 }
1416 /* this is actually an immutable bytes sequence */
1417 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1418 OPENSSL_free(bytes_buf);
1419 return retval;
1420}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001422/*[clinic input]
1423_ssl._test_decode_cert
1424 path: object(converter="PyUnicode_FSConverter")
1425 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001427[clinic start generated code]*/
1428
1429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001430_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1431/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001432{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 X509 *x=NULL;
1435 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1438 PyErr_SetString(PySSLErrorObject,
1439 "Can't malloc memory to read file");
1440 goto fail0;
1441 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001443 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 PyErr_SetString(PySSLErrorObject,
1445 "Can't open file");
1446 goto fail0;
1447 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1450 if (x == NULL) {
1451 PyErr_SetString(PySSLErrorObject,
1452 "Error decoding PEM-encoded file");
1453 goto fail0;
1454 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001455
Antoine Pitroufb046912010-11-09 20:21:19 +00001456 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001457 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001458
1459 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001460 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 if (cert != NULL) BIO_free(cert);
1462 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463}
1464
1465
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001466/*[clinic input]
1467_ssl._SSLSocket.peer_certificate
1468 der as binary_mode: bool = False
1469 /
1470
1471Returns the certificate for the peer.
1472
1473If no certificate was provided, returns None. If a certificate was
1474provided, but not validated, returns an empty dictionary. Otherwise
1475returns a dict containing information about the peer certificate.
1476
1477If the optional argument is True, returns a DER-encoded copy of the
1478peer certificate, or None if no certificate was provided. This will
1479return the certificate even if it wasn't validated.
1480[clinic start generated code]*/
1481
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001483_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1484/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487
Antoine Pitrou20b85552013-09-29 19:50:53 +02001488 if (!self->handshake_done) {
1489 PyErr_SetString(PyExc_ValueError,
1490 "handshake not done yet");
1491 return NULL;
1492 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 if (!self->peer_cert)
1494 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001495
Antoine Pitrou721738f2012-08-15 23:20:39 +02001496 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001498 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001500 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 if ((verification & SSL_VERIFY_PEER) == 0)
1502 return PyDict_New();
1503 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001504 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506}
1507
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001508static PyObject *
1509cipher_to_tuple(const SSL_CIPHER *cipher)
1510{
1511 const char *cipher_name, *cipher_protocol;
1512 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 if (retval == NULL)
1514 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001516 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001518 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 PyTuple_SET_ITEM(retval, 0, Py_None);
1520 } else {
1521 v = PyUnicode_FromString(cipher_name);
1522 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001523 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 PyTuple_SET_ITEM(retval, 0, v);
1525 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001526
1527 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001529 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 PyTuple_SET_ITEM(retval, 1, Py_None);
1531 } else {
1532 v = PyUnicode_FromString(cipher_protocol);
1533 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001534 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 PyTuple_SET_ITEM(retval, 1, v);
1536 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001537
1538 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001540 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001544
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001545 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 Py_DECREF(retval);
1547 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548}
1549
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001550/*[clinic input]
1551_ssl._SSLSocket.shared_ciphers
1552[clinic start generated code]*/
1553
1554static PyObject *
1555_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1556/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001557{
1558 STACK_OF(SSL_CIPHER) *ciphers;
1559 int i;
1560 PyObject *res;
1561
Christian Heimes598894f2016-09-05 23:19:05 +02001562 ciphers = SSL_get_ciphers(self->ssl);
1563 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001564 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001565 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1566 if (!res)
1567 return NULL;
1568 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1569 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1570 if (!tup) {
1571 Py_DECREF(res);
1572 return NULL;
1573 }
1574 PyList_SET_ITEM(res, i, tup);
1575 }
1576 return res;
1577}
1578
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001579/*[clinic input]
1580_ssl._SSLSocket.cipher
1581[clinic start generated code]*/
1582
1583static PyObject *
1584_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1585/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001586{
1587 const SSL_CIPHER *current;
1588
1589 if (self->ssl == NULL)
1590 Py_RETURN_NONE;
1591 current = SSL_get_current_cipher(self->ssl);
1592 if (current == NULL)
1593 Py_RETURN_NONE;
1594 return cipher_to_tuple(current);
1595}
1596
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001597/*[clinic input]
1598_ssl._SSLSocket.version
1599[clinic start generated code]*/
1600
1601static PyObject *
1602_ssl__SSLSocket_version_impl(PySSLSocket *self)
1603/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001604{
1605 const char *version;
1606
1607 if (self->ssl == NULL)
1608 Py_RETURN_NONE;
1609 version = SSL_get_version(self->ssl);
1610 if (!strcmp(version, "unknown"))
1611 Py_RETURN_NONE;
1612 return PyUnicode_FromString(version);
1613}
1614
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001615#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001616/*[clinic input]
1617_ssl._SSLSocket.selected_npn_protocol
1618[clinic start generated code]*/
1619
1620static PyObject *
1621_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1622/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1623{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001624 const unsigned char *out;
1625 unsigned int outlen;
1626
Victor Stinner4569cd52013-06-23 14:58:43 +02001627 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001628 &out, &outlen);
1629
1630 if (out == NULL)
1631 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001632 return PyUnicode_FromStringAndSize((char *)out, outlen);
1633}
1634#endif
1635
1636#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001637/*[clinic input]
1638_ssl._SSLSocket.selected_alpn_protocol
1639[clinic start generated code]*/
1640
1641static PyObject *
1642_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1643/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1644{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001645 const unsigned char *out;
1646 unsigned int outlen;
1647
1648 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1649
1650 if (out == NULL)
1651 Py_RETURN_NONE;
1652 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001653}
1654#endif
1655
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001656/*[clinic input]
1657_ssl._SSLSocket.compression
1658[clinic start generated code]*/
1659
1660static PyObject *
1661_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1662/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1663{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001664#ifdef OPENSSL_NO_COMP
1665 Py_RETURN_NONE;
1666#else
1667 const COMP_METHOD *comp_method;
1668 const char *short_name;
1669
1670 if (self->ssl == NULL)
1671 Py_RETURN_NONE;
1672 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001673 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001674 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001675 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001676 if (short_name == NULL)
1677 Py_RETURN_NONE;
1678 return PyUnicode_DecodeFSDefault(short_name);
1679#endif
1680}
1681
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001682static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1683 Py_INCREF(self->ctx);
1684 return self->ctx;
1685}
1686
1687static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1688 void *closure) {
1689
1690 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001691#if !HAVE_SNI
1692 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1693 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001694 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001695#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001696 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001697 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001698 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001699#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001700 } else {
1701 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1702 return -1;
1703 }
1704
1705 return 0;
1706}
1707
1708PyDoc_STRVAR(PySSL_set_context_doc,
1709"_setter_context(ctx)\n\
1710\
1711This changes the context associated with the SSLSocket. This is typically\n\
1712used from within a callback function set by the set_servername_callback\n\
1713on the SSLContext to change the certificate information associated with the\n\
1714SSLSocket before the cryptographic exchange handshake messages\n");
1715
1716
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001717static PyObject *
1718PySSL_get_server_side(PySSLSocket *self, void *c)
1719{
1720 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1721}
1722
1723PyDoc_STRVAR(PySSL_get_server_side_doc,
1724"Whether this is a server-side socket.");
1725
1726static PyObject *
1727PySSL_get_server_hostname(PySSLSocket *self, void *c)
1728{
1729 if (self->server_hostname == NULL)
1730 Py_RETURN_NONE;
1731 Py_INCREF(self->server_hostname);
1732 return self->server_hostname;
1733}
1734
1735PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1736"The currently set server hostname (for SNI).");
1737
1738static PyObject *
1739PySSL_get_owner(PySSLSocket *self, void *c)
1740{
1741 PyObject *owner;
1742
1743 if (self->owner == NULL)
1744 Py_RETURN_NONE;
1745
1746 owner = PyWeakref_GetObject(self->owner);
1747 Py_INCREF(owner);
1748 return owner;
1749}
1750
1751static int
1752PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1753{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001754 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001755 if (self->owner == NULL)
1756 return -1;
1757 return 0;
1758}
1759
1760PyDoc_STRVAR(PySSL_get_owner_doc,
1761"The Python-level owner of this object.\
1762Passed as \"self\" in servername callback.");
1763
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001764
Antoine Pitrou152efa22010-05-16 18:19:27 +00001765static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001766{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 if (self->peer_cert) /* Possible not to have one? */
1768 X509_free (self->peer_cert);
1769 if (self->ssl)
1770 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001772 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001773 Py_XDECREF(self->server_hostname);
1774 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001776}
1777
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001778/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001779 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001780 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001781 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001782
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001783static int
Victor Stinner14690702015-04-06 22:46:13 +02001784PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001785{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001786 int rc;
1787#ifdef HAVE_POLL
1788 struct pollfd pollfd;
1789 _PyTime_t ms;
1790#else
1791 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 fd_set fds;
1793 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001794#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001797 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001799 else if (timeout < 0) {
1800 if (s->sock_timeout > 0)
1801 return SOCKET_HAS_TIMED_OUT;
1802 else
1803 return SOCKET_IS_BLOCKING;
1804 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001807 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 /* Prefer poll, if available, since you can poll() any fd
1811 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001812#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001813 pollfd.fd = s->sock_fd;
1814 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001815
Victor Stinner14690702015-04-06 22:46:13 +02001816 /* timeout is in seconds, poll() uses milliseconds */
1817 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001818 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001819
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001820 PySSL_BEGIN_ALLOW_THREADS
1821 rc = poll(&pollfd, 1, (int)ms);
1822 PySSL_END_ALLOW_THREADS
1823#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001825 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001827
Victor Stinner14690702015-04-06 22:46:13 +02001828 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 FD_ZERO(&fds);
1831 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001832
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001833 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001835 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001837 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001838 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001839 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001841#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1844 (when we are able to write or when there's something to read) */
1845 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001846}
1847
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001848/*[clinic input]
1849_ssl._SSLSocket.write
1850 b: Py_buffer
1851 /
1852
1853Writes the bytes-like object b into the SSL object.
1854
1855Returns the number of bytes written.
1856[clinic start generated code]*/
1857
1858static PyObject *
1859_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1860/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001861{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 int len;
1863 int sockstate;
1864 int err;
1865 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001866 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001867 _PyTime_t timeout, deadline = 0;
1868 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001869
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001870 if (sock != NULL) {
1871 if (((PyObject*)sock) == Py_None) {
1872 _setSSLError("Underlying socket connection gone",
1873 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1874 return NULL;
1875 }
1876 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 }
1878
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001880 PyErr_Format(PyExc_OverflowError,
1881 "string longer than %d bytes", INT_MAX);
1882 goto error;
1883 }
1884
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001885 if (sock != NULL) {
1886 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001887 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001888 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1889 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1890 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891
Victor Stinner14690702015-04-06 22:46:13 +02001892 timeout = GET_SOCKET_TIMEOUT(sock);
1893 has_timeout = (timeout > 0);
1894 if (has_timeout)
1895 deadline = _PyTime_GetMonotonicClock() + timeout;
1896
1897 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001899 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 "The write operation timed out");
1901 goto error;
1902 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1903 PyErr_SetString(PySSLErrorObject,
1904 "Underlying socket has been closed.");
1905 goto error;
1906 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1907 PyErr_SetString(PySSLErrorObject,
1908 "Underlying socket too large for select().");
1909 goto error;
1910 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001914 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001915 err = SSL_get_error(self->ssl, len);
1916 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001917
1918 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001920
Victor Stinner14690702015-04-06 22:46:13 +02001921 if (has_timeout)
1922 timeout = deadline - _PyTime_GetMonotonicClock();
1923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001925 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001927 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 } else {
1929 sockstate = SOCKET_OPERATION_OK;
1930 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001933 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 "The write operation timed out");
1935 goto error;
1936 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1937 PyErr_SetString(PySSLErrorObject,
1938 "Underlying socket has been closed.");
1939 goto error;
1940 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1941 break;
1942 }
1943 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001944
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001945 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 if (len > 0)
1947 return PyLong_FromLong(len);
1948 else
1949 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001950
1951error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001952 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954}
1955
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001956/*[clinic input]
1957_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001958
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001959Returns the number of already decrypted bytes available for read, pending on the connection.
1960[clinic start generated code]*/
1961
1962static PyObject *
1963_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1964/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001965{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 PySSL_BEGIN_ALLOW_THREADS
1969 count = SSL_pending(self->ssl);
1970 PySSL_END_ALLOW_THREADS
1971 if (count < 0)
1972 return PySSL_SetError(self, count, __FILE__, __LINE__);
1973 else
1974 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001975}
1976
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001977/*[clinic input]
1978_ssl._SSLSocket.read
1979 size as len: int
1980 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001981 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001982 ]
1983 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001984
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001985Read up to size bytes from the SSL socket.
1986[clinic start generated code]*/
1987
1988static PyObject *
1989_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1990 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001991/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001992{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001995 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 int sockstate;
1997 int err;
1998 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001999 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002000 _PyTime_t timeout, deadline = 0;
2001 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002002
Martin Panter5503d472016-03-27 05:35:19 +00002003 if (!group_right_1 && len < 0) {
2004 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2005 return NULL;
2006 }
2007
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002008 if (sock != NULL) {
2009 if (((PyObject*)sock) == Py_None) {
2010 _setSSLError("Underlying socket connection gone",
2011 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2012 return NULL;
2013 }
2014 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002015 }
2016
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002017 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002018 dest = PyBytes_FromStringAndSize(NULL, len);
2019 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002020 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002021 if (len == 0) {
2022 Py_XDECREF(sock);
2023 return dest;
2024 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002025 mem = PyBytes_AS_STRING(dest);
2026 }
2027 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002028 mem = buffer->buf;
2029 if (len <= 0 || len > buffer->len) {
2030 len = (int) buffer->len;
2031 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002032 PyErr_SetString(PyExc_OverflowError,
2033 "maximum length can't fit in a C 'int'");
2034 goto error;
2035 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002036 if (len == 0) {
2037 count = 0;
2038 goto done;
2039 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002040 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 }
2042
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002043 if (sock != NULL) {
2044 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002045 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002046 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2047 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2048 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049
Victor Stinner14690702015-04-06 22:46:13 +02002050 timeout = GET_SOCKET_TIMEOUT(sock);
2051 has_timeout = (timeout > 0);
2052 if (has_timeout)
2053 deadline = _PyTime_GetMonotonicClock() + timeout;
2054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002056 PySSL_BEGIN_ALLOW_THREADS
2057 count = SSL_read(self->ssl, mem, len);
2058 err = SSL_get_error(self->ssl, count);
2059 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 if (PyErr_CheckSignals())
2062 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002063
Victor Stinner14690702015-04-06 22:46:13 +02002064 if (has_timeout)
2065 timeout = deadline - _PyTime_GetMonotonicClock();
2066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002067 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002068 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002069 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002070 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002071 } else if (err == SSL_ERROR_ZERO_RETURN &&
2072 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002073 {
2074 count = 0;
2075 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002077 else
2078 sockstate = SOCKET_OPERATION_OK;
2079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002081 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 "The read operation timed out");
2083 goto error;
2084 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2085 break;
2086 }
2087 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 if (count <= 0) {
2090 PySSL_SetError(self, count, __FILE__, __LINE__);
2091 goto error;
2092 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002093
2094done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002095 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002096 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002097 _PyBytes_Resize(&dest, count);
2098 return dest;
2099 }
2100 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002101 return PyLong_FromLong(count);
2102 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002103
2104error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002105 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002106 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002107 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002108 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002109}
2110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002111/*[clinic input]
2112_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002114Does the SSL shutdown handshake with the remote end.
2115
2116Returns the underlying socket object.
2117[clinic start generated code]*/
2118
2119static PyObject *
2120_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2121/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002122{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 int err, ssl_err, sockstate, nonblocking;
2124 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002125 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002126 _PyTime_t timeout, deadline = 0;
2127 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002128
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002129 if (sock != NULL) {
2130 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002131 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002132 _setSSLError("Underlying socket connection gone",
2133 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2134 return NULL;
2135 }
2136 Py_INCREF(sock);
2137
2138 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002139 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002140 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2141 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143
Victor Stinner14690702015-04-06 22:46:13 +02002144 timeout = GET_SOCKET_TIMEOUT(sock);
2145 has_timeout = (timeout > 0);
2146 if (has_timeout)
2147 deadline = _PyTime_GetMonotonicClock() + timeout;
2148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 while (1) {
2150 PySSL_BEGIN_ALLOW_THREADS
2151 /* Disable read-ahead so that unwrap can work correctly.
2152 * Otherwise OpenSSL might read in too much data,
2153 * eating clear text data that happens to be
2154 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002155 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 * function is used and the shutdown_seen_zero != 0
2157 * condition is met.
2158 */
2159 if (self->shutdown_seen_zero)
2160 SSL_set_read_ahead(self->ssl, 0);
2161 err = SSL_shutdown(self->ssl);
2162 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2165 if (err > 0)
2166 break;
2167 if (err == 0) {
2168 /* Don't loop endlessly; instead preserve legacy
2169 behaviour of trying SSL_shutdown() only twice.
2170 This looks necessary for OpenSSL < 0.9.8m */
2171 if (++zeros > 1)
2172 break;
2173 /* Shutdown was sent, now try receiving */
2174 self->shutdown_seen_zero = 1;
2175 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002176 }
2177
Victor Stinner14690702015-04-06 22:46:13 +02002178 if (has_timeout)
2179 timeout = deadline - _PyTime_GetMonotonicClock();
2180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 /* Possibly retry shutdown until timeout or failure */
2182 ssl_err = SSL_get_error(self->ssl, err);
2183 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002184 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002186 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002187 else
2188 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2191 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002192 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 "The read operation timed out");
2194 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002195 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002197 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 }
2199 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2200 PyErr_SetString(PySSLErrorObject,
2201 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002202 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 }
2204 else if (sockstate != SOCKET_OPERATION_OK)
2205 /* Retain the SSL error code */
2206 break;
2207 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002208
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002209 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002210 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002214 /* It's already INCREF'ed */
2215 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002216 else
2217 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002218
2219error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002220 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002221 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002222}
2223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002224/*[clinic input]
2225_ssl._SSLSocket.tls_unique_cb
2226
2227Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2228
2229If the TLS handshake is not yet complete, None is returned.
2230[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002231
Antoine Pitroud6494802011-07-21 01:11:30 +02002232static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002233_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2234/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002235{
2236 PyObject *retval = NULL;
2237 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002238 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002239
2240 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2241 /* if session is resumed XOR we are the client */
2242 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2243 }
2244 else {
2245 /* if a new session XOR we are the server */
2246 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2247 }
2248
2249 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002250 if (len == 0)
2251 Py_RETURN_NONE;
2252
2253 retval = PyBytes_FromStringAndSize(buf, len);
2254
2255 return retval;
2256}
2257
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002258static PyGetSetDef ssl_getsetlist[] = {
2259 {"context", (getter) PySSL_get_context,
2260 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002261 {"server_side", (getter) PySSL_get_server_side, NULL,
2262 PySSL_get_server_side_doc},
2263 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2264 PySSL_get_server_hostname_doc},
2265 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2266 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002267 {NULL}, /* sentinel */
2268};
2269
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002270static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002271 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2272 _SSL__SSLSOCKET_WRITE_METHODDEF
2273 _SSL__SSLSOCKET_READ_METHODDEF
2274 _SSL__SSLSOCKET_PENDING_METHODDEF
2275 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2276 _SSL__SSLSOCKET_CIPHER_METHODDEF
2277 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2278 _SSL__SSLSOCKET_VERSION_METHODDEF
2279 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2280 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2281 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2282 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2283 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002285};
2286
Antoine Pitrou152efa22010-05-16 18:19:27 +00002287static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002289 "_ssl._SSLSocket", /*tp_name*/
2290 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 0, /*tp_itemsize*/
2292 /* methods */
2293 (destructor)PySSL_dealloc, /*tp_dealloc*/
2294 0, /*tp_print*/
2295 0, /*tp_getattr*/
2296 0, /*tp_setattr*/
2297 0, /*tp_reserved*/
2298 0, /*tp_repr*/
2299 0, /*tp_as_number*/
2300 0, /*tp_as_sequence*/
2301 0, /*tp_as_mapping*/
2302 0, /*tp_hash*/
2303 0, /*tp_call*/
2304 0, /*tp_str*/
2305 0, /*tp_getattro*/
2306 0, /*tp_setattro*/
2307 0, /*tp_as_buffer*/
2308 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2309 0, /*tp_doc*/
2310 0, /*tp_traverse*/
2311 0, /*tp_clear*/
2312 0, /*tp_richcompare*/
2313 0, /*tp_weaklistoffset*/
2314 0, /*tp_iter*/
2315 0, /*tp_iternext*/
2316 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002317 0, /*tp_members*/
2318 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002319};
2320
Antoine Pitrou152efa22010-05-16 18:19:27 +00002321
2322/*
2323 * _SSLContext objects
2324 */
2325
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002326/*[clinic input]
2327@classmethod
2328_ssl._SSLContext.__new__
2329 protocol as proto_version: int
2330 /
2331[clinic start generated code]*/
2332
Antoine Pitrou152efa22010-05-16 18:19:27 +00002333static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002334_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2335/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002336{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002337 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002338 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002339 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002340#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002341 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002342#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002343
Antoine Pitrou152efa22010-05-16 18:19:27 +00002344 PySSL_BEGIN_ALLOW_THREADS
2345 if (proto_version == PY_SSL_VERSION_TLS1)
2346 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002347#if HAVE_TLSv1_2
2348 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2349 ctx = SSL_CTX_new(TLSv1_1_method());
2350 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2351 ctx = SSL_CTX_new(TLSv1_2_method());
2352#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002353#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002354 else if (proto_version == PY_SSL_VERSION_SSL3)
2355 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002356#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002357#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002358 else if (proto_version == PY_SSL_VERSION_SSL2)
2359 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002360#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002361 else if (proto_version == PY_SSL_VERSION_TLS)
2362 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002363 else
2364 proto_version = -1;
2365 PySSL_END_ALLOW_THREADS
2366
2367 if (proto_version == -1) {
2368 PyErr_SetString(PyExc_ValueError,
2369 "invalid protocol version");
2370 return NULL;
2371 }
2372 if (ctx == NULL) {
2373 PyErr_SetString(PySSLErrorObject,
2374 "failed to allocate SSL context");
2375 return NULL;
2376 }
2377
2378 assert(type != NULL && type->tp_alloc != NULL);
2379 self = (PySSLContext *) type->tp_alloc(type, 0);
2380 if (self == NULL) {
2381 SSL_CTX_free(ctx);
2382 return NULL;
2383 }
2384 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002385#ifdef OPENSSL_NPN_NEGOTIATED
2386 self->npn_protocols = NULL;
2387#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002388#ifdef HAVE_ALPN
2389 self->alpn_protocols = NULL;
2390#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002391#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002392 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002393#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002394 /* Don't check host name by default */
2395 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002396 /* Defaults */
2397 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002398 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2399 if (proto_version != PY_SSL_VERSION_SSL2)
2400 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002401 if (proto_version != PY_SSL_VERSION_SSL3)
2402 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002403 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002404
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002405#if defined(SSL_MODE_RELEASE_BUFFERS)
2406 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2407 usage for no cost at all. However, don't do this for OpenSSL versions
2408 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2409 2014-0198. I can't find exactly which beta fixed this CVE, so be
2410 conservative and assume it wasn't fixed until release. We do this check
2411 at runtime to avoid problems from the dynamic linker.
2412 See #25672 for more on this. */
2413 libver = SSLeay();
2414 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2415 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2416 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2417 }
2418#endif
2419
2420
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002421#ifndef OPENSSL_NO_ECDH
2422 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2423 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002424 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2425 */
2426#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002427 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2428#else
2429 {
2430 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2431 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2432 EC_KEY_free(key);
2433 }
2434#endif
2435#endif
2436
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002437#define SID_CTX "Python"
2438 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2439 sizeof(SID_CTX));
2440#undef SID_CTX
2441
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002442#ifdef X509_V_FLAG_TRUSTED_FIRST
2443 {
2444 /* Improve trust chain building when cross-signed intermediate
2445 certificates are present. See https://bugs.python.org/issue23476. */
2446 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2447 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2448 }
2449#endif
2450
Antoine Pitrou152efa22010-05-16 18:19:27 +00002451 return (PyObject *)self;
2452}
2453
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002454static int
2455context_traverse(PySSLContext *self, visitproc visit, void *arg)
2456{
2457#ifndef OPENSSL_NO_TLSEXT
2458 Py_VISIT(self->set_hostname);
2459#endif
2460 return 0;
2461}
2462
2463static int
2464context_clear(PySSLContext *self)
2465{
2466#ifndef OPENSSL_NO_TLSEXT
2467 Py_CLEAR(self->set_hostname);
2468#endif
2469 return 0;
2470}
2471
Antoine Pitrou152efa22010-05-16 18:19:27 +00002472static void
2473context_dealloc(PySSLContext *self)
2474{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002475 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002476 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002477#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002478 PyMem_FREE(self->npn_protocols);
2479#endif
2480#ifdef HAVE_ALPN
2481 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002482#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002483 Py_TYPE(self)->tp_free(self);
2484}
2485
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002486/*[clinic input]
2487_ssl._SSLContext.set_ciphers
2488 cipherlist: str
2489 /
2490[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492static PyObject *
2493_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2494/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2495{
2496 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002497 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002498 /* Clearing the error queue is necessary on some OpenSSL versions,
2499 otherwise the error will be reported again when another SSL call
2500 is done. */
2501 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002502 PyErr_SetString(PySSLErrorObject,
2503 "No cipher can be selected.");
2504 return NULL;
2505 }
2506 Py_RETURN_NONE;
2507}
2508
Benjamin Petersonc54de472015-01-28 12:06:39 -05002509#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002510static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002511do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2512 const unsigned char *server_protocols, unsigned int server_protocols_len,
2513 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002514{
Benjamin Peterson88615022015-01-23 17:30:26 -05002515 int ret;
2516 if (client_protocols == NULL) {
2517 client_protocols = (unsigned char *)"";
2518 client_protocols_len = 0;
2519 }
2520 if (server_protocols == NULL) {
2521 server_protocols = (unsigned char *)"";
2522 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002523 }
2524
Benjamin Peterson88615022015-01-23 17:30:26 -05002525 ret = SSL_select_next_proto(out, outlen,
2526 server_protocols, server_protocols_len,
2527 client_protocols, client_protocols_len);
2528 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2529 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002530
2531 return SSL_TLSEXT_ERR_OK;
2532}
2533
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002534/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2535static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002536_advertiseNPN_cb(SSL *s,
2537 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002538 void *args)
2539{
2540 PySSLContext *ssl_ctx = (PySSLContext *) args;
2541
2542 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002543 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002544 *len = 0;
2545 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002546 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002547 *len = ssl_ctx->npn_protocols_len;
2548 }
2549
2550 return SSL_TLSEXT_ERR_OK;
2551}
2552/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2553static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002554_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002555 unsigned char **out, unsigned char *outlen,
2556 const unsigned char *server, unsigned int server_len,
2557 void *args)
2558{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002559 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002560 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002561 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002562}
2563#endif
2564
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002565/*[clinic input]
2566_ssl._SSLContext._set_npn_protocols
2567 protos: Py_buffer
2568 /
2569[clinic start generated code]*/
2570
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002571static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002572_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2573 Py_buffer *protos)
2574/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002575{
2576#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002577 PyMem_Free(self->npn_protocols);
2578 self->npn_protocols = PyMem_Malloc(protos->len);
2579 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002580 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002581 memcpy(self->npn_protocols, protos->buf, protos->len);
2582 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002583
2584 /* set both server and client callbacks, because the context can
2585 * be used to create both types of sockets */
2586 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2587 _advertiseNPN_cb,
2588 self);
2589 SSL_CTX_set_next_proto_select_cb(self->ctx,
2590 _selectNPN_cb,
2591 self);
2592
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002593 Py_RETURN_NONE;
2594#else
2595 PyErr_SetString(PyExc_NotImplementedError,
2596 "The NPN extension requires OpenSSL 1.0.1 or later.");
2597 return NULL;
2598#endif
2599}
2600
Benjamin Petersoncca27322015-01-23 16:35:37 -05002601#ifdef HAVE_ALPN
2602static int
2603_selectALPN_cb(SSL *s,
2604 const unsigned char **out, unsigned char *outlen,
2605 const unsigned char *client_protocols, unsigned int client_protocols_len,
2606 void *args)
2607{
2608 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002609 return do_protocol_selection(1, (unsigned char **)out, outlen,
2610 ctx->alpn_protocols, ctx->alpn_protocols_len,
2611 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002612}
2613#endif
2614
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002615/*[clinic input]
2616_ssl._SSLContext._set_alpn_protocols
2617 protos: Py_buffer
2618 /
2619[clinic start generated code]*/
2620
Benjamin Petersoncca27322015-01-23 16:35:37 -05002621static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002622_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2623 Py_buffer *protos)
2624/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002625{
2626#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002627 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002628 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002629 if (!self->alpn_protocols)
2630 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002631 memcpy(self->alpn_protocols, protos->buf, protos->len);
2632 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002633
2634 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2635 return PyErr_NoMemory();
2636 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2637
Benjamin Petersoncca27322015-01-23 16:35:37 -05002638 Py_RETURN_NONE;
2639#else
2640 PyErr_SetString(PyExc_NotImplementedError,
2641 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2642 return NULL;
2643#endif
2644}
2645
Antoine Pitrou152efa22010-05-16 18:19:27 +00002646static PyObject *
2647get_verify_mode(PySSLContext *self, void *c)
2648{
2649 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2650 case SSL_VERIFY_NONE:
2651 return PyLong_FromLong(PY_SSL_CERT_NONE);
2652 case SSL_VERIFY_PEER:
2653 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2654 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2655 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2656 }
2657 PyErr_SetString(PySSLErrorObject,
2658 "invalid return value from SSL_CTX_get_verify_mode");
2659 return NULL;
2660}
2661
2662static int
2663set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2664{
2665 int n, mode;
2666 if (!PyArg_Parse(arg, "i", &n))
2667 return -1;
2668 if (n == PY_SSL_CERT_NONE)
2669 mode = SSL_VERIFY_NONE;
2670 else if (n == PY_SSL_CERT_OPTIONAL)
2671 mode = SSL_VERIFY_PEER;
2672 else if (n == PY_SSL_CERT_REQUIRED)
2673 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2674 else {
2675 PyErr_SetString(PyExc_ValueError,
2676 "invalid value for verify_mode");
2677 return -1;
2678 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002679 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2680 PyErr_SetString(PyExc_ValueError,
2681 "Cannot set verify_mode to CERT_NONE when "
2682 "check_hostname is enabled.");
2683 return -1;
2684 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002685 SSL_CTX_set_verify(self->ctx, mode, NULL);
2686 return 0;
2687}
2688
2689static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002690get_verify_flags(PySSLContext *self, void *c)
2691{
2692 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002693 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002694 unsigned long flags;
2695
2696 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002697 param = X509_STORE_get0_param(store);
2698 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002699 return PyLong_FromUnsignedLong(flags);
2700}
2701
2702static int
2703set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2704{
2705 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002706 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002707 unsigned long new_flags, flags, set, clear;
2708
2709 if (!PyArg_Parse(arg, "k", &new_flags))
2710 return -1;
2711 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002712 param = X509_STORE_get0_param(store);
2713 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002714 clear = flags & ~new_flags;
2715 set = ~flags & new_flags;
2716 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02002717 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01002718 _setSSLError(NULL, 0, __FILE__, __LINE__);
2719 return -1;
2720 }
2721 }
2722 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02002723 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01002724 _setSSLError(NULL, 0, __FILE__, __LINE__);
2725 return -1;
2726 }
2727 }
2728 return 0;
2729}
2730
2731static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002732get_options(PySSLContext *self, void *c)
2733{
2734 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2735}
2736
2737static int
2738set_options(PySSLContext *self, PyObject *arg, void *c)
2739{
2740 long new_opts, opts, set, clear;
2741 if (!PyArg_Parse(arg, "l", &new_opts))
2742 return -1;
2743 opts = SSL_CTX_get_options(self->ctx);
2744 clear = opts & ~new_opts;
2745 set = ~opts & new_opts;
2746 if (clear) {
2747#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2748 SSL_CTX_clear_options(self->ctx, clear);
2749#else
2750 PyErr_SetString(PyExc_ValueError,
2751 "can't clear options before OpenSSL 0.9.8m");
2752 return -1;
2753#endif
2754 }
2755 if (set)
2756 SSL_CTX_set_options(self->ctx, set);
2757 return 0;
2758}
2759
Christian Heimes1aa9a752013-12-02 02:41:19 +01002760static PyObject *
2761get_check_hostname(PySSLContext *self, void *c)
2762{
2763 return PyBool_FromLong(self->check_hostname);
2764}
2765
2766static int
2767set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2768{
2769 int check_hostname;
2770 if (!PyArg_Parse(arg, "p", &check_hostname))
2771 return -1;
2772 if (check_hostname &&
2773 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2774 PyErr_SetString(PyExc_ValueError,
2775 "check_hostname needs a SSL context with either "
2776 "CERT_OPTIONAL or CERT_REQUIRED");
2777 return -1;
2778 }
2779 self->check_hostname = check_hostname;
2780 return 0;
2781}
2782
2783
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002784typedef struct {
2785 PyThreadState *thread_state;
2786 PyObject *callable;
2787 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002788 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002789 int error;
2790} _PySSLPasswordInfo;
2791
2792static int
2793_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2794 const char *bad_type_error)
2795{
2796 /* Set the password and size fields of a _PySSLPasswordInfo struct
2797 from a unicode, bytes, or byte array object.
2798 The password field will be dynamically allocated and must be freed
2799 by the caller */
2800 PyObject *password_bytes = NULL;
2801 const char *data = NULL;
2802 Py_ssize_t size;
2803
2804 if (PyUnicode_Check(password)) {
2805 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2806 if (!password_bytes) {
2807 goto error;
2808 }
2809 data = PyBytes_AS_STRING(password_bytes);
2810 size = PyBytes_GET_SIZE(password_bytes);
2811 } else if (PyBytes_Check(password)) {
2812 data = PyBytes_AS_STRING(password);
2813 size = PyBytes_GET_SIZE(password);
2814 } else if (PyByteArray_Check(password)) {
2815 data = PyByteArray_AS_STRING(password);
2816 size = PyByteArray_GET_SIZE(password);
2817 } else {
2818 PyErr_SetString(PyExc_TypeError, bad_type_error);
2819 goto error;
2820 }
2821
Victor Stinner9ee02032013-06-23 15:08:23 +02002822 if (size > (Py_ssize_t)INT_MAX) {
2823 PyErr_Format(PyExc_ValueError,
2824 "password cannot be longer than %d bytes", INT_MAX);
2825 goto error;
2826 }
2827
Victor Stinner11ebff22013-07-07 17:07:52 +02002828 PyMem_Free(pw_info->password);
2829 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002830 if (!pw_info->password) {
2831 PyErr_SetString(PyExc_MemoryError,
2832 "unable to allocate password buffer");
2833 goto error;
2834 }
2835 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002836 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002837
2838 Py_XDECREF(password_bytes);
2839 return 1;
2840
2841error:
2842 Py_XDECREF(password_bytes);
2843 return 0;
2844}
2845
2846static int
2847_password_callback(char *buf, int size, int rwflag, void *userdata)
2848{
2849 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2850 PyObject *fn_ret = NULL;
2851
2852 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2853
2854 if (pw_info->callable) {
2855 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2856 if (!fn_ret) {
2857 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2858 core python API, so we could use it to add a frame here */
2859 goto error;
2860 }
2861
2862 if (!_pwinfo_set(pw_info, fn_ret,
2863 "password callback must return a string")) {
2864 goto error;
2865 }
2866 Py_CLEAR(fn_ret);
2867 }
2868
2869 if (pw_info->size > size) {
2870 PyErr_Format(PyExc_ValueError,
2871 "password cannot be longer than %d bytes", size);
2872 goto error;
2873 }
2874
2875 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2876 memcpy(buf, pw_info->password, pw_info->size);
2877 return pw_info->size;
2878
2879error:
2880 Py_XDECREF(fn_ret);
2881 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2882 pw_info->error = 1;
2883 return -1;
2884}
2885
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002886/*[clinic input]
2887_ssl._SSLContext.load_cert_chain
2888 certfile: object
2889 keyfile: object = NULL
2890 password: object = NULL
2891
2892[clinic start generated code]*/
2893
Antoine Pitroub5218772010-05-21 09:56:06 +00002894static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002895_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2896 PyObject *keyfile, PyObject *password)
2897/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002898{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002899 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02002900 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2901 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002902 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903 int r;
2904
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002905 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002906 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002907 if (keyfile == Py_None)
2908 keyfile = NULL;
2909 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2910 PyErr_SetString(PyExc_TypeError,
2911 "certfile should be a valid filesystem path");
2912 return NULL;
2913 }
2914 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2915 PyErr_SetString(PyExc_TypeError,
2916 "keyfile should be a valid filesystem path");
2917 goto error;
2918 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002919 if (password && password != Py_None) {
2920 if (PyCallable_Check(password)) {
2921 pw_info.callable = password;
2922 } else if (!_pwinfo_set(&pw_info, password,
2923 "password should be a string or callable")) {
2924 goto error;
2925 }
2926 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2927 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2928 }
2929 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002930 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2931 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002932 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002933 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002934 if (pw_info.error) {
2935 ERR_clear_error();
2936 /* the password callback has already set the error information */
2937 }
2938 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002939 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002940 PyErr_SetFromErrno(PyExc_IOError);
2941 }
2942 else {
2943 _setSSLError(NULL, 0, __FILE__, __LINE__);
2944 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002945 goto error;
2946 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002947 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002948 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2950 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002951 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2952 Py_CLEAR(keyfile_bytes);
2953 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002955 if (pw_info.error) {
2956 ERR_clear_error();
2957 /* the password callback has already set the error information */
2958 }
2959 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002960 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002961 PyErr_SetFromErrno(PyExc_IOError);
2962 }
2963 else {
2964 _setSSLError(NULL, 0, __FILE__, __LINE__);
2965 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002966 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002967 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002968 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002969 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002970 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971 if (r != 1) {
2972 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002973 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002974 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002975 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2976 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002977 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002978 Py_RETURN_NONE;
2979
2980error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002981 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2982 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002983 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002984 Py_XDECREF(keyfile_bytes);
2985 Py_XDECREF(certfile_bytes);
2986 return NULL;
2987}
2988
Christian Heimesefff7062013-11-21 03:35:02 +01002989/* internal helper function, returns -1 on error
2990 */
2991static int
2992_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2993 int filetype)
2994{
2995 BIO *biobuf = NULL;
2996 X509_STORE *store;
2997 int retval = 0, err, loaded = 0;
2998
2999 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3000
3001 if (len <= 0) {
3002 PyErr_SetString(PyExc_ValueError,
3003 "Empty certificate data");
3004 return -1;
3005 } else if (len > INT_MAX) {
3006 PyErr_SetString(PyExc_OverflowError,
3007 "Certificate data is too long.");
3008 return -1;
3009 }
3010
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003011 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003012 if (biobuf == NULL) {
3013 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3014 return -1;
3015 }
3016
3017 store = SSL_CTX_get_cert_store(self->ctx);
3018 assert(store != NULL);
3019
3020 while (1) {
3021 X509 *cert = NULL;
3022 int r;
3023
3024 if (filetype == SSL_FILETYPE_ASN1) {
3025 cert = d2i_X509_bio(biobuf, NULL);
3026 } else {
3027 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003028 SSL_CTX_get_default_passwd_cb(self->ctx),
3029 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3030 );
Christian Heimesefff7062013-11-21 03:35:02 +01003031 }
3032 if (cert == NULL) {
3033 break;
3034 }
3035 r = X509_STORE_add_cert(store, cert);
3036 X509_free(cert);
3037 if (!r) {
3038 err = ERR_peek_last_error();
3039 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3040 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3041 /* cert already in hash table, not an error */
3042 ERR_clear_error();
3043 } else {
3044 break;
3045 }
3046 }
3047 loaded++;
3048 }
3049
3050 err = ERR_peek_last_error();
3051 if ((filetype == SSL_FILETYPE_ASN1) &&
3052 (loaded > 0) &&
3053 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3054 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3055 /* EOF ASN1 file, not an error */
3056 ERR_clear_error();
3057 retval = 0;
3058 } else if ((filetype == SSL_FILETYPE_PEM) &&
3059 (loaded > 0) &&
3060 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3061 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3062 /* EOF PEM file, not an error */
3063 ERR_clear_error();
3064 retval = 0;
3065 } else {
3066 _setSSLError(NULL, 0, __FILE__, __LINE__);
3067 retval = -1;
3068 }
3069
3070 BIO_free(biobuf);
3071 return retval;
3072}
3073
3074
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003075/*[clinic input]
3076_ssl._SSLContext.load_verify_locations
3077 cafile: object = NULL
3078 capath: object = NULL
3079 cadata: object = NULL
3080
3081[clinic start generated code]*/
3082
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003084_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3085 PyObject *cafile,
3086 PyObject *capath,
3087 PyObject *cadata)
3088/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3091 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003092 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003094 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095 if (cafile == Py_None)
3096 cafile = NULL;
3097 if (capath == Py_None)
3098 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003099 if (cadata == Py_None)
3100 cadata = NULL;
3101
3102 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003103 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003104 "cafile, capath and cadata cannot be all omitted");
3105 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003106 }
3107 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3108 PyErr_SetString(PyExc_TypeError,
3109 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003110 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111 }
3112 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003113 PyErr_SetString(PyExc_TypeError,
3114 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003115 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003116 }
Christian Heimesefff7062013-11-21 03:35:02 +01003117
3118 /* validata cadata type and load cadata */
3119 if (cadata) {
3120 Py_buffer buf;
3121 PyObject *cadata_ascii = NULL;
3122
3123 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3124 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3125 PyBuffer_Release(&buf);
3126 PyErr_SetString(PyExc_TypeError,
3127 "cadata should be a contiguous buffer with "
3128 "a single dimension");
3129 goto error;
3130 }
3131 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3132 PyBuffer_Release(&buf);
3133 if (r == -1) {
3134 goto error;
3135 }
3136 } else {
3137 PyErr_Clear();
3138 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3139 if (cadata_ascii == NULL) {
3140 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003141 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003142 "bytes-like object");
3143 goto error;
3144 }
3145 r = _add_ca_certs(self,
3146 PyBytes_AS_STRING(cadata_ascii),
3147 PyBytes_GET_SIZE(cadata_ascii),
3148 SSL_FILETYPE_PEM);
3149 Py_DECREF(cadata_ascii);
3150 if (r == -1) {
3151 goto error;
3152 }
3153 }
3154 }
3155
3156 /* load cafile or capath */
3157 if (cafile || capath) {
3158 if (cafile)
3159 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3160 if (capath)
3161 capath_buf = PyBytes_AS_STRING(capath_bytes);
3162 PySSL_BEGIN_ALLOW_THREADS
3163 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3164 PySSL_END_ALLOW_THREADS
3165 if (r != 1) {
3166 ok = 0;
3167 if (errno != 0) {
3168 ERR_clear_error();
3169 PyErr_SetFromErrno(PyExc_IOError);
3170 }
3171 else {
3172 _setSSLError(NULL, 0, __FILE__, __LINE__);
3173 }
3174 goto error;
3175 }
3176 }
3177 goto end;
3178
3179 error:
3180 ok = 0;
3181 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003182 Py_XDECREF(cafile_bytes);
3183 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003184 if (ok) {
3185 Py_RETURN_NONE;
3186 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003187 return NULL;
3188 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003189}
3190
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003191/*[clinic input]
3192_ssl._SSLContext.load_dh_params
3193 path as filepath: object
3194 /
3195
3196[clinic start generated code]*/
3197
Antoine Pitrou152efa22010-05-16 18:19:27 +00003198static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003199_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3200/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003201{
3202 FILE *f;
3203 DH *dh;
3204
Victor Stinnerdaf45552013-08-28 00:53:59 +02003205 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003206 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003207 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003208
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003209 errno = 0;
3210 PySSL_BEGIN_ALLOW_THREADS
3211 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003212 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003213 PySSL_END_ALLOW_THREADS
3214 if (dh == NULL) {
3215 if (errno != 0) {
3216 ERR_clear_error();
3217 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3218 }
3219 else {
3220 _setSSLError(NULL, 0, __FILE__, __LINE__);
3221 }
3222 return NULL;
3223 }
3224 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3225 _setSSLError(NULL, 0, __FILE__, __LINE__);
3226 DH_free(dh);
3227 Py_RETURN_NONE;
3228}
3229
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003230/*[clinic input]
3231_ssl._SSLContext._wrap_socket
3232 sock: object(subclass_of="PySocketModule.Sock_Type")
3233 server_side: int
3234 server_hostname as hostname_obj: object = None
3235
3236[clinic start generated code]*/
3237
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003238static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3240 int server_side, PyObject *hostname_obj)
3241/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003242{
Antoine Pitroud5323212010-10-22 18:19:07 +00003243 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003244 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245
Antoine Pitroud5323212010-10-22 18:19:07 +00003246 /* server_hostname is either None (or absent), or to be encoded
3247 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003248 if (hostname_obj != Py_None) {
3249 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003250 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003251 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003253 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3254 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003255 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003256 if (hostname != NULL)
3257 PyMem_Free(hostname);
3258 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003259}
3260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003261/*[clinic input]
3262_ssl._SSLContext._wrap_bio
3263 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3264 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3265 server_side: int
3266 server_hostname as hostname_obj: object = None
3267
3268[clinic start generated code]*/
3269
Antoine Pitroub0182c82010-10-12 20:09:02 +00003270static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003271_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3272 PySSLMemoryBIO *outgoing, int server_side,
3273 PyObject *hostname_obj)
3274/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003275{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003276 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003277 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003278
3279 /* server_hostname is either None (or absent), or to be encoded
3280 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003281 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003282 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3283 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003284 }
3285
3286 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3287 incoming, outgoing);
3288
3289 PyMem_Free(hostname);
3290 return res;
3291}
3292
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003293/*[clinic input]
3294_ssl._SSLContext.session_stats
3295[clinic start generated code]*/
3296
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003297static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003298_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3299/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003300{
3301 int r;
3302 PyObject *value, *stats = PyDict_New();
3303 if (!stats)
3304 return NULL;
3305
3306#define ADD_STATS(SSL_NAME, KEY_NAME) \
3307 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3308 if (value == NULL) \
3309 goto error; \
3310 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3311 Py_DECREF(value); \
3312 if (r < 0) \
3313 goto error;
3314
3315 ADD_STATS(number, "number");
3316 ADD_STATS(connect, "connect");
3317 ADD_STATS(connect_good, "connect_good");
3318 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3319 ADD_STATS(accept, "accept");
3320 ADD_STATS(accept_good, "accept_good");
3321 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3322 ADD_STATS(accept, "accept");
3323 ADD_STATS(hits, "hits");
3324 ADD_STATS(misses, "misses");
3325 ADD_STATS(timeouts, "timeouts");
3326 ADD_STATS(cache_full, "cache_full");
3327
3328#undef ADD_STATS
3329
3330 return stats;
3331
3332error:
3333 Py_DECREF(stats);
3334 return NULL;
3335}
3336
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003337/*[clinic input]
3338_ssl._SSLContext.set_default_verify_paths
3339[clinic start generated code]*/
3340
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003341static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003342_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3343/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003344{
3345 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3346 _setSSLError(NULL, 0, __FILE__, __LINE__);
3347 return NULL;
3348 }
3349 Py_RETURN_NONE;
3350}
3351
Antoine Pitrou501da612011-12-21 09:27:41 +01003352#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003353/*[clinic input]
3354_ssl._SSLContext.set_ecdh_curve
3355 name: object
3356 /
3357
3358[clinic start generated code]*/
3359
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003360static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003361_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3362/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003363{
3364 PyObject *name_bytes;
3365 int nid;
3366 EC_KEY *key;
3367
3368 if (!PyUnicode_FSConverter(name, &name_bytes))
3369 return NULL;
3370 assert(PyBytes_Check(name_bytes));
3371 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3372 Py_DECREF(name_bytes);
3373 if (nid == 0) {
3374 PyErr_Format(PyExc_ValueError,
3375 "unknown elliptic curve name %R", name);
3376 return NULL;
3377 }
3378 key = EC_KEY_new_by_curve_name(nid);
3379 if (key == NULL) {
3380 _setSSLError(NULL, 0, __FILE__, __LINE__);
3381 return NULL;
3382 }
3383 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3384 EC_KEY_free(key);
3385 Py_RETURN_NONE;
3386}
Antoine Pitrou501da612011-12-21 09:27:41 +01003387#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003388
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003389#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003390static int
3391_servername_callback(SSL *s, int *al, void *args)
3392{
3393 int ret;
3394 PySSLContext *ssl_ctx = (PySSLContext *) args;
3395 PySSLSocket *ssl;
3396 PyObject *servername_o;
3397 PyObject *servername_idna;
3398 PyObject *result;
3399 /* The high-level ssl.SSLSocket object */
3400 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003401 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003402#ifdef WITH_THREAD
3403 PyGILState_STATE gstate = PyGILState_Ensure();
3404#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003405
3406 if (ssl_ctx->set_hostname == NULL) {
3407 /* remove race condition in this the call back while if removing the
3408 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003409#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003410 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003411#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003412 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003413 }
3414
3415 ssl = SSL_get_app_data(s);
3416 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003417
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003418 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003419 * SSL connection and that has a .context attribute that can be changed to
3420 * identify the requested hostname. Since the official API is the Python
3421 * level API we want to pass the callback a Python level object rather than
3422 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3423 * SSLObject) that will be passed. Otherwise if there's a socket then that
3424 * will be passed. If both do not exist only then the C-level object is
3425 * passed. */
3426 if (ssl->owner)
3427 ssl_socket = PyWeakref_GetObject(ssl->owner);
3428 else if (ssl->Socket)
3429 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3430 else
3431 ssl_socket = (PyObject *) ssl;
3432
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003433 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003434 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003435 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003436
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003437 if (servername == NULL) {
3438 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3439 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003440 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003441 else {
3442 servername_o = PyBytes_FromString(servername);
3443 if (servername_o == NULL) {
3444 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3445 goto error;
3446 }
3447 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3448 if (servername_idna == NULL) {
3449 PyErr_WriteUnraisable(servername_o);
3450 Py_DECREF(servername_o);
3451 goto error;
3452 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003453 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003454 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3455 servername_idna, ssl_ctx, NULL);
3456 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003457 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003458 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003459
3460 if (result == NULL) {
3461 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3462 *al = SSL_AD_HANDSHAKE_FAILURE;
3463 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3464 }
3465 else {
3466 if (result != Py_None) {
3467 *al = (int) PyLong_AsLong(result);
3468 if (PyErr_Occurred()) {
3469 PyErr_WriteUnraisable(result);
3470 *al = SSL_AD_INTERNAL_ERROR;
3471 }
3472 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3473 }
3474 else {
3475 ret = SSL_TLSEXT_ERR_OK;
3476 }
3477 Py_DECREF(result);
3478 }
3479
Stefan Krah20d60802013-01-17 17:07:17 +01003480#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003481 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003482#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003483 return ret;
3484
3485error:
3486 Py_DECREF(ssl_socket);
3487 *al = SSL_AD_INTERNAL_ERROR;
3488 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003489#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003490 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003491#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003492 return ret;
3493}
Antoine Pitroua5963382013-03-30 16:39:00 +01003494#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003496/*[clinic input]
3497_ssl._SSLContext.set_servername_callback
3498 method as cb: object
3499 /
3500
3501Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3502
3503If the argument is None then the callback is disabled. The method is called
3504with the SSLSocket, the server name as a string, and the SSLContext object.
3505See RFC 6066 for details of the SNI extension.
3506[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003507
3508static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003509_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3510/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003511{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003512#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003513 Py_CLEAR(self->set_hostname);
3514 if (cb == Py_None) {
3515 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3516 }
3517 else {
3518 if (!PyCallable_Check(cb)) {
3519 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3520 PyErr_SetString(PyExc_TypeError,
3521 "not a callable object");
3522 return NULL;
3523 }
3524 Py_INCREF(cb);
3525 self->set_hostname = cb;
3526 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3527 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3528 }
3529 Py_RETURN_NONE;
3530#else
3531 PyErr_SetString(PyExc_NotImplementedError,
3532 "The TLS extension servername callback, "
3533 "SSL_CTX_set_tlsext_servername_callback, "
3534 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003535 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003536#endif
3537}
3538
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003539/*[clinic input]
3540_ssl._SSLContext.cert_store_stats
3541
3542Returns quantities of loaded X.509 certificates.
3543
3544X.509 certificates with a CA extension and certificate revocation lists
3545inside the context's cert store.
3546
3547NOTE: Certificates in a capath directory aren't loaded unless they have
3548been used at least once.
3549[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003550
3551static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003552_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3553/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003554{
3555 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003556 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003557 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003558 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003559
3560 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003561 objs = X509_STORE_get0_objects(store);
3562 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3563 obj = sk_X509_OBJECT_value(objs, i);
3564 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003565 case X509_LU_X509:
3566 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003567 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003568 ca++;
3569 }
3570 break;
3571 case X509_LU_CRL:
3572 crl++;
3573 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003574 default:
3575 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3576 * As far as I can tell they are internal states and never
3577 * stored in a cert store */
3578 break;
3579 }
3580 }
3581 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3582 "x509_ca", ca);
3583}
3584
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003585/*[clinic input]
3586_ssl._SSLContext.get_ca_certs
3587 binary_form: bool = False
3588
3589Returns a list of dicts with information of loaded CA certs.
3590
3591If the optional argument is True, returns a DER-encoded copy of the CA
3592certificate.
3593
3594NOTE: Certificates in a capath directory aren't loaded unless they have
3595been used at least once.
3596[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003597
3598static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003599_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3600/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003601{
3602 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003603 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003604 PyObject *ci = NULL, *rlist = NULL;
3605 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003606
3607 if ((rlist = PyList_New(0)) == NULL) {
3608 return NULL;
3609 }
3610
3611 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003612 objs = X509_STORE_get0_objects(store);
3613 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003614 X509_OBJECT *obj;
3615 X509 *cert;
3616
Christian Heimes598894f2016-09-05 23:19:05 +02003617 obj = sk_X509_OBJECT_value(objs, i);
3618 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003619 /* not a x509 cert */
3620 continue;
3621 }
3622 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003623 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003624 if (!X509_check_ca(cert)) {
3625 continue;
3626 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003627 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003628 ci = _certificate_to_der(cert);
3629 } else {
3630 ci = _decode_certificate(cert);
3631 }
3632 if (ci == NULL) {
3633 goto error;
3634 }
3635 if (PyList_Append(rlist, ci) == -1) {
3636 goto error;
3637 }
3638 Py_CLEAR(ci);
3639 }
3640 return rlist;
3641
3642 error:
3643 Py_XDECREF(ci);
3644 Py_XDECREF(rlist);
3645 return NULL;
3646}
3647
3648
Antoine Pitrou152efa22010-05-16 18:19:27 +00003649static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003650 {"check_hostname", (getter) get_check_hostname,
3651 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003652 {"options", (getter) get_options,
3653 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003654 {"verify_flags", (getter) get_verify_flags,
3655 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003656 {"verify_mode", (getter) get_verify_mode,
3657 (setter) set_verify_mode, NULL},
3658 {NULL}, /* sentinel */
3659};
3660
3661static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3663 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3664 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3665 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3666 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3667 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3668 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3669 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3670 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3671 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3672 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3673 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3674 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3675 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003676 {NULL, NULL} /* sentinel */
3677};
3678
3679static PyTypeObject PySSLContext_Type = {
3680 PyVarObject_HEAD_INIT(NULL, 0)
3681 "_ssl._SSLContext", /*tp_name*/
3682 sizeof(PySSLContext), /*tp_basicsize*/
3683 0, /*tp_itemsize*/
3684 (destructor)context_dealloc, /*tp_dealloc*/
3685 0, /*tp_print*/
3686 0, /*tp_getattr*/
3687 0, /*tp_setattr*/
3688 0, /*tp_reserved*/
3689 0, /*tp_repr*/
3690 0, /*tp_as_number*/
3691 0, /*tp_as_sequence*/
3692 0, /*tp_as_mapping*/
3693 0, /*tp_hash*/
3694 0, /*tp_call*/
3695 0, /*tp_str*/
3696 0, /*tp_getattro*/
3697 0, /*tp_setattro*/
3698 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003699 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003700 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003701 (traverseproc) context_traverse, /*tp_traverse*/
3702 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003703 0, /*tp_richcompare*/
3704 0, /*tp_weaklistoffset*/
3705 0, /*tp_iter*/
3706 0, /*tp_iternext*/
3707 context_methods, /*tp_methods*/
3708 0, /*tp_members*/
3709 context_getsetlist, /*tp_getset*/
3710 0, /*tp_base*/
3711 0, /*tp_dict*/
3712 0, /*tp_descr_get*/
3713 0, /*tp_descr_set*/
3714 0, /*tp_dictoffset*/
3715 0, /*tp_init*/
3716 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003717 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003718};
3719
3720
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003721/*
3722 * MemoryBIO objects
3723 */
3724
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003725/*[clinic input]
3726@classmethod
3727_ssl.MemoryBIO.__new__
3728
3729[clinic start generated code]*/
3730
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003731static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003732_ssl_MemoryBIO_impl(PyTypeObject *type)
3733/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003734{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003735 BIO *bio;
3736 PySSLMemoryBIO *self;
3737
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003738 bio = BIO_new(BIO_s_mem());
3739 if (bio == NULL) {
3740 PyErr_SetString(PySSLErrorObject,
3741 "failed to allocate BIO");
3742 return NULL;
3743 }
3744 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3745 * just that no data is currently available. The SSL routines should retry
3746 * the read, which we can achieve by calling BIO_set_retry_read(). */
3747 BIO_set_retry_read(bio);
3748 BIO_set_mem_eof_return(bio, -1);
3749
3750 assert(type != NULL && type->tp_alloc != NULL);
3751 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3752 if (self == NULL) {
3753 BIO_free(bio);
3754 return NULL;
3755 }
3756 self->bio = bio;
3757 self->eof_written = 0;
3758
3759 return (PyObject *) self;
3760}
3761
3762static void
3763memory_bio_dealloc(PySSLMemoryBIO *self)
3764{
3765 BIO_free(self->bio);
3766 Py_TYPE(self)->tp_free(self);
3767}
3768
3769static PyObject *
3770memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3771{
3772 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3773}
3774
3775PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3776"The number of bytes pending in the memory BIO.");
3777
3778static PyObject *
3779memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3780{
3781 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3782 && self->eof_written);
3783}
3784
3785PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3786"Whether the memory BIO is at EOF.");
3787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003788/*[clinic input]
3789_ssl.MemoryBIO.read
3790 size as len: int = -1
3791 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003792
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003793Read up to size bytes from the memory BIO.
3794
3795If size is not specified, read the entire buffer.
3796If the return value is an empty bytes instance, this means either
3797EOF or that no data is available. Use the "eof" property to
3798distinguish between the two.
3799[clinic start generated code]*/
3800
3801static PyObject *
3802_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3803/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3804{
3805 int avail, nbytes;
3806 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003807
3808 avail = BIO_ctrl_pending(self->bio);
3809 if ((len < 0) || (len > avail))
3810 len = avail;
3811
3812 result = PyBytes_FromStringAndSize(NULL, len);
3813 if ((result == NULL) || (len == 0))
3814 return result;
3815
3816 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3817 /* There should never be any short reads but check anyway. */
3818 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3819 Py_DECREF(result);
3820 return NULL;
3821 }
3822
3823 return result;
3824}
3825
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003826/*[clinic input]
3827_ssl.MemoryBIO.write
3828 b: Py_buffer
3829 /
3830
3831Writes the bytes b into the memory BIO.
3832
3833Returns the number of bytes written.
3834[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003835
3836static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003837_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3838/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003839{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003840 int nbytes;
3841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003842 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003843 PyErr_Format(PyExc_OverflowError,
3844 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003845 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003846 }
3847
3848 if (self->eof_written) {
3849 PyErr_SetString(PySSLErrorObject,
3850 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003851 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003852 }
3853
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003854 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003855 if (nbytes < 0) {
3856 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003857 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003858 }
3859
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003860 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003861}
3862
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003863/*[clinic input]
3864_ssl.MemoryBIO.write_eof
3865
3866Write an EOF marker to the memory BIO.
3867
3868When all data has been read, the "eof" property will be True.
3869[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003870
3871static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3873/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003874{
3875 self->eof_written = 1;
3876 /* After an EOF is written, a zero return from read() should be a real EOF
3877 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3878 BIO_clear_retry_flags(self->bio);
3879 BIO_set_mem_eof_return(self->bio, 0);
3880
3881 Py_RETURN_NONE;
3882}
3883
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003884static PyGetSetDef memory_bio_getsetlist[] = {
3885 {"pending", (getter) memory_bio_get_pending, NULL,
3886 PySSL_memory_bio_pending_doc},
3887 {"eof", (getter) memory_bio_get_eof, NULL,
3888 PySSL_memory_bio_eof_doc},
3889 {NULL}, /* sentinel */
3890};
3891
3892static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003893 _SSL_MEMORYBIO_READ_METHODDEF
3894 _SSL_MEMORYBIO_WRITE_METHODDEF
3895 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003896 {NULL, NULL} /* sentinel */
3897};
3898
3899static PyTypeObject PySSLMemoryBIO_Type = {
3900 PyVarObject_HEAD_INIT(NULL, 0)
3901 "_ssl.MemoryBIO", /*tp_name*/
3902 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3903 0, /*tp_itemsize*/
3904 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3905 0, /*tp_print*/
3906 0, /*tp_getattr*/
3907 0, /*tp_setattr*/
3908 0, /*tp_reserved*/
3909 0, /*tp_repr*/
3910 0, /*tp_as_number*/
3911 0, /*tp_as_sequence*/
3912 0, /*tp_as_mapping*/
3913 0, /*tp_hash*/
3914 0, /*tp_call*/
3915 0, /*tp_str*/
3916 0, /*tp_getattro*/
3917 0, /*tp_setattro*/
3918 0, /*tp_as_buffer*/
3919 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3920 0, /*tp_doc*/
3921 0, /*tp_traverse*/
3922 0, /*tp_clear*/
3923 0, /*tp_richcompare*/
3924 0, /*tp_weaklistoffset*/
3925 0, /*tp_iter*/
3926 0, /*tp_iternext*/
3927 memory_bio_methods, /*tp_methods*/
3928 0, /*tp_members*/
3929 memory_bio_getsetlist, /*tp_getset*/
3930 0, /*tp_base*/
3931 0, /*tp_dict*/
3932 0, /*tp_descr_get*/
3933 0, /*tp_descr_set*/
3934 0, /*tp_dictoffset*/
3935 0, /*tp_init*/
3936 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003938};
3939
Antoine Pitrou152efa22010-05-16 18:19:27 +00003940
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003941/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003942/*[clinic input]
3943_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003944 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003945 entropy: double
3946 /
3947
3948Mix string into the OpenSSL PRNG state.
3949
3950entropy (a float) is a lower bound on the entropy contained in
3951string. See RFC 1750.
3952[clinic start generated code]*/
3953
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003955_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
3956/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003957{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003958 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003959 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003960
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003961 buf = (const char *)view->buf;
3962 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003963 do {
3964 written = Py_MIN(len, INT_MAX);
3965 RAND_add(buf, (int)written, entropy);
3966 buf += written;
3967 len -= written;
3968 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003969 Py_INCREF(Py_None);
3970 return Py_None;
3971}
3972
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003973static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003974PySSL_RAND(int len, int pseudo)
3975{
3976 int ok;
3977 PyObject *bytes;
3978 unsigned long err;
3979 const char *errstr;
3980 PyObject *v;
3981
Victor Stinner1e81a392013-12-19 16:47:04 +01003982 if (len < 0) {
3983 PyErr_SetString(PyExc_ValueError, "num must be positive");
3984 return NULL;
3985 }
3986
Victor Stinner99c8b162011-05-24 12:05:19 +02003987 bytes = PyBytes_FromStringAndSize(NULL, len);
3988 if (bytes == NULL)
3989 return NULL;
3990 if (pseudo) {
3991 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3992 if (ok == 0 || ok == 1)
3993 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3994 }
3995 else {
3996 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3997 if (ok == 1)
3998 return bytes;
3999 }
4000 Py_DECREF(bytes);
4001
4002 err = ERR_get_error();
4003 errstr = ERR_reason_error_string(err);
4004 v = Py_BuildValue("(ks)", err, errstr);
4005 if (v != NULL) {
4006 PyErr_SetObject(PySSLErrorObject, v);
4007 Py_DECREF(v);
4008 }
4009 return NULL;
4010}
4011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004012/*[clinic input]
4013_ssl.RAND_bytes
4014 n: int
4015 /
4016
4017Generate n cryptographically strong pseudo-random bytes.
4018[clinic start generated code]*/
4019
Victor Stinner99c8b162011-05-24 12:05:19 +02004020static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004021_ssl_RAND_bytes_impl(PyObject *module, int n)
4022/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004023{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004024 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004025}
4026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004027/*[clinic input]
4028_ssl.RAND_pseudo_bytes
4029 n: int
4030 /
4031
4032Generate n pseudo-random bytes.
4033
4034Return a pair (bytes, is_cryptographic). is_cryptographic is True
4035if the bytes generated are cryptographically strong.
4036[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004037
4038static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004039_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4040/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004041{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004042 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004043}
4044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004045/*[clinic input]
4046_ssl.RAND_status
4047
4048Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4049
4050It is necessary to seed the PRNG with RAND_add() on some platforms before
4051using the ssl() function.
4052[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004053
4054static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004055_ssl_RAND_status_impl(PyObject *module)
4056/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004057{
Christian Heimes217cfd12007-12-02 14:31:20 +00004058 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004059}
4060
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004061#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062/*[clinic input]
4063_ssl.RAND_egd
4064 path: object(converter="PyUnicode_FSConverter")
4065 /
4066
4067Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4068
4069Returns number of bytes read. Raises SSLError if connection to EGD
4070fails or if it does not provide enough data to seed PRNG.
4071[clinic start generated code]*/
4072
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004073static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004074_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4075/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004076{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004077 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004078 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004079 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004080 PyErr_SetString(PySSLErrorObject,
4081 "EGD connection failed or EGD did not return "
4082 "enough data to seed the PRNG");
4083 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004084 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004085 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004086}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004087#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004088
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004089
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004090
4091/*[clinic input]
4092_ssl.get_default_verify_paths
4093
4094Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4095
4096The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4097[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004098
4099static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004100_ssl_get_default_verify_paths_impl(PyObject *module)
4101/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004102{
4103 PyObject *ofile_env = NULL;
4104 PyObject *ofile = NULL;
4105 PyObject *odir_env = NULL;
4106 PyObject *odir = NULL;
4107
Benjamin Petersond113c962015-07-18 10:59:13 -07004108#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004109 const char *tmp = (info); \
4110 target = NULL; \
4111 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4112 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4113 target = PyBytes_FromString(tmp); } \
4114 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004115 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004116
Benjamin Petersond113c962015-07-18 10:59:13 -07004117 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4118 CONVERT(X509_get_default_cert_file(), ofile);
4119 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4120 CONVERT(X509_get_default_cert_dir(), odir);
4121#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004122
Christian Heimes200bb1b2013-06-14 15:14:29 +02004123 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004124
4125 error:
4126 Py_XDECREF(ofile_env);
4127 Py_XDECREF(ofile);
4128 Py_XDECREF(odir_env);
4129 Py_XDECREF(odir);
4130 return NULL;
4131}
4132
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004133static PyObject*
4134asn1obj2py(ASN1_OBJECT *obj)
4135{
4136 int nid;
4137 const char *ln, *sn;
4138 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004139 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004140
4141 nid = OBJ_obj2nid(obj);
4142 if (nid == NID_undef) {
4143 PyErr_Format(PyExc_ValueError, "Unknown object");
4144 return NULL;
4145 }
4146 sn = OBJ_nid2sn(nid);
4147 ln = OBJ_nid2ln(nid);
4148 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4149 if (buflen < 0) {
4150 _setSSLError(NULL, 0, __FILE__, __LINE__);
4151 return NULL;
4152 }
4153 if (buflen) {
4154 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4155 } else {
4156 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4157 }
4158}
4159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160/*[clinic input]
4161_ssl.txt2obj
4162 txt: str
4163 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004164
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004165Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4166
4167By default objects are looked up by OID. With name=True short and
4168long name are also matched.
4169[clinic start generated code]*/
4170
4171static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004172_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4173/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004174{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004175 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004176 ASN1_OBJECT *obj;
4177
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004178 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4179 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004180 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004181 return NULL;
4182 }
4183 result = asn1obj2py(obj);
4184 ASN1_OBJECT_free(obj);
4185 return result;
4186}
4187
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004188/*[clinic input]
4189_ssl.nid2obj
4190 nid: int
4191 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004192
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4194[clinic start generated code]*/
4195
4196static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004197_ssl_nid2obj_impl(PyObject *module, int nid)
4198/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004199{
4200 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004201 ASN1_OBJECT *obj;
4202
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004203 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004204 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004205 return NULL;
4206 }
4207 obj = OBJ_nid2obj(nid);
4208 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004209 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004210 return NULL;
4211 }
4212 result = asn1obj2py(obj);
4213 ASN1_OBJECT_free(obj);
4214 return result;
4215}
4216
Christian Heimes46bebee2013-06-09 19:03:31 +02004217#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004218
4219static PyObject*
4220certEncodingType(DWORD encodingType)
4221{
4222 static PyObject *x509_asn = NULL;
4223 static PyObject *pkcs_7_asn = NULL;
4224
4225 if (x509_asn == NULL) {
4226 x509_asn = PyUnicode_InternFromString("x509_asn");
4227 if (x509_asn == NULL)
4228 return NULL;
4229 }
4230 if (pkcs_7_asn == NULL) {
4231 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4232 if (pkcs_7_asn == NULL)
4233 return NULL;
4234 }
4235 switch(encodingType) {
4236 case X509_ASN_ENCODING:
4237 Py_INCREF(x509_asn);
4238 return x509_asn;
4239 case PKCS_7_ASN_ENCODING:
4240 Py_INCREF(pkcs_7_asn);
4241 return pkcs_7_asn;
4242 default:
4243 return PyLong_FromLong(encodingType);
4244 }
4245}
4246
4247static PyObject*
4248parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4249{
4250 CERT_ENHKEY_USAGE *usage;
4251 DWORD size, error, i;
4252 PyObject *retval;
4253
4254 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4255 error = GetLastError();
4256 if (error == CRYPT_E_NOT_FOUND) {
4257 Py_RETURN_TRUE;
4258 }
4259 return PyErr_SetFromWindowsErr(error);
4260 }
4261
4262 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4263 if (usage == NULL) {
4264 return PyErr_NoMemory();
4265 }
4266
4267 /* Now get the actual enhanced usage property */
4268 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4269 PyMem_Free(usage);
4270 error = GetLastError();
4271 if (error == CRYPT_E_NOT_FOUND) {
4272 Py_RETURN_TRUE;
4273 }
4274 return PyErr_SetFromWindowsErr(error);
4275 }
4276 retval = PySet_New(NULL);
4277 if (retval == NULL) {
4278 goto error;
4279 }
4280 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4281 if (usage->rgpszUsageIdentifier[i]) {
4282 PyObject *oid;
4283 int err;
4284 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4285 if (oid == NULL) {
4286 Py_CLEAR(retval);
4287 goto error;
4288 }
4289 err = PySet_Add(retval, oid);
4290 Py_DECREF(oid);
4291 if (err == -1) {
4292 Py_CLEAR(retval);
4293 goto error;
4294 }
4295 }
4296 }
4297 error:
4298 PyMem_Free(usage);
4299 return retval;
4300}
4301
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004302/*[clinic input]
4303_ssl.enum_certificates
4304 store_name: str
4305
4306Retrieve certificates from Windows' cert store.
4307
4308store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4309more cert storages, too. The function returns a list of (bytes,
4310encoding_type, trust) tuples. The encoding_type flag can be interpreted
4311with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4312a set of OIDs or the boolean True.
4313[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004314
Christian Heimes46bebee2013-06-09 19:03:31 +02004315static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004316_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4317/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004318{
Christian Heimes46bebee2013-06-09 19:03:31 +02004319 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004320 PCCERT_CONTEXT pCertCtx = NULL;
4321 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004322 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004323
Christian Heimes44109d72013-11-22 01:51:30 +01004324 result = PyList_New(0);
4325 if (result == NULL) {
4326 return NULL;
4327 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004328 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4329 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4330 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004331 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004332 Py_DECREF(result);
4333 return PyErr_SetFromWindowsErr(GetLastError());
4334 }
4335
Christian Heimes44109d72013-11-22 01:51:30 +01004336 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4337 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4338 pCertCtx->cbCertEncoded);
4339 if (!cert) {
4340 Py_CLEAR(result);
4341 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004342 }
Christian Heimes44109d72013-11-22 01:51:30 +01004343 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4344 Py_CLEAR(result);
4345 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004346 }
Christian Heimes44109d72013-11-22 01:51:30 +01004347 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4348 if (keyusage == Py_True) {
4349 Py_DECREF(keyusage);
4350 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004351 }
Christian Heimes44109d72013-11-22 01:51:30 +01004352 if (keyusage == NULL) {
4353 Py_CLEAR(result);
4354 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004355 }
Christian Heimes44109d72013-11-22 01:51:30 +01004356 if ((tup = PyTuple_New(3)) == NULL) {
4357 Py_CLEAR(result);
4358 break;
4359 }
4360 PyTuple_SET_ITEM(tup, 0, cert);
4361 cert = NULL;
4362 PyTuple_SET_ITEM(tup, 1, enc);
4363 enc = NULL;
4364 PyTuple_SET_ITEM(tup, 2, keyusage);
4365 keyusage = NULL;
4366 if (PyList_Append(result, tup) < 0) {
4367 Py_CLEAR(result);
4368 break;
4369 }
4370 Py_CLEAR(tup);
4371 }
4372 if (pCertCtx) {
4373 /* loop ended with an error, need to clean up context manually */
4374 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004375 }
4376
4377 /* In error cases cert, enc and tup may not be NULL */
4378 Py_XDECREF(cert);
4379 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004380 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004381 Py_XDECREF(tup);
4382
4383 if (!CertCloseStore(hStore, 0)) {
4384 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004385 Py_XDECREF(result);
4386 return PyErr_SetFromWindowsErr(GetLastError());
4387 }
4388 return result;
4389}
4390
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004391/*[clinic input]
4392_ssl.enum_crls
4393 store_name: str
4394
4395Retrieve CRLs from Windows' cert store.
4396
4397store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4398more cert storages, too. The function returns a list of (bytes,
4399encoding_type) tuples. The encoding_type flag can be interpreted with
4400X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4401[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004402
4403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004404_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4405/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004406{
Christian Heimes44109d72013-11-22 01:51:30 +01004407 HCERTSTORE hStore = NULL;
4408 PCCRL_CONTEXT pCrlCtx = NULL;
4409 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4410 PyObject *result = NULL;
4411
Christian Heimes44109d72013-11-22 01:51:30 +01004412 result = PyList_New(0);
4413 if (result == NULL) {
4414 return NULL;
4415 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004416 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4417 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4418 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004419 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004420 Py_DECREF(result);
4421 return PyErr_SetFromWindowsErr(GetLastError());
4422 }
Christian Heimes44109d72013-11-22 01:51:30 +01004423
4424 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4425 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4426 pCrlCtx->cbCrlEncoded);
4427 if (!crl) {
4428 Py_CLEAR(result);
4429 break;
4430 }
4431 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4432 Py_CLEAR(result);
4433 break;
4434 }
4435 if ((tup = PyTuple_New(2)) == NULL) {
4436 Py_CLEAR(result);
4437 break;
4438 }
4439 PyTuple_SET_ITEM(tup, 0, crl);
4440 crl = NULL;
4441 PyTuple_SET_ITEM(tup, 1, enc);
4442 enc = NULL;
4443
4444 if (PyList_Append(result, tup) < 0) {
4445 Py_CLEAR(result);
4446 break;
4447 }
4448 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004449 }
Christian Heimes44109d72013-11-22 01:51:30 +01004450 if (pCrlCtx) {
4451 /* loop ended with an error, need to clean up context manually */
4452 CertFreeCRLContext(pCrlCtx);
4453 }
4454
4455 /* In error cases cert, enc and tup may not be NULL */
4456 Py_XDECREF(crl);
4457 Py_XDECREF(enc);
4458 Py_XDECREF(tup);
4459
4460 if (!CertCloseStore(hStore, 0)) {
4461 /* This error case might shadow another exception.*/
4462 Py_XDECREF(result);
4463 return PyErr_SetFromWindowsErr(GetLastError());
4464 }
4465 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004466}
Christian Heimes44109d72013-11-22 01:51:30 +01004467
4468#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004469
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004470/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004471static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004472 _SSL__TEST_DECODE_CERT_METHODDEF
4473 _SSL_RAND_ADD_METHODDEF
4474 _SSL_RAND_BYTES_METHODDEF
4475 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4476 _SSL_RAND_EGD_METHODDEF
4477 _SSL_RAND_STATUS_METHODDEF
4478 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4479 _SSL_ENUM_CERTIFICATES_METHODDEF
4480 _SSL_ENUM_CRLS_METHODDEF
4481 _SSL_TXT2OBJ_METHODDEF
4482 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004483 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004484};
4485
4486
Christian Heimes598894f2016-09-05 23:19:05 +02004487#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004488
4489/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004490 * of the Python C thread library
4491 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4492 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004493
4494static PyThread_type_lock *_ssl_locks = NULL;
4495
Christian Heimes4d98ca92013-08-19 17:36:29 +02004496#if OPENSSL_VERSION_NUMBER >= 0x10000000
4497/* use new CRYPTO_THREADID API. */
4498static void
4499_ssl_threadid_callback(CRYPTO_THREADID *id)
4500{
4501 CRYPTO_THREADID_set_numeric(id,
4502 (unsigned long)PyThread_get_thread_ident());
4503}
4504#else
4505/* deprecated CRYPTO_set_id_callback() API. */
4506static unsigned long
4507_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004508 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004510#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004511
Bill Janssen6e027db2007-11-15 22:23:56 +00004512static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004513 (int mode, int n, const char *file, int line) {
4514 /* this function is needed to perform locking on shared data
4515 structures. (Note that OpenSSL uses a number of global data
4516 structures that will be implicitly shared whenever multiple
4517 threads use OpenSSL.) Multi-threaded applications will
4518 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004520 locking_function() must be able to handle up to
4521 CRYPTO_num_locks() different mutex locks. It sets the n-th
4522 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004524 file and line are the file number of the function setting the
4525 lock. They can be useful for debugging.
4526 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004528 if ((_ssl_locks == NULL) ||
4529 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4530 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004532 if (mode & CRYPTO_LOCK) {
4533 PyThread_acquire_lock(_ssl_locks[n], 1);
4534 } else {
4535 PyThread_release_lock(_ssl_locks[n]);
4536 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004537}
4538
4539static int _setup_ssl_threads(void) {
4540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004541 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004543 if (_ssl_locks == NULL) {
4544 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004545 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4546 if (_ssl_locks == NULL) {
4547 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004548 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004549 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004550 memset(_ssl_locks, 0,
4551 sizeof(PyThread_type_lock) * _ssl_locks_count);
4552 for (i = 0; i < _ssl_locks_count; i++) {
4553 _ssl_locks[i] = PyThread_allocate_lock();
4554 if (_ssl_locks[i] == NULL) {
4555 unsigned int j;
4556 for (j = 0; j < i; j++) {
4557 PyThread_free_lock(_ssl_locks[j]);
4558 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004559 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004560 return 0;
4561 }
4562 }
4563 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004564#if OPENSSL_VERSION_NUMBER >= 0x10000000
4565 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4566#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004567 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004568#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004569 }
4570 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004571}
4572
Christian Heimes598894f2016-09-05 23:19:05 +02004573#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004575PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004576"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004577for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004578
Martin v. Löwis1a214512008-06-11 05:26:20 +00004579
4580static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004581 PyModuleDef_HEAD_INIT,
4582 "_ssl",
4583 module_doc,
4584 -1,
4585 PySSL_methods,
4586 NULL,
4587 NULL,
4588 NULL,
4589 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004590};
4591
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004592
4593static void
4594parse_openssl_version(unsigned long libver,
4595 unsigned int *major, unsigned int *minor,
4596 unsigned int *fix, unsigned int *patch,
4597 unsigned int *status)
4598{
4599 *status = libver & 0xF;
4600 libver >>= 4;
4601 *patch = libver & 0xFF;
4602 libver >>= 8;
4603 *fix = libver & 0xFF;
4604 libver >>= 8;
4605 *minor = libver & 0xFF;
4606 libver >>= 8;
4607 *major = libver & 0xFF;
4608}
4609
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004610PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004611PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004612{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004613 PyObject *m, *d, *r;
4614 unsigned long libver;
4615 unsigned int major, minor, fix, patch, status;
4616 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004617 struct py_ssl_error_code *errcode;
4618 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619
Antoine Pitrou152efa22010-05-16 18:19:27 +00004620 if (PyType_Ready(&PySSLContext_Type) < 0)
4621 return NULL;
4622 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004623 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004624 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4625 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004627 m = PyModule_Create(&_sslmodule);
4628 if (m == NULL)
4629 return NULL;
4630 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004632 /* Load _socket module and its C API */
4633 socket_api = PySocketModule_ImportModuleAndAPI();
4634 if (!socket_api)
4635 return NULL;
4636 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004638 /* Init OpenSSL */
4639 SSL_load_error_strings();
4640 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004641#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02004642#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004643 /* note that this will start threading if not already started */
4644 if (!_setup_ssl_threads()) {
4645 return NULL;
4646 }
Christian Heimes598894f2016-09-05 23:19:05 +02004647#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4648 /* OpenSSL 1.1.0 builtin thread support is enabled */
4649 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004650#endif
Christian Heimes598894f2016-09-05 23:19:05 +02004651#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004652 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004654 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004655 sslerror_type_slots[0].pfunc = PyExc_OSError;
4656 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004657 if (PySSLErrorObject == NULL)
4658 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004659
Antoine Pitrou41032a62011-10-27 23:56:55 +02004660 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4661 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4662 PySSLErrorObject, NULL);
4663 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4664 "ssl.SSLWantReadError", SSLWantReadError_doc,
4665 PySSLErrorObject, NULL);
4666 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4667 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4668 PySSLErrorObject, NULL);
4669 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4670 "ssl.SSLSyscallError", SSLSyscallError_doc,
4671 PySSLErrorObject, NULL);
4672 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4673 "ssl.SSLEOFError", SSLEOFError_doc,
4674 PySSLErrorObject, NULL);
4675 if (PySSLZeroReturnErrorObject == NULL
4676 || PySSLWantReadErrorObject == NULL
4677 || PySSLWantWriteErrorObject == NULL
4678 || PySSLSyscallErrorObject == NULL
4679 || PySSLEOFErrorObject == NULL)
4680 return NULL;
4681 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4682 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4683 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4684 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4685 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4686 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004687 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004688 if (PyDict_SetItemString(d, "_SSLContext",
4689 (PyObject *)&PySSLContext_Type) != 0)
4690 return NULL;
4691 if (PyDict_SetItemString(d, "_SSLSocket",
4692 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004693 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004694 if (PyDict_SetItemString(d, "MemoryBIO",
4695 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4696 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004697 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4698 PY_SSL_ERROR_ZERO_RETURN);
4699 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4700 PY_SSL_ERROR_WANT_READ);
4701 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4702 PY_SSL_ERROR_WANT_WRITE);
4703 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4704 PY_SSL_ERROR_WANT_X509_LOOKUP);
4705 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4706 PY_SSL_ERROR_SYSCALL);
4707 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4708 PY_SSL_ERROR_SSL);
4709 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4710 PY_SSL_ERROR_WANT_CONNECT);
4711 /* non ssl.h errorcodes */
4712 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4713 PY_SSL_ERROR_EOF);
4714 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4715 PY_SSL_ERROR_INVALID_ERROR_CODE);
4716 /* cert requirements */
4717 PyModule_AddIntConstant(m, "CERT_NONE",
4718 PY_SSL_CERT_NONE);
4719 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4720 PY_SSL_CERT_OPTIONAL);
4721 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4722 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004723 /* CRL verification for verification_flags */
4724 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4725 0);
4726 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4727 X509_V_FLAG_CRL_CHECK);
4728 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4729 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4730 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4731 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004732#ifdef X509_V_FLAG_TRUSTED_FIRST
4733 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4734 X509_V_FLAG_TRUSTED_FIRST);
4735#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004736
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004737 /* Alert Descriptions from ssl.h */
4738 /* note RESERVED constants no longer intended for use have been removed */
4739 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4740
4741#define ADD_AD_CONSTANT(s) \
4742 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4743 SSL_AD_##s)
4744
4745 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4746 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4747 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4748 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4749 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4750 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4751 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4752 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4753 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4754 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4755 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4756 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4757 ADD_AD_CONSTANT(UNKNOWN_CA);
4758 ADD_AD_CONSTANT(ACCESS_DENIED);
4759 ADD_AD_CONSTANT(DECODE_ERROR);
4760 ADD_AD_CONSTANT(DECRYPT_ERROR);
4761 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4762 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4763 ADD_AD_CONSTANT(INTERNAL_ERROR);
4764 ADD_AD_CONSTANT(USER_CANCELLED);
4765 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004766 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004767#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4768 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4769#endif
4770#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4771 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4772#endif
4773#ifdef SSL_AD_UNRECOGNIZED_NAME
4774 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4775#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004776#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4777 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4778#endif
4779#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4780 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4781#endif
4782#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4783 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4784#endif
4785
4786#undef ADD_AD_CONSTANT
4787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004788 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004789#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004790 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4791 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004792#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004793#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004794 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4795 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004796#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004797 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02004798 PY_SSL_VERSION_TLS);
4799 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4800 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004801 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4802 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004803#if HAVE_TLSv1_2
4804 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4805 PY_SSL_VERSION_TLS1_1);
4806 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4807 PY_SSL_VERSION_TLS1_2);
4808#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004809
Antoine Pitroub5218772010-05-21 09:56:06 +00004810 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004811 PyModule_AddIntConstant(m, "OP_ALL",
4812 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004813 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4814 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4815 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004816#if HAVE_TLSv1_2
4817 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4818 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4819#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004820 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4821 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004822 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004823#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004824 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004825#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004826#ifdef SSL_OP_NO_COMPRESSION
4827 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4828 SSL_OP_NO_COMPRESSION);
4829#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004830
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004831#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004832 r = Py_True;
4833#else
4834 r = Py_False;
4835#endif
4836 Py_INCREF(r);
4837 PyModule_AddObject(m, "HAS_SNI", r);
4838
Antoine Pitroud6494802011-07-21 01:11:30 +02004839 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004840 Py_INCREF(r);
4841 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4842
Antoine Pitrou501da612011-12-21 09:27:41 +01004843#ifdef OPENSSL_NO_ECDH
4844 r = Py_False;
4845#else
4846 r = Py_True;
4847#endif
4848 Py_INCREF(r);
4849 PyModule_AddObject(m, "HAS_ECDH", r);
4850
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004851#ifdef OPENSSL_NPN_NEGOTIATED
4852 r = Py_True;
4853#else
4854 r = Py_False;
4855#endif
4856 Py_INCREF(r);
4857 PyModule_AddObject(m, "HAS_NPN", r);
4858
Benjamin Petersoncca27322015-01-23 16:35:37 -05004859#ifdef HAVE_ALPN
4860 r = Py_True;
4861#else
4862 r = Py_False;
4863#endif
4864 Py_INCREF(r);
4865 PyModule_AddObject(m, "HAS_ALPN", r);
4866
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004867 /* Mappings for error codes */
4868 err_codes_to_names = PyDict_New();
4869 err_names_to_codes = PyDict_New();
4870 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4871 return NULL;
4872 errcode = error_codes;
4873 while (errcode->mnemonic != NULL) {
4874 PyObject *mnemo, *key;
4875 mnemo = PyUnicode_FromString(errcode->mnemonic);
4876 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4877 if (mnemo == NULL || key == NULL)
4878 return NULL;
4879 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4880 return NULL;
4881 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4882 return NULL;
4883 Py_DECREF(key);
4884 Py_DECREF(mnemo);
4885 errcode++;
4886 }
4887 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4888 return NULL;
4889 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4890 return NULL;
4891
4892 lib_codes_to_names = PyDict_New();
4893 if (lib_codes_to_names == NULL)
4894 return NULL;
4895 libcode = library_codes;
4896 while (libcode->library != NULL) {
4897 PyObject *mnemo, *key;
4898 key = PyLong_FromLong(libcode->code);
4899 mnemo = PyUnicode_FromString(libcode->library);
4900 if (key == NULL || mnemo == NULL)
4901 return NULL;
4902 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4903 return NULL;
4904 Py_DECREF(key);
4905 Py_DECREF(mnemo);
4906 libcode++;
4907 }
4908 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4909 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004911 /* OpenSSL version */
4912 /* SSLeay() gives us the version of the library linked against,
4913 which could be different from the headers version.
4914 */
4915 libver = SSLeay();
4916 r = PyLong_FromUnsignedLong(libver);
4917 if (r == NULL)
4918 return NULL;
4919 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4920 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004921 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004922 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4923 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4924 return NULL;
4925 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4926 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4927 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004928
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004929 libver = OPENSSL_VERSION_NUMBER;
4930 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4931 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4932 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4933 return NULL;
4934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004935 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004936}