blob: 736fc1d81046cd3d7dff33facbaad92c893ed81f [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
Christian Heimes5fe668c2016-09-12 00:01:11 +0200143#define TLS_client_method SSLv23_client_method
144#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200145
146static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147{
148 return ne->set;
149}
150
151#ifndef OPENSSL_NO_COMP
152static int COMP_get_type(const COMP_METHOD *meth)
153{
154 return meth->type;
155}
Christian Heimes598894f2016-09-05 23:19:05 +0200156#endif
157
158static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
159{
160 return ctx->default_passwd_callback;
161}
162
163static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
164{
165 return ctx->default_passwd_callback_userdata;
166}
167
168static int X509_OBJECT_get_type(X509_OBJECT *x)
169{
170 return x->type;
171}
172
173static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
174{
175 return x->data.x509;
176}
177
178static int BIO_up_ref(BIO *b)
179{
180 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
181 return 1;
182}
183
184static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
185 return store->objs;
186}
187
188static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
189{
190 return store->param;
191}
Christian Heimes99a65702016-09-10 23:44:53 +0200192
193static int
194SSL_SESSION_has_ticket(const SSL_SESSION *s)
195{
196 return (s->tlsext_ticklen > 0) ? 1 : 0;
197}
198
199static unsigned long
200SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
201{
202 return s->tlsext_tick_lifetime_hint;
203}
204
Christian Heimes598894f2016-09-05 23:19:05 +0200205#endif /* OpenSSL < 1.1.0 or LibreSSL */
206
207
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000208enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 /* these mirror ssl.h */
210 PY_SSL_ERROR_NONE,
211 PY_SSL_ERROR_SSL,
212 PY_SSL_ERROR_WANT_READ,
213 PY_SSL_ERROR_WANT_WRITE,
214 PY_SSL_ERROR_WANT_X509_LOOKUP,
215 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
216 PY_SSL_ERROR_ZERO_RETURN,
217 PY_SSL_ERROR_WANT_CONNECT,
218 /* start of non ssl.h errorcodes */
219 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
220 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
221 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000222};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000223
Thomas Woutersed03b412007-08-28 21:37:11 +0000224enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 PY_SSL_CLIENT,
226 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000227};
228
229enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000230 PY_SSL_CERT_NONE,
231 PY_SSL_CERT_OPTIONAL,
232 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000233};
234
235enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200237 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200238 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100239#if HAVE_TLSv1_2
240 PY_SSL_VERSION_TLS1,
241 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200242 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100243#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200244 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200246 PY_SSL_VERSION_TLS_CLIENT=0x10,
247 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100248};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200249
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000250#ifdef WITH_THREAD
251
252/* serves as a flag to see whether we've initialized the SSL thread support. */
253/* 0 means no, greater than 0 means yes */
254
255static unsigned int _ssl_locks_count = 0;
256
257#endif /* def WITH_THREAD */
258
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000259/* SSL socket object */
260
261#define X509_NAME_MAXLEN 256
262
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000263/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
264 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
265 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
266#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000267# define HAVE_SSL_CTX_CLEAR_OPTIONS
268#else
269# undef HAVE_SSL_CTX_CLEAR_OPTIONS
270#endif
271
Antoine Pitroud6494802011-07-21 01:11:30 +0200272/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
273 * older SSL, but let's be safe */
274#define PySSL_CB_MAXLEN 128
275
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100276
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000277typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000278 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000279 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100280#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500281 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100282 int npn_protocols_len;
283#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500284#ifdef HAVE_ALPN
285 unsigned char *alpn_protocols;
286 int alpn_protocols_len;
287#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100288#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200289 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100290#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100291 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000292} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000293
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294typedef struct {
295 PyObject_HEAD
296 PyObject *Socket; /* weakref to socket on which we're layered */
297 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100298 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200300 char shutdown_seen_zero;
301 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200302 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303 PyObject *owner; /* Python level "owner" passed to servername callback */
304 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000305} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200307typedef struct {
308 PyObject_HEAD
309 BIO *bio;
310 int eof_written;
311} PySSLMemoryBIO;
312
Christian Heimes99a65702016-09-10 23:44:53 +0200313typedef struct {
314 PyObject_HEAD
315 SSL_SESSION *session;
316 PySSLContext *ctx;
317} PySSLSession;
318
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319static PyTypeObject PySSLContext_Type;
320static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200321static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200322static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300324/*[clinic input]
325module _ssl
326class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
327class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
328class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200329class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300330[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200331/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300332
333#include "clinic/_ssl.c.h"
334
Victor Stinner14690702015-04-06 22:46:13 +0200335static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000336
Christian Heimes99a65702016-09-10 23:44:53 +0200337
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
339#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200340#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200341#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000343typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 SOCKET_IS_NONBLOCKING,
345 SOCKET_IS_BLOCKING,
346 SOCKET_HAS_TIMED_OUT,
347 SOCKET_HAS_BEEN_CLOSED,
348 SOCKET_TOO_LARGE_FOR_SELECT,
349 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000350} timeout_state;
351
Thomas Woutersed03b412007-08-28 21:37:11 +0000352/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000353#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200354#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000355
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200356/* Get the socket from a PySSLSocket, if it has one */
357#define GET_SOCKET(obj) ((obj)->Socket ? \
358 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359
Victor Stinner14690702015-04-06 22:46:13 +0200360/* If sock is NULL, use a timeout of 0 second */
361#define GET_SOCKET_TIMEOUT(sock) \
362 ((sock != NULL) ? (sock)->sock_timeout : 0)
363
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200364/*
365 * SSL errors.
366 */
367
368PyDoc_STRVAR(SSLError_doc,
369"An error occurred in the SSL implementation.");
370
371PyDoc_STRVAR(SSLZeroReturnError_doc,
372"SSL/TLS session closed cleanly.");
373
374PyDoc_STRVAR(SSLWantReadError_doc,
375"Non-blocking SSL socket needs to read more data\n"
376"before the requested operation can be completed.");
377
378PyDoc_STRVAR(SSLWantWriteError_doc,
379"Non-blocking SSL socket needs to write more data\n"
380"before the requested operation can be completed.");
381
382PyDoc_STRVAR(SSLSyscallError_doc,
383"System error when attempting SSL operation.");
384
385PyDoc_STRVAR(SSLEOFError_doc,
386"SSL/TLS connection terminated abruptly.");
387
388static PyObject *
389SSLError_str(PyOSErrorObject *self)
390{
391 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
392 Py_INCREF(self->strerror);
393 return self->strerror;
394 }
395 else
396 return PyObject_Str(self->args);
397}
398
399static PyType_Slot sslerror_type_slots[] = {
400 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
401 {Py_tp_doc, SSLError_doc},
402 {Py_tp_str, SSLError_str},
403 {0, 0},
404};
405
406static PyType_Spec sslerror_type_spec = {
407 "ssl.SSLError",
408 sizeof(PyOSErrorObject),
409 0,
410 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
411 sslerror_type_slots
412};
413
414static void
415fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
416 int lineno, unsigned long errcode)
417{
418 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
419 PyObject *init_value, *msg, *key;
420 _Py_IDENTIFIER(reason);
421 _Py_IDENTIFIER(library);
422
423 if (errcode != 0) {
424 int lib, reason;
425
426 lib = ERR_GET_LIB(errcode);
427 reason = ERR_GET_REASON(errcode);
428 key = Py_BuildValue("ii", lib, reason);
429 if (key == NULL)
430 goto fail;
431 reason_obj = PyDict_GetItem(err_codes_to_names, key);
432 Py_DECREF(key);
433 if (reason_obj == NULL) {
434 /* XXX if reason < 100, it might reflect a library number (!!) */
435 PyErr_Clear();
436 }
437 key = PyLong_FromLong(lib);
438 if (key == NULL)
439 goto fail;
440 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
441 Py_DECREF(key);
442 if (lib_obj == NULL) {
443 PyErr_Clear();
444 }
445 if (errstr == NULL)
446 errstr = ERR_reason_error_string(errcode);
447 }
448 if (errstr == NULL)
449 errstr = "unknown error";
450
451 if (reason_obj && lib_obj)
452 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
453 lib_obj, reason_obj, errstr, lineno);
454 else if (lib_obj)
455 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
456 lib_obj, errstr, lineno);
457 else
458 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 if (msg == NULL)
460 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100463 if (init_value == NULL)
464 goto fail;
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 err_value = PyObject_CallObject(type, init_value);
467 Py_DECREF(init_value);
468 if (err_value == NULL)
469 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100470
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200471 if (reason_obj == NULL)
472 reason_obj = Py_None;
473 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
474 goto fail;
475 if (lib_obj == NULL)
476 lib_obj = Py_None;
477 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
478 goto fail;
479 PyErr_SetObject(type, err_value);
480fail:
481 Py_XDECREF(err_value);
482}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
484static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200485PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000486{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200487 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200488 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 int err;
490 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200491 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200494 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 if (obj->ssl != NULL) {
497 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 switch (err) {
500 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200501 errstr = "TLS/SSL connection has been closed (EOF)";
502 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 p = PY_SSL_ERROR_ZERO_RETURN;
504 break;
505 case SSL_ERROR_WANT_READ:
506 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200507 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 p = PY_SSL_ERROR_WANT_READ;
509 break;
510 case SSL_ERROR_WANT_WRITE:
511 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200512 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 errstr = "The operation did not complete (write)";
514 break;
515 case SSL_ERROR_WANT_X509_LOOKUP:
516 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000517 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 break;
519 case SSL_ERROR_WANT_CONNECT:
520 p = PY_SSL_ERROR_WANT_CONNECT;
521 errstr = "The operation did not complete (connect)";
522 break;
523 case SSL_ERROR_SYSCALL:
524 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200526 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000528 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200529 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000530 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200531 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000532 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000533 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000534 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000536 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000539 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200540 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000541 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 }
543 } else {
544 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 }
546 break;
547 }
548 case SSL_ERROR_SSL:
549 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 if (e == 0)
552 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000553 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 break;
555 }
556 default:
557 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
558 errstr = "Invalid error code";
559 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200561 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000562 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564}
565
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200567_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 else
572 errcode = 0;
573 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000574 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576}
577
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200578/*
579 * SSL objects
580 */
581
Antoine Pitrou152efa22010-05-16 18:19:27 +0000582static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100583newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000584 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200585 char *server_hostname,
586 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100589 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200590 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000591
Antoine Pitrou152efa22010-05-16 18:19:27 +0000592 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (self == NULL)
594 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 self->peer_cert = NULL;
597 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100599 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200600 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200601 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200602 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700603 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200604 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700605 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
606 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200607 if (hostname == NULL) {
608 Py_DECREF(self);
609 return NULL;
610 }
611 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700612 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200613
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100614 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 /* Make sure the SSL error state is initialized */
617 (void) ERR_get_state();
618 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000621 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200623 SSL_set_app_data(self->ssl, self);
624 if (sock) {
625 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
626 } else {
627 /* BIOs are reference counted and SSL_set_bio borrows our reference.
628 * To prevent a double free in memory_bio_dealloc() we need to take an
629 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200630 BIO_up_ref(inbio->bio);
631 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
633 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200634 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000635#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200636 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000637#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200638 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000639
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100640#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000641 if (server_hostname != NULL)
642 SSL_set_tlsext_host_name(self->ssl, server_hostname);
643#endif
644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 /* If the socket is in non-blocking mode or timeout mode, set the BIO
646 * to non-blocking mode (blocking is the default)
647 */
Victor Stinnere2452312015-03-28 03:00:46 +0100648 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
650 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
651 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 PySSL_BEGIN_ALLOW_THREADS
654 if (socket_type == PY_SSL_CLIENT)
655 SSL_set_connect_state(self->ssl);
656 else
657 SSL_set_accept_state(self->ssl);
658 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000659
Antoine Pitroud6494802011-07-21 01:11:30 +0200660 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 if (sock != NULL) {
662 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
663 if (self->Socket == NULL) {
664 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200665 return NULL;
666 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100667 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000669}
670
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000671/* SSL object methods */
672
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300673/*[clinic input]
674_ssl._SSLSocket.do_handshake
675[clinic start generated code]*/
676
677static PyObject *
678_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
679/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000680{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 int ret;
682 int err;
683 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200684 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200685 _PyTime_t timeout, deadline = 0;
686 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000687
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200688 if (sock) {
689 if (((PyObject*)sock) == Py_None) {
690 _setSSLError("Underlying socket connection gone",
691 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
692 return NULL;
693 }
694 Py_INCREF(sock);
695
696 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100697 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200698 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
699 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000701
Victor Stinner14690702015-04-06 22:46:13 +0200702 timeout = GET_SOCKET_TIMEOUT(sock);
703 has_timeout = (timeout > 0);
704 if (has_timeout)
705 deadline = _PyTime_GetMonotonicClock() + timeout;
706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 /* Actually negotiate SSL connection */
708 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000710 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 ret = SSL_do_handshake(self->ssl);
712 err = SSL_get_error(self->ssl, ret);
713 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200714
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000715 if (PyErr_CheckSignals())
716 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200717
Victor Stinner14690702015-04-06 22:46:13 +0200718 if (has_timeout)
719 timeout = deadline - _PyTime_GetMonotonicClock();
720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200722 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200724 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 } else {
726 sockstate = SOCKET_OPERATION_OK;
727 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000730 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000731 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000732 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
734 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000735 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000736 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
738 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000739 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000740 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
742 break;
743 }
744 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200745 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (ret < 1)
747 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 if (self->peer_cert)
750 X509_free (self->peer_cert);
751 PySSL_BEGIN_ALLOW_THREADS
752 self->peer_cert = SSL_get_peer_certificate(self->ssl);
753 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200754 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755
756 Py_INCREF(Py_None);
757 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000758
759error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200760 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000761 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000762}
763
Thomas Woutersed03b412007-08-28 21:37:11 +0000764static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 char namebuf[X509_NAME_MAXLEN];
768 int buflen;
769 PyObject *name_obj;
770 PyObject *value_obj;
771 PyObject *attr;
772 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
775 if (buflen < 0) {
776 _setSSLError(NULL, 0, __FILE__, __LINE__);
777 goto fail;
778 }
779 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
780 if (name_obj == NULL)
781 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
784 if (buflen < 0) {
785 _setSSLError(NULL, 0, __FILE__, __LINE__);
786 Py_DECREF(name_obj);
787 goto fail;
788 }
789 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000790 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 OPENSSL_free(valuebuf);
792 if (value_obj == NULL) {
793 Py_DECREF(name_obj);
794 goto fail;
795 }
796 attr = PyTuple_New(2);
797 if (attr == NULL) {
798 Py_DECREF(name_obj);
799 Py_DECREF(value_obj);
800 goto fail;
801 }
802 PyTuple_SET_ITEM(attr, 0, name_obj);
803 PyTuple_SET_ITEM(attr, 1, value_obj);
804 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000805
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000808}
809
810static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000812{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
814 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
815 PyObject *rdnt;
816 PyObject *attr = NULL; /* tuple to hold an attribute */
817 int entry_count = X509_NAME_entry_count(xname);
818 X509_NAME_ENTRY *entry;
819 ASN1_OBJECT *name;
820 ASN1_STRING *value;
821 int index_counter;
822 int rdn_level = -1;
823 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 dn = PyList_New(0);
826 if (dn == NULL)
827 return NULL;
828 /* now create another tuple to hold the top-level RDN */
829 rdn = PyList_New(0);
830 if (rdn == NULL)
831 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 for (index_counter = 0;
834 index_counter < entry_count;
835 index_counter++)
836 {
837 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 /* check to see if we've gotten to a new RDN */
840 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200841 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 /* yes, new RDN */
843 /* add old RDN to DN */
844 rdnt = PyList_AsTuple(rdn);
845 Py_DECREF(rdn);
846 if (rdnt == NULL)
847 goto fail0;
848 retcode = PyList_Append(dn, rdnt);
849 Py_DECREF(rdnt);
850 if (retcode < 0)
851 goto fail0;
852 /* create new RDN */
853 rdn = PyList_New(0);
854 if (rdn == NULL)
855 goto fail0;
856 }
857 }
Christian Heimes598894f2016-09-05 23:19:05 +0200858 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 /* now add this attribute to the current RDN */
861 name = X509_NAME_ENTRY_get_object(entry);
862 value = X509_NAME_ENTRY_get_data(entry);
863 attr = _create_tuple_for_attribute(name, value);
864 /*
865 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
866 entry->set,
867 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
868 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
869 */
870 if (attr == NULL)
871 goto fail1;
872 retcode = PyList_Append(rdn, attr);
873 Py_DECREF(attr);
874 if (retcode < 0)
875 goto fail1;
876 }
877 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100878 if (rdn != NULL) {
879 if (PyList_GET_SIZE(rdn) > 0) {
880 rdnt = PyList_AsTuple(rdn);
881 Py_DECREF(rdn);
882 if (rdnt == NULL)
883 goto fail0;
884 retcode = PyList_Append(dn, rdnt);
885 Py_DECREF(rdnt);
886 if (retcode < 0)
887 goto fail0;
888 }
889 else {
890 Py_DECREF(rdn);
891 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* convert list to tuple */
895 rdnt = PyList_AsTuple(dn);
896 Py_DECREF(dn);
897 if (rdnt == NULL)
898 return NULL;
899 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
901 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
904 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 Py_XDECREF(dn);
906 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907}
908
909static PyObject *
910_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 /* this code follows the procedure outlined in
913 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
914 function to extract the STACK_OF(GENERAL_NAME),
915 then iterates through the stack to add the
916 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 int i, j;
919 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200920 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 X509_EXTENSION *ext = NULL;
922 GENERAL_NAMES *names = NULL;
923 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000924 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 BIO *biobuf = NULL;
926 char buf[2048];
927 char *vptr;
928 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 if (certificate == NULL)
932 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* get a memory buffer */
935 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200937 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 while ((i = X509_get_ext_by_NID(
939 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 if (peer_alt_names == Py_None) {
942 peer_alt_names = PyList_New(0);
943 if (peer_alt_names == NULL)
944 goto fail;
945 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 /* now decode the altName */
948 ext = X509_get_ext(certificate, i);
949 if(!(method = X509V3_EXT_get(ext))) {
950 PyErr_SetString
951 (PySSLErrorObject,
952 ERRSTR("No method for internalizing subjectAltName!"));
953 goto fail;
954 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Christian Heimes598894f2016-09-05 23:19:05 +0200956 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (method->it)
958 names = (GENERAL_NAMES*)
959 (ASN1_item_d2i(NULL,
960 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200961 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 ASN1_ITEM_ptr(method->it)));
963 else
964 names = (GENERAL_NAMES*)
965 (method->d2i(NULL,
966 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200967 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200971 int gntype;
972 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200975 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200976 switch (gntype) {
977 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 /* we special-case DirName as a tuple of
979 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 t = PyTuple_New(2);
982 if (t == NULL) {
983 goto fail;
984 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 v = PyUnicode_FromString("DirName");
987 if (v == NULL) {
988 Py_DECREF(t);
989 goto fail;
990 }
991 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000993 v = _create_tuple_for_X509_NAME (name->d.dirn);
994 if (v == NULL) {
995 Py_DECREF(t);
996 goto fail;
997 }
998 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200999 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001000
Christian Heimes824f7f32013-08-17 00:54:47 +02001001 case GEN_EMAIL:
1002 case GEN_DNS:
1003 case GEN_URI:
1004 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1005 correctly, CVE-2013-4238 */
1006 t = PyTuple_New(2);
1007 if (t == NULL)
1008 goto fail;
1009 switch (gntype) {
1010 case GEN_EMAIL:
1011 v = PyUnicode_FromString("email");
1012 as = name->d.rfc822Name;
1013 break;
1014 case GEN_DNS:
1015 v = PyUnicode_FromString("DNS");
1016 as = name->d.dNSName;
1017 break;
1018 case GEN_URI:
1019 v = PyUnicode_FromString("URI");
1020 as = name->d.uniformResourceIdentifier;
1021 break;
1022 }
1023 if (v == NULL) {
1024 Py_DECREF(t);
1025 goto fail;
1026 }
1027 PyTuple_SET_ITEM(t, 0, v);
1028 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1029 ASN1_STRING_length(as));
1030 if (v == NULL) {
1031 Py_DECREF(t);
1032 goto fail;
1033 }
1034 PyTuple_SET_ITEM(t, 1, v);
1035 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036
Christian Heimes1c03abd2016-09-06 23:25:35 +02001037 case GEN_RID:
1038 t = PyTuple_New(2);
1039 if (t == NULL)
1040 goto fail;
1041
1042 v = PyUnicode_FromString("Registered ID");
1043 if (v == NULL) {
1044 Py_DECREF(t);
1045 goto fail;
1046 }
1047 PyTuple_SET_ITEM(t, 0, v);
1048
1049 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1050 if (len < 0) {
1051 Py_DECREF(t);
1052 _setSSLError(NULL, 0, __FILE__, __LINE__);
1053 goto fail;
1054 } else if (len >= (int)sizeof(buf)) {
1055 v = PyUnicode_FromString("<INVALID>");
1056 } else {
1057 v = PyUnicode_FromStringAndSize(buf, len);
1058 }
1059 if (v == NULL) {
1060 Py_DECREF(t);
1061 goto fail;
1062 }
1063 PyTuple_SET_ITEM(t, 1, v);
1064 break;
1065
Christian Heimes824f7f32013-08-17 00:54:47 +02001066 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001068 switch (gntype) {
1069 /* check for new general name type */
1070 case GEN_OTHERNAME:
1071 case GEN_X400:
1072 case GEN_EDIPARTY:
1073 case GEN_IPADD:
1074 case GEN_RID:
1075 break;
1076 default:
1077 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1078 "Unknown general name type %d",
1079 gntype) == -1) {
1080 goto fail;
1081 }
1082 break;
1083 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 (void) BIO_reset(biobuf);
1085 GENERAL_NAME_print(biobuf, name);
1086 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1087 if (len < 0) {
1088 _setSSLError(NULL, 0, __FILE__, __LINE__);
1089 goto fail;
1090 }
1091 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001092 if (vptr == NULL) {
1093 PyErr_Format(PyExc_ValueError,
1094 "Invalid value %.200s",
1095 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001097 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 t = PyTuple_New(2);
1099 if (t == NULL)
1100 goto fail;
1101 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1102 if (v == NULL) {
1103 Py_DECREF(t);
1104 goto fail;
1105 }
1106 PyTuple_SET_ITEM(t, 0, v);
1107 v = PyUnicode_FromStringAndSize((vptr + 1),
1108 (len - (vptr - buf + 1)));
1109 if (v == NULL) {
1110 Py_DECREF(t);
1111 goto fail;
1112 }
1113 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001114 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 if (PyList_Append(peer_alt_names, t) < 0) {
1120 Py_DECREF(t);
1121 goto fail;
1122 }
1123 Py_DECREF(t);
1124 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001125 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 }
1127 BIO_free(biobuf);
1128 if (peer_alt_names != Py_None) {
1129 v = PyList_AsTuple(peer_alt_names);
1130 Py_DECREF(peer_alt_names);
1131 return v;
1132 } else {
1133 return peer_alt_names;
1134 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001135
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
1137 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 if (biobuf != NULL)
1139 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 if (peer_alt_names != Py_None) {
1142 Py_XDECREF(peer_alt_names);
1143 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146}
1147
1148static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001149_get_aia_uri(X509 *certificate, int nid) {
1150 PyObject *lst = NULL, *ostr = NULL;
1151 int i, result;
1152 AUTHORITY_INFO_ACCESS *info;
1153
1154 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001155 if (info == NULL)
1156 return Py_None;
1157 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1158 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001159 return Py_None;
1160 }
1161
1162 if ((lst = PyList_New(0)) == NULL) {
1163 goto fail;
1164 }
1165
1166 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1167 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1168 ASN1_IA5STRING *uri;
1169
1170 if ((OBJ_obj2nid(ad->method) != nid) ||
1171 (ad->location->type != GEN_URI)) {
1172 continue;
1173 }
1174 uri = ad->location->d.uniformResourceIdentifier;
1175 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1176 uri->length);
1177 if (ostr == NULL) {
1178 goto fail;
1179 }
1180 result = PyList_Append(lst, ostr);
1181 Py_DECREF(ostr);
1182 if (result < 0) {
1183 goto fail;
1184 }
1185 }
1186 AUTHORITY_INFO_ACCESS_free(info);
1187
1188 /* convert to tuple or None */
1189 if (PyList_Size(lst) == 0) {
1190 Py_DECREF(lst);
1191 return Py_None;
1192 } else {
1193 PyObject *tup;
1194 tup = PyList_AsTuple(lst);
1195 Py_DECREF(lst);
1196 return tup;
1197 }
1198
1199 fail:
1200 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001201 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001202 return NULL;
1203}
1204
1205static PyObject *
1206_get_crl_dp(X509 *certificate) {
1207 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001208 int i, j;
1209 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210
Christian Heimes598894f2016-09-05 23:19:05 +02001211#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001212 /* Calls x509v3_cache_extensions and sets up crldp */
1213 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001214#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001215 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001216
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001217 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001218 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001219
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001220 lst = PyList_New(0);
1221 if (lst == NULL)
1222 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001223
1224 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1225 DIST_POINT *dp;
1226 STACK_OF(GENERAL_NAME) *gns;
1227
1228 dp = sk_DIST_POINT_value(dps, i);
1229 gns = dp->distpoint->name.fullname;
1230
1231 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1232 GENERAL_NAME *gn;
1233 ASN1_IA5STRING *uri;
1234 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001235 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001236
1237 gn = sk_GENERAL_NAME_value(gns, j);
1238 if (gn->type != GEN_URI) {
1239 continue;
1240 }
1241 uri = gn->d.uniformResourceIdentifier;
1242 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1243 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001244 if (ouri == NULL)
1245 goto done;
1246
1247 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001248 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001249 if (err < 0)
1250 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001251 }
1252 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001253
1254 /* Convert to tuple. */
1255 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1256
1257 done:
1258 Py_XDECREF(lst);
1259#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001260 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001261#endif
1262 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001263}
1264
1265static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001266_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 PyObject *retval = NULL;
1269 BIO *biobuf = NULL;
1270 PyObject *peer;
1271 PyObject *peer_alt_names = NULL;
1272 PyObject *issuer;
1273 PyObject *version;
1274 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001275 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 ASN1_INTEGER *serialNumber;
1277 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001278 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 ASN1_TIME *notBefore, *notAfter;
1280 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 retval = PyDict_New();
1283 if (retval == NULL)
1284 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 peer = _create_tuple_for_X509_NAME(
1287 X509_get_subject_name(certificate));
1288 if (peer == NULL)
1289 goto fail0;
1290 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1291 Py_DECREF(peer);
1292 goto fail0;
1293 }
1294 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001295
Antoine Pitroufb046912010-11-09 20:21:19 +00001296 issuer = _create_tuple_for_X509_NAME(
1297 X509_get_issuer_name(certificate));
1298 if (issuer == NULL)
1299 goto fail0;
1300 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001302 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 Py_DECREF(issuer);
1305
1306 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001307 if (version == NULL)
1308 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001309 if (PyDict_SetItemString(retval, "version", version) < 0) {
1310 Py_DECREF(version);
1311 goto fail0;
1312 }
1313 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* get a memory buffer */
1316 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001317
Antoine Pitroufb046912010-11-09 20:21:19 +00001318 (void) BIO_reset(biobuf);
1319 serialNumber = X509_get_serialNumber(certificate);
1320 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1321 i2a_ASN1_INTEGER(biobuf, serialNumber);
1322 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1323 if (len < 0) {
1324 _setSSLError(NULL, 0, __FILE__, __LINE__);
1325 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001327 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1328 if (sn_obj == NULL)
1329 goto fail1;
1330 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1331 Py_DECREF(sn_obj);
1332 goto fail1;
1333 }
1334 Py_DECREF(sn_obj);
1335
1336 (void) BIO_reset(biobuf);
1337 notBefore = X509_get_notBefore(certificate);
1338 ASN1_TIME_print(biobuf, notBefore);
1339 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1340 if (len < 0) {
1341 _setSSLError(NULL, 0, __FILE__, __LINE__);
1342 goto fail1;
1343 }
1344 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1345 if (pnotBefore == NULL)
1346 goto fail1;
1347 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1348 Py_DECREF(pnotBefore);
1349 goto fail1;
1350 }
1351 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 (void) BIO_reset(biobuf);
1354 notAfter = X509_get_notAfter(certificate);
1355 ASN1_TIME_print(biobuf, notAfter);
1356 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1357 if (len < 0) {
1358 _setSSLError(NULL, 0, __FILE__, __LINE__);
1359 goto fail1;
1360 }
1361 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1362 if (pnotAfter == NULL)
1363 goto fail1;
1364 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1365 Py_DECREF(pnotAfter);
1366 goto fail1;
1367 }
1368 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 peer_alt_names = _get_peer_alt_names(certificate);
1373 if (peer_alt_names == NULL)
1374 goto fail1;
1375 else if (peer_alt_names != Py_None) {
1376 if (PyDict_SetItemString(retval, "subjectAltName",
1377 peer_alt_names) < 0) {
1378 Py_DECREF(peer_alt_names);
1379 goto fail1;
1380 }
1381 Py_DECREF(peer_alt_names);
1382 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001383
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001384 /* Authority Information Access: OCSP URIs */
1385 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1386 if (obj == NULL) {
1387 goto fail1;
1388 } else if (obj != Py_None) {
1389 result = PyDict_SetItemString(retval, "OCSP", obj);
1390 Py_DECREF(obj);
1391 if (result < 0) {
1392 goto fail1;
1393 }
1394 }
1395
1396 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1397 if (obj == NULL) {
1398 goto fail1;
1399 } else if (obj != Py_None) {
1400 result = PyDict_SetItemString(retval, "caIssuers", obj);
1401 Py_DECREF(obj);
1402 if (result < 0) {
1403 goto fail1;
1404 }
1405 }
1406
1407 /* CDP (CRL distribution points) */
1408 obj = _get_crl_dp(certificate);
1409 if (obj == NULL) {
1410 goto fail1;
1411 } else if (obj != Py_None) {
1412 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1413 Py_DECREF(obj);
1414 if (result < 0) {
1415 goto fail1;
1416 }
1417 }
1418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 BIO_free(biobuf);
1420 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001421
1422 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (biobuf != NULL)
1424 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001425 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 Py_XDECREF(retval);
1427 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001428}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001429
Christian Heimes9a5395a2013-06-17 15:44:12 +02001430static PyObject *
1431_certificate_to_der(X509 *certificate)
1432{
1433 unsigned char *bytes_buf = NULL;
1434 int len;
1435 PyObject *retval;
1436
1437 bytes_buf = NULL;
1438 len = i2d_X509(certificate, &bytes_buf);
1439 if (len < 0) {
1440 _setSSLError(NULL, 0, __FILE__, __LINE__);
1441 return NULL;
1442 }
1443 /* this is actually an immutable bytes sequence */
1444 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1445 OPENSSL_free(bytes_buf);
1446 return retval;
1447}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001449/*[clinic input]
1450_ssl._test_decode_cert
1451 path: object(converter="PyUnicode_FSConverter")
1452 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001454[clinic start generated code]*/
1455
1456static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001457_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1458/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001459{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 X509 *x=NULL;
1462 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1465 PyErr_SetString(PySSLErrorObject,
1466 "Can't malloc memory to read file");
1467 goto fail0;
1468 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001470 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 PyErr_SetString(PySSLErrorObject,
1472 "Can't open file");
1473 goto fail0;
1474 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1477 if (x == NULL) {
1478 PyErr_SetString(PySSLErrorObject,
1479 "Error decoding PEM-encoded file");
1480 goto fail0;
1481 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482
Antoine Pitroufb046912010-11-09 20:21:19 +00001483 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001484 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485
1486 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001487 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 if (cert != NULL) BIO_free(cert);
1489 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490}
1491
1492
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001493/*[clinic input]
1494_ssl._SSLSocket.peer_certificate
1495 der as binary_mode: bool = False
1496 /
1497
1498Returns the certificate for the peer.
1499
1500If no certificate was provided, returns None. If a certificate was
1501provided, but not validated, returns an empty dictionary. Otherwise
1502returns a dict containing information about the peer certificate.
1503
1504If the optional argument is True, returns a DER-encoded copy of the
1505peer certificate, or None if no certificate was provided. This will
1506return the certificate even if it wasn't validated.
1507[clinic start generated code]*/
1508
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001510_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1511/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514
Antoine Pitrou20b85552013-09-29 19:50:53 +02001515 if (!self->handshake_done) {
1516 PyErr_SetString(PyExc_ValueError,
1517 "handshake not done yet");
1518 return NULL;
1519 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 if (!self->peer_cert)
1521 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522
Antoine Pitrou721738f2012-08-15 23:20:39 +02001523 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001525 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001527 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if ((verification & SSL_VERIFY_PEER) == 0)
1529 return PyDict_New();
1530 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001531 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533}
1534
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001535static PyObject *
1536cipher_to_tuple(const SSL_CIPHER *cipher)
1537{
1538 const char *cipher_name, *cipher_protocol;
1539 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 if (retval == NULL)
1541 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001543 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001545 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PyTuple_SET_ITEM(retval, 0, Py_None);
1547 } else {
1548 v = PyUnicode_FromString(cipher_name);
1549 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001550 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 PyTuple_SET_ITEM(retval, 0, v);
1552 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001553
1554 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001556 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 PyTuple_SET_ITEM(retval, 1, Py_None);
1558 } else {
1559 v = PyUnicode_FromString(cipher_protocol);
1560 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001561 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 PyTuple_SET_ITEM(retval, 1, v);
1563 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001564
1565 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001567 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001571
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001572 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 Py_DECREF(retval);
1574 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575}
1576
Christian Heimes25bfcd52016-09-06 00:04:45 +02001577#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1578static PyObject *
1579cipher_to_dict(const SSL_CIPHER *cipher)
1580{
1581 const char *cipher_name, *cipher_protocol;
1582
1583 unsigned long cipher_id;
1584 int alg_bits, strength_bits, len;
1585 char buf[512] = {0};
1586#if OPENSSL_VERSION_1_1
1587 int aead, nid;
1588 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1589#endif
1590 PyObject *retval;
1591
1592 retval = PyDict_New();
1593 if (retval == NULL) {
1594 goto error;
1595 }
1596
1597 /* can be NULL */
1598 cipher_name = SSL_CIPHER_get_name(cipher);
1599 cipher_protocol = SSL_CIPHER_get_version(cipher);
1600 cipher_id = SSL_CIPHER_get_id(cipher);
1601 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1602 len = strlen(buf);
1603 if (len > 1 && buf[len-1] == '\n')
1604 buf[len-1] = '\0';
1605 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1606
1607#if OPENSSL_VERSION_1_1
1608 aead = SSL_CIPHER_is_aead(cipher);
1609 nid = SSL_CIPHER_get_cipher_nid(cipher);
1610 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1611 nid = SSL_CIPHER_get_digest_nid(cipher);
1612 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1613 nid = SSL_CIPHER_get_kx_nid(cipher);
1614 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1615 nid = SSL_CIPHER_get_auth_nid(cipher);
1616 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1617#endif
1618
1619 retval = Py_BuildValue(
1620 "{sksssssssisi"
1621#if OPENSSL_VERSION_1_1
1622 "sOssssssss"
1623#endif
1624 "}",
1625 "id", cipher_id,
1626 "name", cipher_name,
1627 "protocol", cipher_protocol,
1628 "description", buf,
1629 "strength_bits", strength_bits,
1630 "alg_bits", alg_bits
1631#if OPENSSL_VERSION_1_1
1632 ,"aead", aead ? Py_True : Py_False,
1633 "symmetric", skcipher,
1634 "digest", digest,
1635 "kea", kx,
1636 "auth", auth
1637#endif
1638 );
1639 return retval;
1640
1641 error:
1642 Py_XDECREF(retval);
1643 return NULL;
1644}
1645#endif
1646
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001647/*[clinic input]
1648_ssl._SSLSocket.shared_ciphers
1649[clinic start generated code]*/
1650
1651static PyObject *
1652_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1653/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001654{
1655 STACK_OF(SSL_CIPHER) *ciphers;
1656 int i;
1657 PyObject *res;
1658
Christian Heimes598894f2016-09-05 23:19:05 +02001659 ciphers = SSL_get_ciphers(self->ssl);
1660 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001661 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001662 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1663 if (!res)
1664 return NULL;
1665 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1666 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1667 if (!tup) {
1668 Py_DECREF(res);
1669 return NULL;
1670 }
1671 PyList_SET_ITEM(res, i, tup);
1672 }
1673 return res;
1674}
1675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001676/*[clinic input]
1677_ssl._SSLSocket.cipher
1678[clinic start generated code]*/
1679
1680static PyObject *
1681_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1682/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001683{
1684 const SSL_CIPHER *current;
1685
1686 if (self->ssl == NULL)
1687 Py_RETURN_NONE;
1688 current = SSL_get_current_cipher(self->ssl);
1689 if (current == NULL)
1690 Py_RETURN_NONE;
1691 return cipher_to_tuple(current);
1692}
1693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001694/*[clinic input]
1695_ssl._SSLSocket.version
1696[clinic start generated code]*/
1697
1698static PyObject *
1699_ssl__SSLSocket_version_impl(PySSLSocket *self)
1700/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001701{
1702 const char *version;
1703
1704 if (self->ssl == NULL)
1705 Py_RETURN_NONE;
1706 version = SSL_get_version(self->ssl);
1707 if (!strcmp(version, "unknown"))
1708 Py_RETURN_NONE;
1709 return PyUnicode_FromString(version);
1710}
1711
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001712#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001713/*[clinic input]
1714_ssl._SSLSocket.selected_npn_protocol
1715[clinic start generated code]*/
1716
1717static PyObject *
1718_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1719/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1720{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001721 const unsigned char *out;
1722 unsigned int outlen;
1723
Victor Stinner4569cd52013-06-23 14:58:43 +02001724 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001725 &out, &outlen);
1726
1727 if (out == NULL)
1728 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001729 return PyUnicode_FromStringAndSize((char *)out, outlen);
1730}
1731#endif
1732
1733#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734/*[clinic input]
1735_ssl._SSLSocket.selected_alpn_protocol
1736[clinic start generated code]*/
1737
1738static PyObject *
1739_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1740/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1741{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001742 const unsigned char *out;
1743 unsigned int outlen;
1744
1745 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1746
1747 if (out == NULL)
1748 Py_RETURN_NONE;
1749 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001750}
1751#endif
1752
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001753/*[clinic input]
1754_ssl._SSLSocket.compression
1755[clinic start generated code]*/
1756
1757static PyObject *
1758_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1759/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1760{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001761#ifdef OPENSSL_NO_COMP
1762 Py_RETURN_NONE;
1763#else
1764 const COMP_METHOD *comp_method;
1765 const char *short_name;
1766
1767 if (self->ssl == NULL)
1768 Py_RETURN_NONE;
1769 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001770 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001771 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001772 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001773 if (short_name == NULL)
1774 Py_RETURN_NONE;
1775 return PyUnicode_DecodeFSDefault(short_name);
1776#endif
1777}
1778
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001779static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1780 Py_INCREF(self->ctx);
1781 return self->ctx;
1782}
1783
1784static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1785 void *closure) {
1786
1787 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001788#if !HAVE_SNI
1789 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1790 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001791 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001792#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001793 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001794 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001795 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001796#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001797 } else {
1798 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1799 return -1;
1800 }
1801
1802 return 0;
1803}
1804
1805PyDoc_STRVAR(PySSL_set_context_doc,
1806"_setter_context(ctx)\n\
1807\
1808This changes the context associated with the SSLSocket. This is typically\n\
1809used from within a callback function set by the set_servername_callback\n\
1810on the SSLContext to change the certificate information associated with the\n\
1811SSLSocket before the cryptographic exchange handshake messages\n");
1812
1813
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001814static PyObject *
1815PySSL_get_server_side(PySSLSocket *self, void *c)
1816{
1817 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1818}
1819
1820PyDoc_STRVAR(PySSL_get_server_side_doc,
1821"Whether this is a server-side socket.");
1822
1823static PyObject *
1824PySSL_get_server_hostname(PySSLSocket *self, void *c)
1825{
1826 if (self->server_hostname == NULL)
1827 Py_RETURN_NONE;
1828 Py_INCREF(self->server_hostname);
1829 return self->server_hostname;
1830}
1831
1832PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1833"The currently set server hostname (for SNI).");
1834
1835static PyObject *
1836PySSL_get_owner(PySSLSocket *self, void *c)
1837{
1838 PyObject *owner;
1839
1840 if (self->owner == NULL)
1841 Py_RETURN_NONE;
1842
1843 owner = PyWeakref_GetObject(self->owner);
1844 Py_INCREF(owner);
1845 return owner;
1846}
1847
1848static int
1849PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1850{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001851 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001852 if (self->owner == NULL)
1853 return -1;
1854 return 0;
1855}
1856
1857PyDoc_STRVAR(PySSL_get_owner_doc,
1858"The Python-level owner of this object.\
1859Passed as \"self\" in servername callback.");
1860
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001861
Antoine Pitrou152efa22010-05-16 18:19:27 +00001862static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001863{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 if (self->peer_cert) /* Possible not to have one? */
1865 X509_free (self->peer_cert);
1866 if (self->ssl)
1867 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001869 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001870 Py_XDECREF(self->server_hostname);
1871 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001873}
1874
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001875/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001876 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001877 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001878 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001879
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001880static int
Victor Stinner14690702015-04-06 22:46:13 +02001881PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001882{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001883 int rc;
1884#ifdef HAVE_POLL
1885 struct pollfd pollfd;
1886 _PyTime_t ms;
1887#else
1888 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 fd_set fds;
1890 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001891#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001894 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001896 else if (timeout < 0) {
1897 if (s->sock_timeout > 0)
1898 return SOCKET_HAS_TIMED_OUT;
1899 else
1900 return SOCKET_IS_BLOCKING;
1901 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001904 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 /* Prefer poll, if available, since you can poll() any fd
1908 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001909#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001910 pollfd.fd = s->sock_fd;
1911 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001912
Victor Stinner14690702015-04-06 22:46:13 +02001913 /* timeout is in seconds, poll() uses milliseconds */
1914 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001915 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001916
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001917 PySSL_BEGIN_ALLOW_THREADS
1918 rc = poll(&pollfd, 1, (int)ms);
1919 PySSL_END_ALLOW_THREADS
1920#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001922 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001924
Victor Stinner14690702015-04-06 22:46:13 +02001925 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 FD_ZERO(&fds);
1928 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001929
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001930 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001932 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001934 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001936 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001937 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001938#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1941 (when we are able to write or when there's something to read) */
1942 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001943}
1944
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001945/*[clinic input]
1946_ssl._SSLSocket.write
1947 b: Py_buffer
1948 /
1949
1950Writes the bytes-like object b into the SSL object.
1951
1952Returns the number of bytes written.
1953[clinic start generated code]*/
1954
1955static PyObject *
1956_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1957/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001958{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 int len;
1960 int sockstate;
1961 int err;
1962 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001963 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001964 _PyTime_t timeout, deadline = 0;
1965 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001966
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001967 if (sock != NULL) {
1968 if (((PyObject*)sock) == Py_None) {
1969 _setSSLError("Underlying socket connection gone",
1970 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1971 return NULL;
1972 }
1973 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 }
1975
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001976 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001977 PyErr_Format(PyExc_OverflowError,
1978 "string longer than %d bytes", INT_MAX);
1979 goto error;
1980 }
1981
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001982 if (sock != NULL) {
1983 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001984 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001985 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1986 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1987 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988
Victor Stinner14690702015-04-06 22:46:13 +02001989 timeout = GET_SOCKET_TIMEOUT(sock);
1990 has_timeout = (timeout > 0);
1991 if (has_timeout)
1992 deadline = _PyTime_GetMonotonicClock() + timeout;
1993
1994 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001996 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001997 "The write operation timed out");
1998 goto error;
1999 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2000 PyErr_SetString(PySSLErrorObject,
2001 "Underlying socket has been closed.");
2002 goto error;
2003 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2004 PyErr_SetString(PySSLErrorObject,
2005 "Underlying socket too large for select().");
2006 goto error;
2007 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002009 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002011 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 err = SSL_get_error(self->ssl, len);
2013 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002014
2015 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002017
Victor Stinner14690702015-04-06 22:46:13 +02002018 if (has_timeout)
2019 timeout = deadline - _PyTime_GetMonotonicClock();
2020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002022 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002023 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002024 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002025 } else {
2026 sockstate = SOCKET_OPERATION_OK;
2027 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002030 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002031 "The write operation timed out");
2032 goto error;
2033 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2034 PyErr_SetString(PySSLErrorObject,
2035 "Underlying socket has been closed.");
2036 goto error;
2037 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2038 break;
2039 }
2040 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002041
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002042 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002043 if (len > 0)
2044 return PyLong_FromLong(len);
2045 else
2046 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002047
2048error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002049 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002051}
2052
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002053/*[clinic input]
2054_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002055
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002056Returns the number of already decrypted bytes available for read, pending on the connection.
2057[clinic start generated code]*/
2058
2059static PyObject *
2060_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2061/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002062{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002063 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002065 PySSL_BEGIN_ALLOW_THREADS
2066 count = SSL_pending(self->ssl);
2067 PySSL_END_ALLOW_THREADS
2068 if (count < 0)
2069 return PySSL_SetError(self, count, __FILE__, __LINE__);
2070 else
2071 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002072}
2073
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002074/*[clinic input]
2075_ssl._SSLSocket.read
2076 size as len: int
2077 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002078 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002079 ]
2080 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002081
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002082Read up to size bytes from the SSL socket.
2083[clinic start generated code]*/
2084
2085static PyObject *
2086_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2087 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002088/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002089{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002090 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002092 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 int sockstate;
2094 int err;
2095 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002096 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002097 _PyTime_t timeout, deadline = 0;
2098 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002099
Martin Panter5503d472016-03-27 05:35:19 +00002100 if (!group_right_1 && len < 0) {
2101 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2102 return NULL;
2103 }
2104
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002105 if (sock != NULL) {
2106 if (((PyObject*)sock) == Py_None) {
2107 _setSSLError("Underlying socket connection gone",
2108 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2109 return NULL;
2110 }
2111 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002112 }
2113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002114 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002115 dest = PyBytes_FromStringAndSize(NULL, len);
2116 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002117 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002118 if (len == 0) {
2119 Py_XDECREF(sock);
2120 return dest;
2121 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002122 mem = PyBytes_AS_STRING(dest);
2123 }
2124 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002125 mem = buffer->buf;
2126 if (len <= 0 || len > buffer->len) {
2127 len = (int) buffer->len;
2128 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002129 PyErr_SetString(PyExc_OverflowError,
2130 "maximum length can't fit in a C 'int'");
2131 goto error;
2132 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002133 if (len == 0) {
2134 count = 0;
2135 goto done;
2136 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002137 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 }
2139
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002140 if (sock != NULL) {
2141 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002142 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002143 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2144 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2145 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146
Victor Stinner14690702015-04-06 22:46:13 +02002147 timeout = GET_SOCKET_TIMEOUT(sock);
2148 has_timeout = (timeout > 0);
2149 if (has_timeout)
2150 deadline = _PyTime_GetMonotonicClock() + timeout;
2151
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002152 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 PySSL_BEGIN_ALLOW_THREADS
2154 count = SSL_read(self->ssl, mem, len);
2155 err = SSL_get_error(self->ssl, count);
2156 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 if (PyErr_CheckSignals())
2159 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002160
Victor Stinner14690702015-04-06 22:46:13 +02002161 if (has_timeout)
2162 timeout = deadline - _PyTime_GetMonotonicClock();
2163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002165 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002167 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002168 } else if (err == SSL_ERROR_ZERO_RETURN &&
2169 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 {
2171 count = 0;
2172 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002173 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002174 else
2175 sockstate = SOCKET_OPERATION_OK;
2176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002178 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 "The read operation timed out");
2180 goto error;
2181 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2182 break;
2183 }
2184 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 if (count <= 0) {
2187 PySSL_SetError(self, count, __FILE__, __LINE__);
2188 goto error;
2189 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002190
2191done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002192 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002193 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002194 _PyBytes_Resize(&dest, count);
2195 return dest;
2196 }
2197 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 return PyLong_FromLong(count);
2199 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002200
2201error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002202 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002203 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002204 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002206}
2207
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002208/*[clinic input]
2209_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002210
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002211Does the SSL shutdown handshake with the remote end.
2212
2213Returns the underlying socket object.
2214[clinic start generated code]*/
2215
2216static PyObject *
2217_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2218/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002219{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 int err, ssl_err, sockstate, nonblocking;
2221 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002223 _PyTime_t timeout, deadline = 0;
2224 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002225
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002226 if (sock != NULL) {
2227 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002228 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002229 _setSSLError("Underlying socket connection gone",
2230 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2231 return NULL;
2232 }
2233 Py_INCREF(sock);
2234
2235 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002236 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002237 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2238 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240
Victor Stinner14690702015-04-06 22:46:13 +02002241 timeout = GET_SOCKET_TIMEOUT(sock);
2242 has_timeout = (timeout > 0);
2243 if (has_timeout)
2244 deadline = _PyTime_GetMonotonicClock() + timeout;
2245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 while (1) {
2247 PySSL_BEGIN_ALLOW_THREADS
2248 /* Disable read-ahead so that unwrap can work correctly.
2249 * Otherwise OpenSSL might read in too much data,
2250 * eating clear text data that happens to be
2251 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002252 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 * function is used and the shutdown_seen_zero != 0
2254 * condition is met.
2255 */
2256 if (self->shutdown_seen_zero)
2257 SSL_set_read_ahead(self->ssl, 0);
2258 err = SSL_shutdown(self->ssl);
2259 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2262 if (err > 0)
2263 break;
2264 if (err == 0) {
2265 /* Don't loop endlessly; instead preserve legacy
2266 behaviour of trying SSL_shutdown() only twice.
2267 This looks necessary for OpenSSL < 0.9.8m */
2268 if (++zeros > 1)
2269 break;
2270 /* Shutdown was sent, now try receiving */
2271 self->shutdown_seen_zero = 1;
2272 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002273 }
2274
Victor Stinner14690702015-04-06 22:46:13 +02002275 if (has_timeout)
2276 timeout = deadline - _PyTime_GetMonotonicClock();
2277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 /* Possibly retry shutdown until timeout or failure */
2279 ssl_err = SSL_get_error(self->ssl, err);
2280 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002281 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002283 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 else
2285 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2288 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002289 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 "The read operation timed out");
2291 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002292 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002294 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 }
2296 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2297 PyErr_SetString(PySSLErrorObject,
2298 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002299 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 }
2301 else if (sockstate != SOCKET_OPERATION_OK)
2302 /* Retain the SSL error code */
2303 break;
2304 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002305
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002306 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002310 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002311 /* It's already INCREF'ed */
2312 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002313 else
2314 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002315
2316error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002317 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002318 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002319}
2320
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002321/*[clinic input]
2322_ssl._SSLSocket.tls_unique_cb
2323
2324Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2325
2326If the TLS handshake is not yet complete, None is returned.
2327[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002328
Antoine Pitroud6494802011-07-21 01:11:30 +02002329static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002330_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2331/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002332{
2333 PyObject *retval = NULL;
2334 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002335 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002336
2337 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2338 /* if session is resumed XOR we are the client */
2339 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2340 }
2341 else {
2342 /* if a new session XOR we are the server */
2343 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2344 }
2345
2346 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002347 if (len == 0)
2348 Py_RETURN_NONE;
2349
2350 retval = PyBytes_FromStringAndSize(buf, len);
2351
2352 return retval;
2353}
2354
Christian Heimes99a65702016-09-10 23:44:53 +02002355#ifdef OPENSSL_VERSION_1_1
2356
2357static SSL_SESSION*
2358_ssl_session_dup(SSL_SESSION *session) {
2359 SSL_SESSION *newsession = NULL;
2360 int slen;
2361 unsigned char *senc = NULL, *p;
2362 const unsigned char *const_p;
2363
2364 if (session == NULL) {
2365 PyErr_SetString(PyExc_ValueError, "Invalid session");
2366 goto error;
2367 }
2368
2369 /* get length */
2370 slen = i2d_SSL_SESSION(session, NULL);
2371 if (slen == 0 || slen > 0xFF00) {
2372 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2373 goto error;
2374 }
2375 if ((senc = PyMem_Malloc(slen)) == NULL) {
2376 PyErr_NoMemory();
2377 goto error;
2378 }
2379 p = senc;
2380 if (!i2d_SSL_SESSION(session, &p)) {
2381 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2382 goto error;
2383 }
2384 const_p = senc;
2385 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2386 if (session == NULL) {
2387 goto error;
2388 }
2389 PyMem_Free(senc);
2390 return newsession;
2391 error:
2392 if (senc != NULL) {
2393 PyMem_Free(senc);
2394 }
2395 return NULL;
2396}
2397#endif
2398
2399static PyObject *
2400PySSL_get_session(PySSLSocket *self, void *closure) {
2401 /* get_session can return sessions from a server-side connection,
2402 * it does not check for handshake done or client socket. */
2403 PySSLSession *pysess;
2404 SSL_SESSION *session;
2405
2406#ifdef OPENSSL_VERSION_1_1
2407 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2408 * https://github.com/openssl/openssl/issues/1550 */
2409 session = SSL_get0_session(self->ssl); /* borrowed reference */
2410 if (session == NULL) {
2411 Py_RETURN_NONE;
2412 }
2413 if ((session = _ssl_session_dup(session)) == NULL) {
2414 return NULL;
2415 }
2416#else
2417 session = SSL_get1_session(self->ssl);
2418 if (session == NULL) {
2419 Py_RETURN_NONE;
2420 }
2421#endif
2422
2423 pysess = PyObject_New(PySSLSession, &PySSLSession_Type);
2424 if (pysess == NULL) {
2425 SSL_SESSION_free(session);
2426 return NULL;
2427 }
2428
2429 assert(self->ctx);
2430 pysess->ctx = self->ctx;
2431 Py_INCREF(pysess->ctx);
2432 pysess->session = session;
2433 return (PyObject *)pysess;
2434}
2435
2436static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2437 void *closure)
2438 {
2439 PySSLSession *pysess;
2440#ifdef OPENSSL_VERSION_1_1
2441 SSL_SESSION *session;
2442#endif
2443 int result;
2444
2445 if (!PySSLSession_Check(value)) {
2446 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2447 return -1;
2448 }
2449 pysess = (PySSLSession *)value;
2450
2451 if (self->ctx->ctx != pysess->ctx->ctx) {
2452 PyErr_SetString(PyExc_ValueError,
2453 "Session refers to a different SSLContext.");
2454 return -1;
2455 }
2456 if (self->socket_type != PY_SSL_CLIENT) {
2457 PyErr_SetString(PyExc_ValueError,
2458 "Cannot set session for server-side SSLSocket.");
2459 return -1;
2460 }
2461 if (self->handshake_done) {
2462 PyErr_SetString(PyExc_ValueError,
2463 "Cannot set session after handshake.");
2464 return -1;
2465 }
2466#ifdef OPENSSL_VERSION_1_1
2467 /* duplicate session */
2468 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2469 return -1;
2470 }
2471 result = SSL_set_session(self->ssl, session);
2472 /* free duplicate, SSL_set_session() bumps ref count */
2473 SSL_SESSION_free(session);
2474#else
2475 result = SSL_set_session(self->ssl, pysess->session);
2476#endif
2477 if (result == 0) {
2478 _setSSLError(NULL, 0, __FILE__, __LINE__);
2479 return -1;
2480 }
2481 return 0;
2482}
2483
2484PyDoc_STRVAR(PySSL_set_session_doc,
2485"_setter_session(session)\n\
2486\
2487Get / set SSLSession.");
2488
2489static PyObject *
2490PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2491 if (SSL_session_reused(self->ssl)) {
2492 Py_RETURN_TRUE;
2493 } else {
2494 Py_RETURN_FALSE;
2495 }
2496}
2497
2498PyDoc_STRVAR(PySSL_get_session_reused_doc,
2499"Was the client session reused during handshake?");
2500
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002501static PyGetSetDef ssl_getsetlist[] = {
2502 {"context", (getter) PySSL_get_context,
2503 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002504 {"server_side", (getter) PySSL_get_server_side, NULL,
2505 PySSL_get_server_side_doc},
2506 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2507 PySSL_get_server_hostname_doc},
2508 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2509 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002510 {"session", (getter) PySSL_get_session,
2511 (setter) PySSL_set_session, PySSL_set_session_doc},
2512 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2513 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002514 {NULL}, /* sentinel */
2515};
2516
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002517static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002518 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2519 _SSL__SSLSOCKET_WRITE_METHODDEF
2520 _SSL__SSLSOCKET_READ_METHODDEF
2521 _SSL__SSLSOCKET_PENDING_METHODDEF
2522 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2523 _SSL__SSLSOCKET_CIPHER_METHODDEF
2524 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2525 _SSL__SSLSOCKET_VERSION_METHODDEF
2526 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2527 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2528 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2529 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2530 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002532};
2533
Antoine Pitrou152efa22010-05-16 18:19:27 +00002534static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002536 "_ssl._SSLSocket", /*tp_name*/
2537 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002538 0, /*tp_itemsize*/
2539 /* methods */
2540 (destructor)PySSL_dealloc, /*tp_dealloc*/
2541 0, /*tp_print*/
2542 0, /*tp_getattr*/
2543 0, /*tp_setattr*/
2544 0, /*tp_reserved*/
2545 0, /*tp_repr*/
2546 0, /*tp_as_number*/
2547 0, /*tp_as_sequence*/
2548 0, /*tp_as_mapping*/
2549 0, /*tp_hash*/
2550 0, /*tp_call*/
2551 0, /*tp_str*/
2552 0, /*tp_getattro*/
2553 0, /*tp_setattro*/
2554 0, /*tp_as_buffer*/
2555 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2556 0, /*tp_doc*/
2557 0, /*tp_traverse*/
2558 0, /*tp_clear*/
2559 0, /*tp_richcompare*/
2560 0, /*tp_weaklistoffset*/
2561 0, /*tp_iter*/
2562 0, /*tp_iternext*/
2563 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002564 0, /*tp_members*/
2565 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002566};
2567
Antoine Pitrou152efa22010-05-16 18:19:27 +00002568
2569/*
2570 * _SSLContext objects
2571 */
2572
Christian Heimes5fe668c2016-09-12 00:01:11 +02002573static int
2574_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2575{
2576 int mode;
2577 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2578
2579 switch(n) {
2580 case PY_SSL_CERT_NONE:
2581 mode = SSL_VERIFY_NONE;
2582 break;
2583 case PY_SSL_CERT_OPTIONAL:
2584 mode = SSL_VERIFY_PEER;
2585 break;
2586 case PY_SSL_CERT_REQUIRED:
2587 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2588 break;
2589 default:
2590 PyErr_SetString(PyExc_ValueError,
2591 "invalid value for verify_mode");
2592 return -1;
2593 }
2594 /* keep current verify cb */
2595 verify_cb = SSL_CTX_get_verify_callback(ctx);
2596 SSL_CTX_set_verify(ctx, mode, verify_cb);
2597 return 0;
2598}
2599
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002600/*[clinic input]
2601@classmethod
2602_ssl._SSLContext.__new__
2603 protocol as proto_version: int
2604 /
2605[clinic start generated code]*/
2606
Antoine Pitrou152efa22010-05-16 18:19:27 +00002607static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002608_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2609/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002610{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002611 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002612 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002613 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002614 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002615#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002616 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002617#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619 PySSL_BEGIN_ALLOW_THREADS
2620 if (proto_version == PY_SSL_VERSION_TLS1)
2621 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002622#if HAVE_TLSv1_2
2623 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2624 ctx = SSL_CTX_new(TLSv1_1_method());
2625 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2626 ctx = SSL_CTX_new(TLSv1_2_method());
2627#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002628#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002629 else if (proto_version == PY_SSL_VERSION_SSL3)
2630 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002631#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002632#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002633 else if (proto_version == PY_SSL_VERSION_SSL2)
2634 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002635#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002636 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002637 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002638 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2639 ctx = SSL_CTX_new(TLS_client_method());
2640 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2641 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002642 else
2643 proto_version = -1;
2644 PySSL_END_ALLOW_THREADS
2645
2646 if (proto_version == -1) {
2647 PyErr_SetString(PyExc_ValueError,
2648 "invalid protocol version");
2649 return NULL;
2650 }
2651 if (ctx == NULL) {
2652 PyErr_SetString(PySSLErrorObject,
2653 "failed to allocate SSL context");
2654 return NULL;
2655 }
2656
2657 assert(type != NULL && type->tp_alloc != NULL);
2658 self = (PySSLContext *) type->tp_alloc(type, 0);
2659 if (self == NULL) {
2660 SSL_CTX_free(ctx);
2661 return NULL;
2662 }
2663 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002664#ifdef OPENSSL_NPN_NEGOTIATED
2665 self->npn_protocols = NULL;
2666#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002667#ifdef HAVE_ALPN
2668 self->alpn_protocols = NULL;
2669#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002670#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002671 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002672#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002673 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002674 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2675 self->check_hostname = 1;
2676 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2677 Py_DECREF(self);
2678 return NULL;
2679 }
2680 } else {
2681 self->check_hostname = 0;
2682 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2683 Py_DECREF(self);
2684 return NULL;
2685 }
2686 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002687 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002688 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2689 if (proto_version != PY_SSL_VERSION_SSL2)
2690 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002691 if (proto_version != PY_SSL_VERSION_SSL3)
2692 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002693 /* Minimal security flags for server and client side context.
2694 * Client sockets ignore server-side parameters. */
2695#ifdef SSL_OP_NO_COMPRESSION
2696 options |= SSL_OP_NO_COMPRESSION;
2697#endif
2698#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2699 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2700#endif
2701#ifdef SSL_OP_SINGLE_DH_USE
2702 options |= SSL_OP_SINGLE_DH_USE;
2703#endif
2704#ifdef SSL_OP_SINGLE_ECDH_USE
2705 options |= SSL_OP_SINGLE_ECDH_USE;
2706#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002707 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002708
Christian Heimes358cfd42016-09-10 22:43:48 +02002709 /* A bare minimum cipher list without completly broken cipher suites.
2710 * It's far from perfect but gives users a better head start. */
2711 if (proto_version != PY_SSL_VERSION_SSL2) {
2712 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2713 } else {
2714 /* SSLv2 needs MD5 */
2715 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2716 }
2717 if (result == 0) {
2718 Py_DECREF(self);
2719 ERR_clear_error();
2720 PyErr_SetString(PySSLErrorObject,
2721 "No cipher can be selected.");
2722 return NULL;
2723 }
2724
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002725#if defined(SSL_MODE_RELEASE_BUFFERS)
2726 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2727 usage for no cost at all. However, don't do this for OpenSSL versions
2728 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2729 2014-0198. I can't find exactly which beta fixed this CVE, so be
2730 conservative and assume it wasn't fixed until release. We do this check
2731 at runtime to avoid problems from the dynamic linker.
2732 See #25672 for more on this. */
2733 libver = SSLeay();
2734 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2735 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2736 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2737 }
2738#endif
2739
2740
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002741#ifndef OPENSSL_NO_ECDH
2742 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2743 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002744 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2745 */
2746#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002747 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2748#else
2749 {
2750 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2751 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2752 EC_KEY_free(key);
2753 }
2754#endif
2755#endif
2756
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002757#define SID_CTX "Python"
2758 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2759 sizeof(SID_CTX));
2760#undef SID_CTX
2761
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002762#ifdef X509_V_FLAG_TRUSTED_FIRST
2763 {
2764 /* Improve trust chain building when cross-signed intermediate
2765 certificates are present. See https://bugs.python.org/issue23476. */
2766 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2767 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2768 }
2769#endif
2770
Antoine Pitrou152efa22010-05-16 18:19:27 +00002771 return (PyObject *)self;
2772}
2773
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002774static int
2775context_traverse(PySSLContext *self, visitproc visit, void *arg)
2776{
2777#ifndef OPENSSL_NO_TLSEXT
2778 Py_VISIT(self->set_hostname);
2779#endif
2780 return 0;
2781}
2782
2783static int
2784context_clear(PySSLContext *self)
2785{
2786#ifndef OPENSSL_NO_TLSEXT
2787 Py_CLEAR(self->set_hostname);
2788#endif
2789 return 0;
2790}
2791
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792static void
2793context_dealloc(PySSLContext *self)
2794{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002795 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002796 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002797#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002798 PyMem_FREE(self->npn_protocols);
2799#endif
2800#ifdef HAVE_ALPN
2801 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002802#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002803 Py_TYPE(self)->tp_free(self);
2804}
2805
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002806/*[clinic input]
2807_ssl._SSLContext.set_ciphers
2808 cipherlist: str
2809 /
2810[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002811
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002812static PyObject *
2813_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2814/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2815{
2816 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002817 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002818 /* Clearing the error queue is necessary on some OpenSSL versions,
2819 otherwise the error will be reported again when another SSL call
2820 is done. */
2821 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822 PyErr_SetString(PySSLErrorObject,
2823 "No cipher can be selected.");
2824 return NULL;
2825 }
2826 Py_RETURN_NONE;
2827}
2828
Christian Heimes25bfcd52016-09-06 00:04:45 +02002829#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2830/*[clinic input]
2831_ssl._SSLContext.get_ciphers
2832[clinic start generated code]*/
2833
2834static PyObject *
2835_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2836/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2837{
2838 SSL *ssl = NULL;
2839 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002840 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002841 int i=0;
2842 PyObject *result = NULL, *dct;
2843
2844 ssl = SSL_new(self->ctx);
2845 if (ssl == NULL) {
2846 _setSSLError(NULL, 0, __FILE__, __LINE__);
2847 goto exit;
2848 }
2849 sk = SSL_get_ciphers(ssl);
2850
2851 result = PyList_New(sk_SSL_CIPHER_num(sk));
2852 if (result == NULL) {
2853 goto exit;
2854 }
2855
2856 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2857 cipher = sk_SSL_CIPHER_value(sk, i);
2858 dct = cipher_to_dict(cipher);
2859 if (dct == NULL) {
2860 Py_CLEAR(result);
2861 goto exit;
2862 }
2863 PyList_SET_ITEM(result, i, dct);
2864 }
2865
2866 exit:
2867 if (ssl != NULL)
2868 SSL_free(ssl);
2869 return result;
2870
2871}
2872#endif
2873
2874
Benjamin Petersonc54de472015-01-28 12:06:39 -05002875#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002876static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002877do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2878 const unsigned char *server_protocols, unsigned int server_protocols_len,
2879 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002880{
Benjamin Peterson88615022015-01-23 17:30:26 -05002881 int ret;
2882 if (client_protocols == NULL) {
2883 client_protocols = (unsigned char *)"";
2884 client_protocols_len = 0;
2885 }
2886 if (server_protocols == NULL) {
2887 server_protocols = (unsigned char *)"";
2888 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002889 }
2890
Benjamin Peterson88615022015-01-23 17:30:26 -05002891 ret = SSL_select_next_proto(out, outlen,
2892 server_protocols, server_protocols_len,
2893 client_protocols, client_protocols_len);
2894 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2895 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002896
2897 return SSL_TLSEXT_ERR_OK;
2898}
2899
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002900/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2901static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002902_advertiseNPN_cb(SSL *s,
2903 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002904 void *args)
2905{
2906 PySSLContext *ssl_ctx = (PySSLContext *) args;
2907
2908 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002909 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002910 *len = 0;
2911 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002912 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002913 *len = ssl_ctx->npn_protocols_len;
2914 }
2915
2916 return SSL_TLSEXT_ERR_OK;
2917}
2918/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2919static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002920_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002921 unsigned char **out, unsigned char *outlen,
2922 const unsigned char *server, unsigned int server_len,
2923 void *args)
2924{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002925 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002926 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002927 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002928}
2929#endif
2930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002931/*[clinic input]
2932_ssl._SSLContext._set_npn_protocols
2933 protos: Py_buffer
2934 /
2935[clinic start generated code]*/
2936
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002937static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002938_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2939 Py_buffer *protos)
2940/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002941{
2942#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002943 PyMem_Free(self->npn_protocols);
2944 self->npn_protocols = PyMem_Malloc(protos->len);
2945 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002946 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002947 memcpy(self->npn_protocols, protos->buf, protos->len);
2948 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002949
2950 /* set both server and client callbacks, because the context can
2951 * be used to create both types of sockets */
2952 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2953 _advertiseNPN_cb,
2954 self);
2955 SSL_CTX_set_next_proto_select_cb(self->ctx,
2956 _selectNPN_cb,
2957 self);
2958
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002959 Py_RETURN_NONE;
2960#else
2961 PyErr_SetString(PyExc_NotImplementedError,
2962 "The NPN extension requires OpenSSL 1.0.1 or later.");
2963 return NULL;
2964#endif
2965}
2966
Benjamin Petersoncca27322015-01-23 16:35:37 -05002967#ifdef HAVE_ALPN
2968static int
2969_selectALPN_cb(SSL *s,
2970 const unsigned char **out, unsigned char *outlen,
2971 const unsigned char *client_protocols, unsigned int client_protocols_len,
2972 void *args)
2973{
2974 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002975 return do_protocol_selection(1, (unsigned char **)out, outlen,
2976 ctx->alpn_protocols, ctx->alpn_protocols_len,
2977 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002978}
2979#endif
2980
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002981/*[clinic input]
2982_ssl._SSLContext._set_alpn_protocols
2983 protos: Py_buffer
2984 /
2985[clinic start generated code]*/
2986
Benjamin Petersoncca27322015-01-23 16:35:37 -05002987static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002988_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2989 Py_buffer *protos)
2990/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002991{
2992#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002993 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002994 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002995 if (!self->alpn_protocols)
2996 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002997 memcpy(self->alpn_protocols, protos->buf, protos->len);
2998 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002999
3000 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3001 return PyErr_NoMemory();
3002 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3003
Benjamin Petersoncca27322015-01-23 16:35:37 -05003004 Py_RETURN_NONE;
3005#else
3006 PyErr_SetString(PyExc_NotImplementedError,
3007 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3008 return NULL;
3009#endif
3010}
3011
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012static PyObject *
3013get_verify_mode(PySSLContext *self, void *c)
3014{
3015 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3016 case SSL_VERIFY_NONE:
3017 return PyLong_FromLong(PY_SSL_CERT_NONE);
3018 case SSL_VERIFY_PEER:
3019 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3020 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3021 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3022 }
3023 PyErr_SetString(PySSLErrorObject,
3024 "invalid return value from SSL_CTX_get_verify_mode");
3025 return NULL;
3026}
3027
3028static int
3029set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3030{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003031 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003032 if (!PyArg_Parse(arg, "i", &n))
3033 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003034 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003035 PyErr_SetString(PyExc_ValueError,
3036 "Cannot set verify_mode to CERT_NONE when "
3037 "check_hostname is enabled.");
3038 return -1;
3039 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003040 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003041}
3042
3043static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003044get_verify_flags(PySSLContext *self, void *c)
3045{
3046 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003047 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003048 unsigned long flags;
3049
3050 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003051 param = X509_STORE_get0_param(store);
3052 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003053 return PyLong_FromUnsignedLong(flags);
3054}
3055
3056static int
3057set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3058{
3059 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003060 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003061 unsigned long new_flags, flags, set, clear;
3062
3063 if (!PyArg_Parse(arg, "k", &new_flags))
3064 return -1;
3065 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003066 param = X509_STORE_get0_param(store);
3067 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003068 clear = flags & ~new_flags;
3069 set = ~flags & new_flags;
3070 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003071 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003072 _setSSLError(NULL, 0, __FILE__, __LINE__);
3073 return -1;
3074 }
3075 }
3076 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003077 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003078 _setSSLError(NULL, 0, __FILE__, __LINE__);
3079 return -1;
3080 }
3081 }
3082 return 0;
3083}
3084
3085static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003086get_options(PySSLContext *self, void *c)
3087{
3088 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3089}
3090
3091static int
3092set_options(PySSLContext *self, PyObject *arg, void *c)
3093{
3094 long new_opts, opts, set, clear;
3095 if (!PyArg_Parse(arg, "l", &new_opts))
3096 return -1;
3097 opts = SSL_CTX_get_options(self->ctx);
3098 clear = opts & ~new_opts;
3099 set = ~opts & new_opts;
3100 if (clear) {
3101#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3102 SSL_CTX_clear_options(self->ctx, clear);
3103#else
3104 PyErr_SetString(PyExc_ValueError,
3105 "can't clear options before OpenSSL 0.9.8m");
3106 return -1;
3107#endif
3108 }
3109 if (set)
3110 SSL_CTX_set_options(self->ctx, set);
3111 return 0;
3112}
3113
Christian Heimes1aa9a752013-12-02 02:41:19 +01003114static PyObject *
3115get_check_hostname(PySSLContext *self, void *c)
3116{
3117 return PyBool_FromLong(self->check_hostname);
3118}
3119
3120static int
3121set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3122{
3123 int check_hostname;
3124 if (!PyArg_Parse(arg, "p", &check_hostname))
3125 return -1;
3126 if (check_hostname &&
3127 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3128 PyErr_SetString(PyExc_ValueError,
3129 "check_hostname needs a SSL context with either "
3130 "CERT_OPTIONAL or CERT_REQUIRED");
3131 return -1;
3132 }
3133 self->check_hostname = check_hostname;
3134 return 0;
3135}
3136
3137
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003138typedef struct {
3139 PyThreadState *thread_state;
3140 PyObject *callable;
3141 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003142 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003143 int error;
3144} _PySSLPasswordInfo;
3145
3146static int
3147_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3148 const char *bad_type_error)
3149{
3150 /* Set the password and size fields of a _PySSLPasswordInfo struct
3151 from a unicode, bytes, or byte array object.
3152 The password field will be dynamically allocated and must be freed
3153 by the caller */
3154 PyObject *password_bytes = NULL;
3155 const char *data = NULL;
3156 Py_ssize_t size;
3157
3158 if (PyUnicode_Check(password)) {
3159 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3160 if (!password_bytes) {
3161 goto error;
3162 }
3163 data = PyBytes_AS_STRING(password_bytes);
3164 size = PyBytes_GET_SIZE(password_bytes);
3165 } else if (PyBytes_Check(password)) {
3166 data = PyBytes_AS_STRING(password);
3167 size = PyBytes_GET_SIZE(password);
3168 } else if (PyByteArray_Check(password)) {
3169 data = PyByteArray_AS_STRING(password);
3170 size = PyByteArray_GET_SIZE(password);
3171 } else {
3172 PyErr_SetString(PyExc_TypeError, bad_type_error);
3173 goto error;
3174 }
3175
Victor Stinner9ee02032013-06-23 15:08:23 +02003176 if (size > (Py_ssize_t)INT_MAX) {
3177 PyErr_Format(PyExc_ValueError,
3178 "password cannot be longer than %d bytes", INT_MAX);
3179 goto error;
3180 }
3181
Victor Stinner11ebff22013-07-07 17:07:52 +02003182 PyMem_Free(pw_info->password);
3183 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003184 if (!pw_info->password) {
3185 PyErr_SetString(PyExc_MemoryError,
3186 "unable to allocate password buffer");
3187 goto error;
3188 }
3189 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003190 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003191
3192 Py_XDECREF(password_bytes);
3193 return 1;
3194
3195error:
3196 Py_XDECREF(password_bytes);
3197 return 0;
3198}
3199
3200static int
3201_password_callback(char *buf, int size, int rwflag, void *userdata)
3202{
3203 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3204 PyObject *fn_ret = NULL;
3205
3206 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3207
3208 if (pw_info->callable) {
3209 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
3210 if (!fn_ret) {
3211 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3212 core python API, so we could use it to add a frame here */
3213 goto error;
3214 }
3215
3216 if (!_pwinfo_set(pw_info, fn_ret,
3217 "password callback must return a string")) {
3218 goto error;
3219 }
3220 Py_CLEAR(fn_ret);
3221 }
3222
3223 if (pw_info->size > size) {
3224 PyErr_Format(PyExc_ValueError,
3225 "password cannot be longer than %d bytes", size);
3226 goto error;
3227 }
3228
3229 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3230 memcpy(buf, pw_info->password, pw_info->size);
3231 return pw_info->size;
3232
3233error:
3234 Py_XDECREF(fn_ret);
3235 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3236 pw_info->error = 1;
3237 return -1;
3238}
3239
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240/*[clinic input]
3241_ssl._SSLContext.load_cert_chain
3242 certfile: object
3243 keyfile: object = NULL
3244 password: object = NULL
3245
3246[clinic start generated code]*/
3247
Antoine Pitroub5218772010-05-21 09:56:06 +00003248static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003249_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3250 PyObject *keyfile, PyObject *password)
3251/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003254 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3255 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003256 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257 int r;
3258
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003259 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003260 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003261 if (keyfile == Py_None)
3262 keyfile = NULL;
3263 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3264 PyErr_SetString(PyExc_TypeError,
3265 "certfile should be a valid filesystem path");
3266 return NULL;
3267 }
3268 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3269 PyErr_SetString(PyExc_TypeError,
3270 "keyfile should be a valid filesystem path");
3271 goto error;
3272 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003273 if (password && password != Py_None) {
3274 if (PyCallable_Check(password)) {
3275 pw_info.callable = password;
3276 } else if (!_pwinfo_set(&pw_info, password,
3277 "password should be a string or callable")) {
3278 goto error;
3279 }
3280 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3281 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3282 }
3283 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3285 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003286 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003287 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003288 if (pw_info.error) {
3289 ERR_clear_error();
3290 /* the password callback has already set the error information */
3291 }
3292 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003293 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003294 PyErr_SetFromErrno(PyExc_IOError);
3295 }
3296 else {
3297 _setSSLError(NULL, 0, __FILE__, __LINE__);
3298 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299 goto error;
3300 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003301 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003302 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003303 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3304 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003305 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3306 Py_CLEAR(keyfile_bytes);
3307 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003309 if (pw_info.error) {
3310 ERR_clear_error();
3311 /* the password callback has already set the error information */
3312 }
3313 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003314 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003315 PyErr_SetFromErrno(PyExc_IOError);
3316 }
3317 else {
3318 _setSSLError(NULL, 0, __FILE__, __LINE__);
3319 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003320 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003322 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003323 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003324 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325 if (r != 1) {
3326 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003327 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003329 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3330 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003331 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003332 Py_RETURN_NONE;
3333
3334error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003335 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3336 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003337 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003338 Py_XDECREF(keyfile_bytes);
3339 Py_XDECREF(certfile_bytes);
3340 return NULL;
3341}
3342
Christian Heimesefff7062013-11-21 03:35:02 +01003343/* internal helper function, returns -1 on error
3344 */
3345static int
3346_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3347 int filetype)
3348{
3349 BIO *biobuf = NULL;
3350 X509_STORE *store;
3351 int retval = 0, err, loaded = 0;
3352
3353 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3354
3355 if (len <= 0) {
3356 PyErr_SetString(PyExc_ValueError,
3357 "Empty certificate data");
3358 return -1;
3359 } else if (len > INT_MAX) {
3360 PyErr_SetString(PyExc_OverflowError,
3361 "Certificate data is too long.");
3362 return -1;
3363 }
3364
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003365 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003366 if (biobuf == NULL) {
3367 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3368 return -1;
3369 }
3370
3371 store = SSL_CTX_get_cert_store(self->ctx);
3372 assert(store != NULL);
3373
3374 while (1) {
3375 X509 *cert = NULL;
3376 int r;
3377
3378 if (filetype == SSL_FILETYPE_ASN1) {
3379 cert = d2i_X509_bio(biobuf, NULL);
3380 } else {
3381 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003382 SSL_CTX_get_default_passwd_cb(self->ctx),
3383 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3384 );
Christian Heimesefff7062013-11-21 03:35:02 +01003385 }
3386 if (cert == NULL) {
3387 break;
3388 }
3389 r = X509_STORE_add_cert(store, cert);
3390 X509_free(cert);
3391 if (!r) {
3392 err = ERR_peek_last_error();
3393 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3394 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3395 /* cert already in hash table, not an error */
3396 ERR_clear_error();
3397 } else {
3398 break;
3399 }
3400 }
3401 loaded++;
3402 }
3403
3404 err = ERR_peek_last_error();
3405 if ((filetype == SSL_FILETYPE_ASN1) &&
3406 (loaded > 0) &&
3407 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3408 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3409 /* EOF ASN1 file, not an error */
3410 ERR_clear_error();
3411 retval = 0;
3412 } else if ((filetype == SSL_FILETYPE_PEM) &&
3413 (loaded > 0) &&
3414 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3415 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3416 /* EOF PEM file, not an error */
3417 ERR_clear_error();
3418 retval = 0;
3419 } else {
3420 _setSSLError(NULL, 0, __FILE__, __LINE__);
3421 retval = -1;
3422 }
3423
3424 BIO_free(biobuf);
3425 return retval;
3426}
3427
3428
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003429/*[clinic input]
3430_ssl._SSLContext.load_verify_locations
3431 cafile: object = NULL
3432 capath: object = NULL
3433 cadata: object = NULL
3434
3435[clinic start generated code]*/
3436
Antoine Pitrou152efa22010-05-16 18:19:27 +00003437static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003438_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3439 PyObject *cafile,
3440 PyObject *capath,
3441 PyObject *cadata)
3442/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003443{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003444 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3445 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003446 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003447
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003448 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003449 if (cafile == Py_None)
3450 cafile = NULL;
3451 if (capath == Py_None)
3452 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003453 if (cadata == Py_None)
3454 cadata = NULL;
3455
3456 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003457 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003458 "cafile, capath and cadata cannot be all omitted");
3459 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003460 }
3461 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3462 PyErr_SetString(PyExc_TypeError,
3463 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003464 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003465 }
3466 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003467 PyErr_SetString(PyExc_TypeError,
3468 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003469 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003470 }
Christian Heimesefff7062013-11-21 03:35:02 +01003471
3472 /* validata cadata type and load cadata */
3473 if (cadata) {
3474 Py_buffer buf;
3475 PyObject *cadata_ascii = NULL;
3476
3477 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3478 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3479 PyBuffer_Release(&buf);
3480 PyErr_SetString(PyExc_TypeError,
3481 "cadata should be a contiguous buffer with "
3482 "a single dimension");
3483 goto error;
3484 }
3485 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3486 PyBuffer_Release(&buf);
3487 if (r == -1) {
3488 goto error;
3489 }
3490 } else {
3491 PyErr_Clear();
3492 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3493 if (cadata_ascii == NULL) {
3494 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003495 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003496 "bytes-like object");
3497 goto error;
3498 }
3499 r = _add_ca_certs(self,
3500 PyBytes_AS_STRING(cadata_ascii),
3501 PyBytes_GET_SIZE(cadata_ascii),
3502 SSL_FILETYPE_PEM);
3503 Py_DECREF(cadata_ascii);
3504 if (r == -1) {
3505 goto error;
3506 }
3507 }
3508 }
3509
3510 /* load cafile or capath */
3511 if (cafile || capath) {
3512 if (cafile)
3513 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3514 if (capath)
3515 capath_buf = PyBytes_AS_STRING(capath_bytes);
3516 PySSL_BEGIN_ALLOW_THREADS
3517 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3518 PySSL_END_ALLOW_THREADS
3519 if (r != 1) {
3520 ok = 0;
3521 if (errno != 0) {
3522 ERR_clear_error();
3523 PyErr_SetFromErrno(PyExc_IOError);
3524 }
3525 else {
3526 _setSSLError(NULL, 0, __FILE__, __LINE__);
3527 }
3528 goto error;
3529 }
3530 }
3531 goto end;
3532
3533 error:
3534 ok = 0;
3535 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003536 Py_XDECREF(cafile_bytes);
3537 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003538 if (ok) {
3539 Py_RETURN_NONE;
3540 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003541 return NULL;
3542 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003543}
3544
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003545/*[clinic input]
3546_ssl._SSLContext.load_dh_params
3547 path as filepath: object
3548 /
3549
3550[clinic start generated code]*/
3551
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003553_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3554/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003555{
3556 FILE *f;
3557 DH *dh;
3558
Victor Stinnerdaf45552013-08-28 00:53:59 +02003559 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003560 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003561 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003562
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003563 errno = 0;
3564 PySSL_BEGIN_ALLOW_THREADS
3565 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003566 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003567 PySSL_END_ALLOW_THREADS
3568 if (dh == NULL) {
3569 if (errno != 0) {
3570 ERR_clear_error();
3571 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3572 }
3573 else {
3574 _setSSLError(NULL, 0, __FILE__, __LINE__);
3575 }
3576 return NULL;
3577 }
3578 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3579 _setSSLError(NULL, 0, __FILE__, __LINE__);
3580 DH_free(dh);
3581 Py_RETURN_NONE;
3582}
3583
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003584/*[clinic input]
3585_ssl._SSLContext._wrap_socket
3586 sock: object(subclass_of="PySocketModule.Sock_Type")
3587 server_side: int
3588 server_hostname as hostname_obj: object = None
3589
3590[clinic start generated code]*/
3591
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003592static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003593_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3594 int server_side, PyObject *hostname_obj)
3595/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003596{
Antoine Pitroud5323212010-10-22 18:19:07 +00003597 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003598 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003599
Antoine Pitroud5323212010-10-22 18:19:07 +00003600 /* server_hostname is either None (or absent), or to be encoded
3601 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003602 if (hostname_obj != Py_None) {
3603 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003604 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003605 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003606
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003607 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3608 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003609 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003610 if (hostname != NULL)
3611 PyMem_Free(hostname);
3612 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003613}
3614
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003615/*[clinic input]
3616_ssl._SSLContext._wrap_bio
3617 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3618 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3619 server_side: int
3620 server_hostname as hostname_obj: object = None
3621
3622[clinic start generated code]*/
3623
Antoine Pitroub0182c82010-10-12 20:09:02 +00003624static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003625_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3626 PySSLMemoryBIO *outgoing, int server_side,
3627 PyObject *hostname_obj)
3628/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003629{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003630 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003631 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003632
3633 /* server_hostname is either None (or absent), or to be encoded
3634 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003635 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003636 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3637 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003638 }
3639
3640 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3641 incoming, outgoing);
3642
3643 PyMem_Free(hostname);
3644 return res;
3645}
3646
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003647/*[clinic input]
3648_ssl._SSLContext.session_stats
3649[clinic start generated code]*/
3650
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003651static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003652_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3653/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003654{
3655 int r;
3656 PyObject *value, *stats = PyDict_New();
3657 if (!stats)
3658 return NULL;
3659
3660#define ADD_STATS(SSL_NAME, KEY_NAME) \
3661 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3662 if (value == NULL) \
3663 goto error; \
3664 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3665 Py_DECREF(value); \
3666 if (r < 0) \
3667 goto error;
3668
3669 ADD_STATS(number, "number");
3670 ADD_STATS(connect, "connect");
3671 ADD_STATS(connect_good, "connect_good");
3672 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3673 ADD_STATS(accept, "accept");
3674 ADD_STATS(accept_good, "accept_good");
3675 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3676 ADD_STATS(accept, "accept");
3677 ADD_STATS(hits, "hits");
3678 ADD_STATS(misses, "misses");
3679 ADD_STATS(timeouts, "timeouts");
3680 ADD_STATS(cache_full, "cache_full");
3681
3682#undef ADD_STATS
3683
3684 return stats;
3685
3686error:
3687 Py_DECREF(stats);
3688 return NULL;
3689}
3690
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003691/*[clinic input]
3692_ssl._SSLContext.set_default_verify_paths
3693[clinic start generated code]*/
3694
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003695static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003696_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3697/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003698{
3699 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3700 _setSSLError(NULL, 0, __FILE__, __LINE__);
3701 return NULL;
3702 }
3703 Py_RETURN_NONE;
3704}
3705
Antoine Pitrou501da612011-12-21 09:27:41 +01003706#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003707/*[clinic input]
3708_ssl._SSLContext.set_ecdh_curve
3709 name: object
3710 /
3711
3712[clinic start generated code]*/
3713
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003714static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003715_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3716/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003717{
3718 PyObject *name_bytes;
3719 int nid;
3720 EC_KEY *key;
3721
3722 if (!PyUnicode_FSConverter(name, &name_bytes))
3723 return NULL;
3724 assert(PyBytes_Check(name_bytes));
3725 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3726 Py_DECREF(name_bytes);
3727 if (nid == 0) {
3728 PyErr_Format(PyExc_ValueError,
3729 "unknown elliptic curve name %R", name);
3730 return NULL;
3731 }
3732 key = EC_KEY_new_by_curve_name(nid);
3733 if (key == NULL) {
3734 _setSSLError(NULL, 0, __FILE__, __LINE__);
3735 return NULL;
3736 }
3737 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3738 EC_KEY_free(key);
3739 Py_RETURN_NONE;
3740}
Antoine Pitrou501da612011-12-21 09:27:41 +01003741#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003742
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003743#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003744static int
3745_servername_callback(SSL *s, int *al, void *args)
3746{
3747 int ret;
3748 PySSLContext *ssl_ctx = (PySSLContext *) args;
3749 PySSLSocket *ssl;
3750 PyObject *servername_o;
3751 PyObject *servername_idna;
3752 PyObject *result;
3753 /* The high-level ssl.SSLSocket object */
3754 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003755 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003756#ifdef WITH_THREAD
3757 PyGILState_STATE gstate = PyGILState_Ensure();
3758#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003759
3760 if (ssl_ctx->set_hostname == NULL) {
3761 /* remove race condition in this the call back while if removing the
3762 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003763#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003764 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003765#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003766 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003767 }
3768
3769 ssl = SSL_get_app_data(s);
3770 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003771
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003772 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003773 * SSL connection and that has a .context attribute that can be changed to
3774 * identify the requested hostname. Since the official API is the Python
3775 * level API we want to pass the callback a Python level object rather than
3776 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3777 * SSLObject) that will be passed. Otherwise if there's a socket then that
3778 * will be passed. If both do not exist only then the C-level object is
3779 * passed. */
3780 if (ssl->owner)
3781 ssl_socket = PyWeakref_GetObject(ssl->owner);
3782 else if (ssl->Socket)
3783 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3784 else
3785 ssl_socket = (PyObject *) ssl;
3786
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003787 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003788 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003789 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003790
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003791 if (servername == NULL) {
3792 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3793 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003794 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003795 else {
3796 servername_o = PyBytes_FromString(servername);
3797 if (servername_o == NULL) {
3798 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3799 goto error;
3800 }
3801 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3802 if (servername_idna == NULL) {
3803 PyErr_WriteUnraisable(servername_o);
3804 Py_DECREF(servername_o);
3805 goto error;
3806 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003807 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003808 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3809 servername_idna, ssl_ctx, NULL);
3810 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003811 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003812 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003813
3814 if (result == NULL) {
3815 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3816 *al = SSL_AD_HANDSHAKE_FAILURE;
3817 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3818 }
3819 else {
3820 if (result != Py_None) {
3821 *al = (int) PyLong_AsLong(result);
3822 if (PyErr_Occurred()) {
3823 PyErr_WriteUnraisable(result);
3824 *al = SSL_AD_INTERNAL_ERROR;
3825 }
3826 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3827 }
3828 else {
3829 ret = SSL_TLSEXT_ERR_OK;
3830 }
3831 Py_DECREF(result);
3832 }
3833
Stefan Krah20d60802013-01-17 17:07:17 +01003834#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003835 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003836#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003837 return ret;
3838
3839error:
3840 Py_DECREF(ssl_socket);
3841 *al = SSL_AD_INTERNAL_ERROR;
3842 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003843#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003844 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003845#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003846 return ret;
3847}
Antoine Pitroua5963382013-03-30 16:39:00 +01003848#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003849
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003850/*[clinic input]
3851_ssl._SSLContext.set_servername_callback
3852 method as cb: object
3853 /
3854
3855Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3856
3857If the argument is None then the callback is disabled. The method is called
3858with the SSLSocket, the server name as a string, and the SSLContext object.
3859See RFC 6066 for details of the SNI extension.
3860[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003861
3862static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003863_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3864/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003865{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003866#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003867 Py_CLEAR(self->set_hostname);
3868 if (cb == Py_None) {
3869 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3870 }
3871 else {
3872 if (!PyCallable_Check(cb)) {
3873 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3874 PyErr_SetString(PyExc_TypeError,
3875 "not a callable object");
3876 return NULL;
3877 }
3878 Py_INCREF(cb);
3879 self->set_hostname = cb;
3880 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3881 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3882 }
3883 Py_RETURN_NONE;
3884#else
3885 PyErr_SetString(PyExc_NotImplementedError,
3886 "The TLS extension servername callback, "
3887 "SSL_CTX_set_tlsext_servername_callback, "
3888 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003889 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003890#endif
3891}
3892
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003893/*[clinic input]
3894_ssl._SSLContext.cert_store_stats
3895
3896Returns quantities of loaded X.509 certificates.
3897
3898X.509 certificates with a CA extension and certificate revocation lists
3899inside the context's cert store.
3900
3901NOTE: Certificates in a capath directory aren't loaded unless they have
3902been used at least once.
3903[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003904
3905static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003906_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3907/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003908{
3909 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003910 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003911 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003912 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003913
3914 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003915 objs = X509_STORE_get0_objects(store);
3916 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3917 obj = sk_X509_OBJECT_value(objs, i);
3918 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003919 case X509_LU_X509:
3920 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003921 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003922 ca++;
3923 }
3924 break;
3925 case X509_LU_CRL:
3926 crl++;
3927 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003928 default:
3929 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3930 * As far as I can tell they are internal states and never
3931 * stored in a cert store */
3932 break;
3933 }
3934 }
3935 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3936 "x509_ca", ca);
3937}
3938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003939/*[clinic input]
3940_ssl._SSLContext.get_ca_certs
3941 binary_form: bool = False
3942
3943Returns a list of dicts with information of loaded CA certs.
3944
3945If the optional argument is True, returns a DER-encoded copy of the CA
3946certificate.
3947
3948NOTE: Certificates in a capath directory aren't loaded unless they have
3949been used at least once.
3950[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003951
3952static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003953_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3954/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003955{
3956 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003957 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003958 PyObject *ci = NULL, *rlist = NULL;
3959 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003960
3961 if ((rlist = PyList_New(0)) == NULL) {
3962 return NULL;
3963 }
3964
3965 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003966 objs = X509_STORE_get0_objects(store);
3967 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003968 X509_OBJECT *obj;
3969 X509 *cert;
3970
Christian Heimes598894f2016-09-05 23:19:05 +02003971 obj = sk_X509_OBJECT_value(objs, i);
3972 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003973 /* not a x509 cert */
3974 continue;
3975 }
3976 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003977 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003978 if (!X509_check_ca(cert)) {
3979 continue;
3980 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003981 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003982 ci = _certificate_to_der(cert);
3983 } else {
3984 ci = _decode_certificate(cert);
3985 }
3986 if (ci == NULL) {
3987 goto error;
3988 }
3989 if (PyList_Append(rlist, ci) == -1) {
3990 goto error;
3991 }
3992 Py_CLEAR(ci);
3993 }
3994 return rlist;
3995
3996 error:
3997 Py_XDECREF(ci);
3998 Py_XDECREF(rlist);
3999 return NULL;
4000}
4001
4002
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004004 {"check_hostname", (getter) get_check_hostname,
4005 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004006 {"options", (getter) get_options,
4007 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004008 {"verify_flags", (getter) get_verify_flags,
4009 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004010 {"verify_mode", (getter) get_verify_mode,
4011 (setter) set_verify_mode, NULL},
4012 {NULL}, /* sentinel */
4013};
4014
4015static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004016 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4017 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4018 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4019 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4020 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4021 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4022 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4023 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4024 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4025 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4026 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4027 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4028 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4029 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004030 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031 {NULL, NULL} /* sentinel */
4032};
4033
4034static PyTypeObject PySSLContext_Type = {
4035 PyVarObject_HEAD_INIT(NULL, 0)
4036 "_ssl._SSLContext", /*tp_name*/
4037 sizeof(PySSLContext), /*tp_basicsize*/
4038 0, /*tp_itemsize*/
4039 (destructor)context_dealloc, /*tp_dealloc*/
4040 0, /*tp_print*/
4041 0, /*tp_getattr*/
4042 0, /*tp_setattr*/
4043 0, /*tp_reserved*/
4044 0, /*tp_repr*/
4045 0, /*tp_as_number*/
4046 0, /*tp_as_sequence*/
4047 0, /*tp_as_mapping*/
4048 0, /*tp_hash*/
4049 0, /*tp_call*/
4050 0, /*tp_str*/
4051 0, /*tp_getattro*/
4052 0, /*tp_setattro*/
4053 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004055 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004056 (traverseproc) context_traverse, /*tp_traverse*/
4057 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058 0, /*tp_richcompare*/
4059 0, /*tp_weaklistoffset*/
4060 0, /*tp_iter*/
4061 0, /*tp_iternext*/
4062 context_methods, /*tp_methods*/
4063 0, /*tp_members*/
4064 context_getsetlist, /*tp_getset*/
4065 0, /*tp_base*/
4066 0, /*tp_dict*/
4067 0, /*tp_descr_get*/
4068 0, /*tp_descr_set*/
4069 0, /*tp_dictoffset*/
4070 0, /*tp_init*/
4071 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004073};
4074
4075
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004076/*
4077 * MemoryBIO objects
4078 */
4079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004080/*[clinic input]
4081@classmethod
4082_ssl.MemoryBIO.__new__
4083
4084[clinic start generated code]*/
4085
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004086static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004087_ssl_MemoryBIO_impl(PyTypeObject *type)
4088/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004089{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004090 BIO *bio;
4091 PySSLMemoryBIO *self;
4092
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004093 bio = BIO_new(BIO_s_mem());
4094 if (bio == NULL) {
4095 PyErr_SetString(PySSLErrorObject,
4096 "failed to allocate BIO");
4097 return NULL;
4098 }
4099 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4100 * just that no data is currently available. The SSL routines should retry
4101 * the read, which we can achieve by calling BIO_set_retry_read(). */
4102 BIO_set_retry_read(bio);
4103 BIO_set_mem_eof_return(bio, -1);
4104
4105 assert(type != NULL && type->tp_alloc != NULL);
4106 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4107 if (self == NULL) {
4108 BIO_free(bio);
4109 return NULL;
4110 }
4111 self->bio = bio;
4112 self->eof_written = 0;
4113
4114 return (PyObject *) self;
4115}
4116
4117static void
4118memory_bio_dealloc(PySSLMemoryBIO *self)
4119{
4120 BIO_free(self->bio);
4121 Py_TYPE(self)->tp_free(self);
4122}
4123
4124static PyObject *
4125memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4126{
4127 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4128}
4129
4130PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4131"The number of bytes pending in the memory BIO.");
4132
4133static PyObject *
4134memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4135{
4136 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4137 && self->eof_written);
4138}
4139
4140PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4141"Whether the memory BIO is at EOF.");
4142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004143/*[clinic input]
4144_ssl.MemoryBIO.read
4145 size as len: int = -1
4146 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004148Read up to size bytes from the memory BIO.
4149
4150If size is not specified, read the entire buffer.
4151If the return value is an empty bytes instance, this means either
4152EOF or that no data is available. Use the "eof" property to
4153distinguish between the two.
4154[clinic start generated code]*/
4155
4156static PyObject *
4157_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4158/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4159{
4160 int avail, nbytes;
4161 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004162
4163 avail = BIO_ctrl_pending(self->bio);
4164 if ((len < 0) || (len > avail))
4165 len = avail;
4166
4167 result = PyBytes_FromStringAndSize(NULL, len);
4168 if ((result == NULL) || (len == 0))
4169 return result;
4170
4171 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4172 /* There should never be any short reads but check anyway. */
4173 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4174 Py_DECREF(result);
4175 return NULL;
4176 }
4177
4178 return result;
4179}
4180
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181/*[clinic input]
4182_ssl.MemoryBIO.write
4183 b: Py_buffer
4184 /
4185
4186Writes the bytes b into the memory BIO.
4187
4188Returns the number of bytes written.
4189[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190
4191static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004192_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4193/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004194{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195 int nbytes;
4196
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004197 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198 PyErr_Format(PyExc_OverflowError,
4199 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004200 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 }
4202
4203 if (self->eof_written) {
4204 PyErr_SetString(PySSLErrorObject,
4205 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004206 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004207 }
4208
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004209 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004210 if (nbytes < 0) {
4211 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004212 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213 }
4214
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004216}
4217
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004218/*[clinic input]
4219_ssl.MemoryBIO.write_eof
4220
4221Write an EOF marker to the memory BIO.
4222
4223When all data has been read, the "eof" property will be True.
4224[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004225
4226static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004227_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4228/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004229{
4230 self->eof_written = 1;
4231 /* After an EOF is written, a zero return from read() should be a real EOF
4232 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4233 BIO_clear_retry_flags(self->bio);
4234 BIO_set_mem_eof_return(self->bio, 0);
4235
4236 Py_RETURN_NONE;
4237}
4238
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004239static PyGetSetDef memory_bio_getsetlist[] = {
4240 {"pending", (getter) memory_bio_get_pending, NULL,
4241 PySSL_memory_bio_pending_doc},
4242 {"eof", (getter) memory_bio_get_eof, NULL,
4243 PySSL_memory_bio_eof_doc},
4244 {NULL}, /* sentinel */
4245};
4246
4247static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004248 _SSL_MEMORYBIO_READ_METHODDEF
4249 _SSL_MEMORYBIO_WRITE_METHODDEF
4250 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004251 {NULL, NULL} /* sentinel */
4252};
4253
4254static PyTypeObject PySSLMemoryBIO_Type = {
4255 PyVarObject_HEAD_INIT(NULL, 0)
4256 "_ssl.MemoryBIO", /*tp_name*/
4257 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4258 0, /*tp_itemsize*/
4259 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4260 0, /*tp_print*/
4261 0, /*tp_getattr*/
4262 0, /*tp_setattr*/
4263 0, /*tp_reserved*/
4264 0, /*tp_repr*/
4265 0, /*tp_as_number*/
4266 0, /*tp_as_sequence*/
4267 0, /*tp_as_mapping*/
4268 0, /*tp_hash*/
4269 0, /*tp_call*/
4270 0, /*tp_str*/
4271 0, /*tp_getattro*/
4272 0, /*tp_setattro*/
4273 0, /*tp_as_buffer*/
4274 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4275 0, /*tp_doc*/
4276 0, /*tp_traverse*/
4277 0, /*tp_clear*/
4278 0, /*tp_richcompare*/
4279 0, /*tp_weaklistoffset*/
4280 0, /*tp_iter*/
4281 0, /*tp_iternext*/
4282 memory_bio_methods, /*tp_methods*/
4283 0, /*tp_members*/
4284 memory_bio_getsetlist, /*tp_getset*/
4285 0, /*tp_base*/
4286 0, /*tp_dict*/
4287 0, /*tp_descr_get*/
4288 0, /*tp_descr_set*/
4289 0, /*tp_dictoffset*/
4290 0, /*tp_init*/
4291 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004292 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004293};
4294
Antoine Pitrou152efa22010-05-16 18:19:27 +00004295
Christian Heimes99a65702016-09-10 23:44:53 +02004296/*
4297 * SSL Session object
4298 */
4299
4300static void
4301PySSLSession_dealloc(PySSLSession *self)
4302{
4303 Py_XDECREF(self->ctx);
4304 if (self->session != NULL) {
4305 SSL_SESSION_free(self->session);
4306 }
4307 PyObject_Del(self);
4308}
4309
4310static PyObject *
4311PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4312{
4313 int result;
4314
4315 if (left == NULL || right == NULL) {
4316 PyErr_BadInternalCall();
4317 return NULL;
4318 }
4319
4320 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4321 Py_RETURN_NOTIMPLEMENTED;
4322 }
4323
4324 if (left == right) {
4325 result = 0;
4326 } else {
4327 const unsigned char *left_id, *right_id;
4328 unsigned int left_len, right_len;
4329 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4330 &left_len);
4331 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4332 &right_len);
4333 if (left_len == right_len) {
4334 result = memcmp(left_id, right_id, left_len);
4335 } else {
4336 result = 1;
4337 }
4338 }
4339
4340 switch (op) {
4341 case Py_EQ:
4342 if (result == 0) {
4343 Py_RETURN_TRUE;
4344 } else {
4345 Py_RETURN_FALSE;
4346 }
4347 break;
4348 case Py_NE:
4349 if (result != 0) {
4350 Py_RETURN_TRUE;
4351 } else {
4352 Py_RETURN_FALSE;
4353 }
4354 break;
4355 case Py_LT:
4356 case Py_LE:
4357 case Py_GT:
4358 case Py_GE:
4359 Py_RETURN_NOTIMPLEMENTED;
4360 break;
4361 default:
4362 PyErr_BadArgument();
4363 return NULL;
4364 }
4365}
4366
4367static int
4368PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4369{
4370 Py_VISIT(self->ctx);
4371 return 0;
4372}
4373
4374static int
4375PySSLSession_clear(PySSLSession *self)
4376{
4377 Py_CLEAR(self->ctx);
4378 return 0;
4379}
4380
4381
4382static PyObject *
4383PySSLSession_get_time(PySSLSession *self, void *closure) {
4384 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4385}
4386
4387PyDoc_STRVAR(PySSLSession_get_time_doc,
4388"Session creation time (seconds since epoch).");
4389
4390
4391static PyObject *
4392PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4393 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4394}
4395
4396PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4397"Session timeout (delta in seconds).");
4398
4399
4400static PyObject *
4401PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4402 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4403 return PyLong_FromUnsignedLong(hint);
4404}
4405
4406PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4407"Ticket life time hint.");
4408
4409
4410static PyObject *
4411PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4412 const unsigned char *id;
4413 unsigned int len;
4414 id = SSL_SESSION_get_id(self->session, &len);
4415 return PyBytes_FromStringAndSize((const char *)id, len);
4416}
4417
4418PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4419"Session id");
4420
4421
4422static PyObject *
4423PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4424 if (SSL_SESSION_has_ticket(self->session)) {
4425 Py_RETURN_TRUE;
4426 } else {
4427 Py_RETURN_FALSE;
4428 }
4429}
4430
4431PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4432"Does the session contain a ticket?");
4433
4434
4435static PyGetSetDef PySSLSession_getsetlist[] = {
4436 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4437 PySSLSession_get_has_ticket_doc},
4438 {"id", (getter) PySSLSession_get_session_id, NULL,
4439 PySSLSession_get_session_id_doc},
4440 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4441 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4442 {"time", (getter) PySSLSession_get_time, NULL,
4443 PySSLSession_get_time_doc},
4444 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4445 PySSLSession_get_timeout_doc},
4446 {NULL}, /* sentinel */
4447};
4448
4449static PyTypeObject PySSLSession_Type = {
4450 PyVarObject_HEAD_INIT(NULL, 0)
4451 "_ssl.Session", /*tp_name*/
4452 sizeof(PySSLSession), /*tp_basicsize*/
4453 0, /*tp_itemsize*/
4454 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4455 0, /*tp_print*/
4456 0, /*tp_getattr*/
4457 0, /*tp_setattr*/
4458 0, /*tp_reserved*/
4459 0, /*tp_repr*/
4460 0, /*tp_as_number*/
4461 0, /*tp_as_sequence*/
4462 0, /*tp_as_mapping*/
4463 0, /*tp_hash*/
4464 0, /*tp_call*/
4465 0, /*tp_str*/
4466 0, /*tp_getattro*/
4467 0, /*tp_setattro*/
4468 0, /*tp_as_buffer*/
4469 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4470 0, /*tp_doc*/
4471 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4472 (inquiry)PySSLSession_clear, /*tp_clear*/
4473 PySSLSession_richcompare, /*tp_richcompare*/
4474 0, /*tp_weaklistoffset*/
4475 0, /*tp_iter*/
4476 0, /*tp_iternext*/
4477 0, /*tp_methods*/
4478 0, /*tp_members*/
4479 PySSLSession_getsetlist, /*tp_getset*/
4480};
4481
4482
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004483/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004484/*[clinic input]
4485_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004486 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004487 entropy: double
4488 /
4489
4490Mix string into the OpenSSL PRNG state.
4491
4492entropy (a float) is a lower bound on the entropy contained in
4493string. See RFC 1750.
4494[clinic start generated code]*/
4495
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004497_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4498/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004499{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004500 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004501 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004502
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004503 buf = (const char *)view->buf;
4504 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004505 do {
4506 written = Py_MIN(len, INT_MAX);
4507 RAND_add(buf, (int)written, entropy);
4508 buf += written;
4509 len -= written;
4510 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004511 Py_INCREF(Py_None);
4512 return Py_None;
4513}
4514
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004515static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004516PySSL_RAND(int len, int pseudo)
4517{
4518 int ok;
4519 PyObject *bytes;
4520 unsigned long err;
4521 const char *errstr;
4522 PyObject *v;
4523
Victor Stinner1e81a392013-12-19 16:47:04 +01004524 if (len < 0) {
4525 PyErr_SetString(PyExc_ValueError, "num must be positive");
4526 return NULL;
4527 }
4528
Victor Stinner99c8b162011-05-24 12:05:19 +02004529 bytes = PyBytes_FromStringAndSize(NULL, len);
4530 if (bytes == NULL)
4531 return NULL;
4532 if (pseudo) {
4533 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4534 if (ok == 0 || ok == 1)
4535 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4536 }
4537 else {
4538 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4539 if (ok == 1)
4540 return bytes;
4541 }
4542 Py_DECREF(bytes);
4543
4544 err = ERR_get_error();
4545 errstr = ERR_reason_error_string(err);
4546 v = Py_BuildValue("(ks)", err, errstr);
4547 if (v != NULL) {
4548 PyErr_SetObject(PySSLErrorObject, v);
4549 Py_DECREF(v);
4550 }
4551 return NULL;
4552}
4553
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004554/*[clinic input]
4555_ssl.RAND_bytes
4556 n: int
4557 /
4558
4559Generate n cryptographically strong pseudo-random bytes.
4560[clinic start generated code]*/
4561
Victor Stinner99c8b162011-05-24 12:05:19 +02004562static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004563_ssl_RAND_bytes_impl(PyObject *module, int n)
4564/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004565{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004566 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004567}
4568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004569/*[clinic input]
4570_ssl.RAND_pseudo_bytes
4571 n: int
4572 /
4573
4574Generate n pseudo-random bytes.
4575
4576Return a pair (bytes, is_cryptographic). is_cryptographic is True
4577if the bytes generated are cryptographically strong.
4578[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004579
4580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004581_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4582/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004583{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004584 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004585}
4586
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004587/*[clinic input]
4588_ssl.RAND_status
4589
4590Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4591
4592It is necessary to seed the PRNG with RAND_add() on some platforms before
4593using the ssl() function.
4594[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004595
4596static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004597_ssl_RAND_status_impl(PyObject *module)
4598/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004599{
Christian Heimes217cfd12007-12-02 14:31:20 +00004600 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004601}
4602
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004603#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004604/*[clinic input]
4605_ssl.RAND_egd
4606 path: object(converter="PyUnicode_FSConverter")
4607 /
4608
4609Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4610
4611Returns number of bytes read. Raises SSLError if connection to EGD
4612fails or if it does not provide enough data to seed PRNG.
4613[clinic start generated code]*/
4614
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004615static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004616_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4617/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004618{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004619 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004620 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004621 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004622 PyErr_SetString(PySSLErrorObject,
4623 "EGD connection failed or EGD did not return "
4624 "enough data to seed the PRNG");
4625 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004626 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004627 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004628}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004629#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004630
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004631
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004632
4633/*[clinic input]
4634_ssl.get_default_verify_paths
4635
4636Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4637
4638The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4639[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004640
4641static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004642_ssl_get_default_verify_paths_impl(PyObject *module)
4643/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004644{
4645 PyObject *ofile_env = NULL;
4646 PyObject *ofile = NULL;
4647 PyObject *odir_env = NULL;
4648 PyObject *odir = NULL;
4649
Benjamin Petersond113c962015-07-18 10:59:13 -07004650#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004651 const char *tmp = (info); \
4652 target = NULL; \
4653 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4654 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4655 target = PyBytes_FromString(tmp); } \
4656 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004657 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658
Benjamin Petersond113c962015-07-18 10:59:13 -07004659 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4660 CONVERT(X509_get_default_cert_file(), ofile);
4661 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4662 CONVERT(X509_get_default_cert_dir(), odir);
4663#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004664
Christian Heimes200bb1b2013-06-14 15:14:29 +02004665 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004666
4667 error:
4668 Py_XDECREF(ofile_env);
4669 Py_XDECREF(ofile);
4670 Py_XDECREF(odir_env);
4671 Py_XDECREF(odir);
4672 return NULL;
4673}
4674
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004675static PyObject*
4676asn1obj2py(ASN1_OBJECT *obj)
4677{
4678 int nid;
4679 const char *ln, *sn;
4680 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004681 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004682
4683 nid = OBJ_obj2nid(obj);
4684 if (nid == NID_undef) {
4685 PyErr_Format(PyExc_ValueError, "Unknown object");
4686 return NULL;
4687 }
4688 sn = OBJ_nid2sn(nid);
4689 ln = OBJ_nid2ln(nid);
4690 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4691 if (buflen < 0) {
4692 _setSSLError(NULL, 0, __FILE__, __LINE__);
4693 return NULL;
4694 }
4695 if (buflen) {
4696 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4697 } else {
4698 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4699 }
4700}
4701
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004702/*[clinic input]
4703_ssl.txt2obj
4704 txt: str
4705 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004706
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004707Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4708
4709By default objects are looked up by OID. With name=True short and
4710long name are also matched.
4711[clinic start generated code]*/
4712
4713static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004714_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4715/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004716{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004717 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004718 ASN1_OBJECT *obj;
4719
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004720 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4721 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004722 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004723 return NULL;
4724 }
4725 result = asn1obj2py(obj);
4726 ASN1_OBJECT_free(obj);
4727 return result;
4728}
4729
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004730/*[clinic input]
4731_ssl.nid2obj
4732 nid: int
4733 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004734
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004735Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4736[clinic start generated code]*/
4737
4738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004739_ssl_nid2obj_impl(PyObject *module, int nid)
4740/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004741{
4742 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004743 ASN1_OBJECT *obj;
4744
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004745 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004746 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004747 return NULL;
4748 }
4749 obj = OBJ_nid2obj(nid);
4750 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004751 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004752 return NULL;
4753 }
4754 result = asn1obj2py(obj);
4755 ASN1_OBJECT_free(obj);
4756 return result;
4757}
4758
Christian Heimes46bebee2013-06-09 19:03:31 +02004759#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004760
4761static PyObject*
4762certEncodingType(DWORD encodingType)
4763{
4764 static PyObject *x509_asn = NULL;
4765 static PyObject *pkcs_7_asn = NULL;
4766
4767 if (x509_asn == NULL) {
4768 x509_asn = PyUnicode_InternFromString("x509_asn");
4769 if (x509_asn == NULL)
4770 return NULL;
4771 }
4772 if (pkcs_7_asn == NULL) {
4773 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4774 if (pkcs_7_asn == NULL)
4775 return NULL;
4776 }
4777 switch(encodingType) {
4778 case X509_ASN_ENCODING:
4779 Py_INCREF(x509_asn);
4780 return x509_asn;
4781 case PKCS_7_ASN_ENCODING:
4782 Py_INCREF(pkcs_7_asn);
4783 return pkcs_7_asn;
4784 default:
4785 return PyLong_FromLong(encodingType);
4786 }
4787}
4788
4789static PyObject*
4790parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4791{
4792 CERT_ENHKEY_USAGE *usage;
4793 DWORD size, error, i;
4794 PyObject *retval;
4795
4796 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4797 error = GetLastError();
4798 if (error == CRYPT_E_NOT_FOUND) {
4799 Py_RETURN_TRUE;
4800 }
4801 return PyErr_SetFromWindowsErr(error);
4802 }
4803
4804 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4805 if (usage == NULL) {
4806 return PyErr_NoMemory();
4807 }
4808
4809 /* Now get the actual enhanced usage property */
4810 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4811 PyMem_Free(usage);
4812 error = GetLastError();
4813 if (error == CRYPT_E_NOT_FOUND) {
4814 Py_RETURN_TRUE;
4815 }
4816 return PyErr_SetFromWindowsErr(error);
4817 }
4818 retval = PySet_New(NULL);
4819 if (retval == NULL) {
4820 goto error;
4821 }
4822 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4823 if (usage->rgpszUsageIdentifier[i]) {
4824 PyObject *oid;
4825 int err;
4826 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4827 if (oid == NULL) {
4828 Py_CLEAR(retval);
4829 goto error;
4830 }
4831 err = PySet_Add(retval, oid);
4832 Py_DECREF(oid);
4833 if (err == -1) {
4834 Py_CLEAR(retval);
4835 goto error;
4836 }
4837 }
4838 }
4839 error:
4840 PyMem_Free(usage);
4841 return retval;
4842}
4843
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004844/*[clinic input]
4845_ssl.enum_certificates
4846 store_name: str
4847
4848Retrieve certificates from Windows' cert store.
4849
4850store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4851more cert storages, too. The function returns a list of (bytes,
4852encoding_type, trust) tuples. The encoding_type flag can be interpreted
4853with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4854a set of OIDs or the boolean True.
4855[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004856
Christian Heimes46bebee2013-06-09 19:03:31 +02004857static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004858_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4859/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004860{
Christian Heimes46bebee2013-06-09 19:03:31 +02004861 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004862 PCCERT_CONTEXT pCertCtx = NULL;
4863 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004864 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004865
Christian Heimes44109d72013-11-22 01:51:30 +01004866 result = PyList_New(0);
4867 if (result == NULL) {
4868 return NULL;
4869 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004870 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4871 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4872 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004873 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004874 Py_DECREF(result);
4875 return PyErr_SetFromWindowsErr(GetLastError());
4876 }
4877
Christian Heimes44109d72013-11-22 01:51:30 +01004878 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4879 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4880 pCertCtx->cbCertEncoded);
4881 if (!cert) {
4882 Py_CLEAR(result);
4883 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004884 }
Christian Heimes44109d72013-11-22 01:51:30 +01004885 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4886 Py_CLEAR(result);
4887 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004888 }
Christian Heimes44109d72013-11-22 01:51:30 +01004889 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4890 if (keyusage == Py_True) {
4891 Py_DECREF(keyusage);
4892 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004893 }
Christian Heimes44109d72013-11-22 01:51:30 +01004894 if (keyusage == NULL) {
4895 Py_CLEAR(result);
4896 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004897 }
Christian Heimes44109d72013-11-22 01:51:30 +01004898 if ((tup = PyTuple_New(3)) == NULL) {
4899 Py_CLEAR(result);
4900 break;
4901 }
4902 PyTuple_SET_ITEM(tup, 0, cert);
4903 cert = NULL;
4904 PyTuple_SET_ITEM(tup, 1, enc);
4905 enc = NULL;
4906 PyTuple_SET_ITEM(tup, 2, keyusage);
4907 keyusage = NULL;
4908 if (PyList_Append(result, tup) < 0) {
4909 Py_CLEAR(result);
4910 break;
4911 }
4912 Py_CLEAR(tup);
4913 }
4914 if (pCertCtx) {
4915 /* loop ended with an error, need to clean up context manually */
4916 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004917 }
4918
4919 /* In error cases cert, enc and tup may not be NULL */
4920 Py_XDECREF(cert);
4921 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004922 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004923 Py_XDECREF(tup);
4924
4925 if (!CertCloseStore(hStore, 0)) {
4926 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004927 Py_XDECREF(result);
4928 return PyErr_SetFromWindowsErr(GetLastError());
4929 }
4930 return result;
4931}
4932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004933/*[clinic input]
4934_ssl.enum_crls
4935 store_name: str
4936
4937Retrieve CRLs from Windows' cert store.
4938
4939store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4940more cert storages, too. The function returns a list of (bytes,
4941encoding_type) tuples. The encoding_type flag can be interpreted with
4942X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4943[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004944
4945static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004946_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4947/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004948{
Christian Heimes44109d72013-11-22 01:51:30 +01004949 HCERTSTORE hStore = NULL;
4950 PCCRL_CONTEXT pCrlCtx = NULL;
4951 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4952 PyObject *result = NULL;
4953
Christian Heimes44109d72013-11-22 01:51:30 +01004954 result = PyList_New(0);
4955 if (result == NULL) {
4956 return NULL;
4957 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004958 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4959 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4960 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004961 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004962 Py_DECREF(result);
4963 return PyErr_SetFromWindowsErr(GetLastError());
4964 }
Christian Heimes44109d72013-11-22 01:51:30 +01004965
4966 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4967 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4968 pCrlCtx->cbCrlEncoded);
4969 if (!crl) {
4970 Py_CLEAR(result);
4971 break;
4972 }
4973 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4974 Py_CLEAR(result);
4975 break;
4976 }
4977 if ((tup = PyTuple_New(2)) == NULL) {
4978 Py_CLEAR(result);
4979 break;
4980 }
4981 PyTuple_SET_ITEM(tup, 0, crl);
4982 crl = NULL;
4983 PyTuple_SET_ITEM(tup, 1, enc);
4984 enc = NULL;
4985
4986 if (PyList_Append(result, tup) < 0) {
4987 Py_CLEAR(result);
4988 break;
4989 }
4990 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004991 }
Christian Heimes44109d72013-11-22 01:51:30 +01004992 if (pCrlCtx) {
4993 /* loop ended with an error, need to clean up context manually */
4994 CertFreeCRLContext(pCrlCtx);
4995 }
4996
4997 /* In error cases cert, enc and tup may not be NULL */
4998 Py_XDECREF(crl);
4999 Py_XDECREF(enc);
5000 Py_XDECREF(tup);
5001
5002 if (!CertCloseStore(hStore, 0)) {
5003 /* This error case might shadow another exception.*/
5004 Py_XDECREF(result);
5005 return PyErr_SetFromWindowsErr(GetLastError());
5006 }
5007 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005008}
Christian Heimes44109d72013-11-22 01:51:30 +01005009
5010#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005011
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005012/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005013static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005014 _SSL__TEST_DECODE_CERT_METHODDEF
5015 _SSL_RAND_ADD_METHODDEF
5016 _SSL_RAND_BYTES_METHODDEF
5017 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5018 _SSL_RAND_EGD_METHODDEF
5019 _SSL_RAND_STATUS_METHODDEF
5020 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5021 _SSL_ENUM_CERTIFICATES_METHODDEF
5022 _SSL_ENUM_CRLS_METHODDEF
5023 _SSL_TXT2OBJ_METHODDEF
5024 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005025 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005026};
5027
5028
Christian Heimes598894f2016-09-05 23:19:05 +02005029#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030
5031/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005032 * of the Python C thread library
5033 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5034 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035
5036static PyThread_type_lock *_ssl_locks = NULL;
5037
Christian Heimes4d98ca92013-08-19 17:36:29 +02005038#if OPENSSL_VERSION_NUMBER >= 0x10000000
5039/* use new CRYPTO_THREADID API. */
5040static void
5041_ssl_threadid_callback(CRYPTO_THREADID *id)
5042{
5043 CRYPTO_THREADID_set_numeric(id,
5044 (unsigned long)PyThread_get_thread_ident());
5045}
5046#else
5047/* deprecated CRYPTO_set_id_callback() API. */
5048static unsigned long
5049_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005050 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005051}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005052#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005053
Bill Janssen6e027db2007-11-15 22:23:56 +00005054static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005055 (int mode, int n, const char *file, int line) {
5056 /* this function is needed to perform locking on shared data
5057 structures. (Note that OpenSSL uses a number of global data
5058 structures that will be implicitly shared whenever multiple
5059 threads use OpenSSL.) Multi-threaded applications will
5060 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005062 locking_function() must be able to handle up to
5063 CRYPTO_num_locks() different mutex locks. It sets the n-th
5064 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005066 file and line are the file number of the function setting the
5067 lock. They can be useful for debugging.
5068 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005070 if ((_ssl_locks == NULL) ||
5071 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5072 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005074 if (mode & CRYPTO_LOCK) {
5075 PyThread_acquire_lock(_ssl_locks[n], 1);
5076 } else {
5077 PyThread_release_lock(_ssl_locks[n]);
5078 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005079}
5080
5081static int _setup_ssl_threads(void) {
5082
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005083 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005085 if (_ssl_locks == NULL) {
5086 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005087 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
5088 if (_ssl_locks == NULL) {
5089 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005090 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005091 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005092 memset(_ssl_locks, 0,
5093 sizeof(PyThread_type_lock) * _ssl_locks_count);
5094 for (i = 0; i < _ssl_locks_count; i++) {
5095 _ssl_locks[i] = PyThread_allocate_lock();
5096 if (_ssl_locks[i] == NULL) {
5097 unsigned int j;
5098 for (j = 0; j < i; j++) {
5099 PyThread_free_lock(_ssl_locks[j]);
5100 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005101 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005102 return 0;
5103 }
5104 }
5105 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005106#if OPENSSL_VERSION_NUMBER >= 0x10000000
5107 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5108#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005109 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005110#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005111 }
5112 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005113}
5114
Christian Heimes598894f2016-09-05 23:19:05 +02005115#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005117PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005118"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005119for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005120
Martin v. Löwis1a214512008-06-11 05:26:20 +00005121
5122static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005123 PyModuleDef_HEAD_INIT,
5124 "_ssl",
5125 module_doc,
5126 -1,
5127 PySSL_methods,
5128 NULL,
5129 NULL,
5130 NULL,
5131 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005132};
5133
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005134
5135static void
5136parse_openssl_version(unsigned long libver,
5137 unsigned int *major, unsigned int *minor,
5138 unsigned int *fix, unsigned int *patch,
5139 unsigned int *status)
5140{
5141 *status = libver & 0xF;
5142 libver >>= 4;
5143 *patch = libver & 0xFF;
5144 libver >>= 8;
5145 *fix = libver & 0xFF;
5146 libver >>= 8;
5147 *minor = libver & 0xFF;
5148 libver >>= 8;
5149 *major = libver & 0xFF;
5150}
5151
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005152PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005153PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005154{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005155 PyObject *m, *d, *r;
5156 unsigned long libver;
5157 unsigned int major, minor, fix, patch, status;
5158 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005159 struct py_ssl_error_code *errcode;
5160 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005161
Antoine Pitrou152efa22010-05-16 18:19:27 +00005162 if (PyType_Ready(&PySSLContext_Type) < 0)
5163 return NULL;
5164 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005165 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005166 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5167 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005168 if (PyType_Ready(&PySSLSession_Type) < 0)
5169 return NULL;
5170
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005172 m = PyModule_Create(&_sslmodule);
5173 if (m == NULL)
5174 return NULL;
5175 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005177 /* Load _socket module and its C API */
5178 socket_api = PySocketModule_ImportModuleAndAPI();
5179 if (!socket_api)
5180 return NULL;
5181 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005183 /* Init OpenSSL */
5184 SSL_load_error_strings();
5185 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005186#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005187#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005188 /* note that this will start threading if not already started */
5189 if (!_setup_ssl_threads()) {
5190 return NULL;
5191 }
Christian Heimes598894f2016-09-05 23:19:05 +02005192#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5193 /* OpenSSL 1.1.0 builtin thread support is enabled */
5194 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005195#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005196#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005197 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005199 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005200 sslerror_type_slots[0].pfunc = PyExc_OSError;
5201 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005202 if (PySSLErrorObject == NULL)
5203 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005204
Antoine Pitrou41032a62011-10-27 23:56:55 +02005205 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5206 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5207 PySSLErrorObject, NULL);
5208 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5209 "ssl.SSLWantReadError", SSLWantReadError_doc,
5210 PySSLErrorObject, NULL);
5211 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5212 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5213 PySSLErrorObject, NULL);
5214 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5215 "ssl.SSLSyscallError", SSLSyscallError_doc,
5216 PySSLErrorObject, NULL);
5217 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5218 "ssl.SSLEOFError", SSLEOFError_doc,
5219 PySSLErrorObject, NULL);
5220 if (PySSLZeroReturnErrorObject == NULL
5221 || PySSLWantReadErrorObject == NULL
5222 || PySSLWantWriteErrorObject == NULL
5223 || PySSLSyscallErrorObject == NULL
5224 || PySSLEOFErrorObject == NULL)
5225 return NULL;
5226 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5227 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5228 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5229 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5230 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5231 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005232 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005233 if (PyDict_SetItemString(d, "_SSLContext",
5234 (PyObject *)&PySSLContext_Type) != 0)
5235 return NULL;
5236 if (PyDict_SetItemString(d, "_SSLSocket",
5237 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005238 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005239 if (PyDict_SetItemString(d, "MemoryBIO",
5240 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5241 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005242 if (PyDict_SetItemString(d, "SSLSession",
5243 (PyObject *)&PySSLSession_Type) != 0)
5244 return NULL;
5245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005246 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5247 PY_SSL_ERROR_ZERO_RETURN);
5248 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5249 PY_SSL_ERROR_WANT_READ);
5250 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5251 PY_SSL_ERROR_WANT_WRITE);
5252 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5253 PY_SSL_ERROR_WANT_X509_LOOKUP);
5254 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5255 PY_SSL_ERROR_SYSCALL);
5256 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5257 PY_SSL_ERROR_SSL);
5258 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5259 PY_SSL_ERROR_WANT_CONNECT);
5260 /* non ssl.h errorcodes */
5261 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5262 PY_SSL_ERROR_EOF);
5263 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5264 PY_SSL_ERROR_INVALID_ERROR_CODE);
5265 /* cert requirements */
5266 PyModule_AddIntConstant(m, "CERT_NONE",
5267 PY_SSL_CERT_NONE);
5268 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5269 PY_SSL_CERT_OPTIONAL);
5270 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5271 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005272 /* CRL verification for verification_flags */
5273 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5274 0);
5275 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5276 X509_V_FLAG_CRL_CHECK);
5277 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5278 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5279 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5280 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005281#ifdef X509_V_FLAG_TRUSTED_FIRST
5282 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5283 X509_V_FLAG_TRUSTED_FIRST);
5284#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005285
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005286 /* Alert Descriptions from ssl.h */
5287 /* note RESERVED constants no longer intended for use have been removed */
5288 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5289
5290#define ADD_AD_CONSTANT(s) \
5291 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5292 SSL_AD_##s)
5293
5294 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5295 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5296 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5297 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5298 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5299 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5300 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5301 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5302 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5303 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5304 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5305 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5306 ADD_AD_CONSTANT(UNKNOWN_CA);
5307 ADD_AD_CONSTANT(ACCESS_DENIED);
5308 ADD_AD_CONSTANT(DECODE_ERROR);
5309 ADD_AD_CONSTANT(DECRYPT_ERROR);
5310 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5311 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5312 ADD_AD_CONSTANT(INTERNAL_ERROR);
5313 ADD_AD_CONSTANT(USER_CANCELLED);
5314 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005315 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005316#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5317 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5318#endif
5319#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5320 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5321#endif
5322#ifdef SSL_AD_UNRECOGNIZED_NAME
5323 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5324#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005325#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5326 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5327#endif
5328#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5329 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5330#endif
5331#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5332 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5333#endif
5334
5335#undef ADD_AD_CONSTANT
5336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005337 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005338#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005339 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5340 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005341#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005342#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005343 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5344 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005345#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005346 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005347 PY_SSL_VERSION_TLS);
5348 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5349 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005350 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5351 PY_SSL_VERSION_TLS_CLIENT);
5352 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5353 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005354 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5355 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005356#if HAVE_TLSv1_2
5357 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5358 PY_SSL_VERSION_TLS1_1);
5359 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5360 PY_SSL_VERSION_TLS1_2);
5361#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005362
Antoine Pitroub5218772010-05-21 09:56:06 +00005363 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005364 PyModule_AddIntConstant(m, "OP_ALL",
5365 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005366 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5367 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5368 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005369#if HAVE_TLSv1_2
5370 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5371 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5372#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005373 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5374 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005375 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005376 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005377#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005378 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005379#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005380#ifdef SSL_OP_NO_COMPRESSION
5381 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5382 SSL_OP_NO_COMPRESSION);
5383#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005384
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005385#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005386 r = Py_True;
5387#else
5388 r = Py_False;
5389#endif
5390 Py_INCREF(r);
5391 PyModule_AddObject(m, "HAS_SNI", r);
5392
Antoine Pitroud6494802011-07-21 01:11:30 +02005393 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005394 Py_INCREF(r);
5395 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5396
Antoine Pitrou501da612011-12-21 09:27:41 +01005397#ifdef OPENSSL_NO_ECDH
5398 r = Py_False;
5399#else
5400 r = Py_True;
5401#endif
5402 Py_INCREF(r);
5403 PyModule_AddObject(m, "HAS_ECDH", r);
5404
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005405#ifdef OPENSSL_NPN_NEGOTIATED
5406 r = Py_True;
5407#else
5408 r = Py_False;
5409#endif
5410 Py_INCREF(r);
5411 PyModule_AddObject(m, "HAS_NPN", r);
5412
Benjamin Petersoncca27322015-01-23 16:35:37 -05005413#ifdef HAVE_ALPN
5414 r = Py_True;
5415#else
5416 r = Py_False;
5417#endif
5418 Py_INCREF(r);
5419 PyModule_AddObject(m, "HAS_ALPN", r);
5420
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005421 /* Mappings for error codes */
5422 err_codes_to_names = PyDict_New();
5423 err_names_to_codes = PyDict_New();
5424 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5425 return NULL;
5426 errcode = error_codes;
5427 while (errcode->mnemonic != NULL) {
5428 PyObject *mnemo, *key;
5429 mnemo = PyUnicode_FromString(errcode->mnemonic);
5430 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5431 if (mnemo == NULL || key == NULL)
5432 return NULL;
5433 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5434 return NULL;
5435 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5436 return NULL;
5437 Py_DECREF(key);
5438 Py_DECREF(mnemo);
5439 errcode++;
5440 }
5441 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5442 return NULL;
5443 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5444 return NULL;
5445
5446 lib_codes_to_names = PyDict_New();
5447 if (lib_codes_to_names == NULL)
5448 return NULL;
5449 libcode = library_codes;
5450 while (libcode->library != NULL) {
5451 PyObject *mnemo, *key;
5452 key = PyLong_FromLong(libcode->code);
5453 mnemo = PyUnicode_FromString(libcode->library);
5454 if (key == NULL || mnemo == NULL)
5455 return NULL;
5456 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5457 return NULL;
5458 Py_DECREF(key);
5459 Py_DECREF(mnemo);
5460 libcode++;
5461 }
5462 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5463 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 /* OpenSSL version */
5466 /* SSLeay() gives us the version of the library linked against,
5467 which could be different from the headers version.
5468 */
5469 libver = SSLeay();
5470 r = PyLong_FromUnsignedLong(libver);
5471 if (r == NULL)
5472 return NULL;
5473 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5474 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005475 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005476 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5477 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5478 return NULL;
5479 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5480 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5481 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005482
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005483 libver = OPENSSL_VERSION_NUMBER;
5484 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5485 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5486 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5487 return NULL;
5488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005489 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005490}