blob: 273241654d9ac49c3cfb74e694102d44fd1f2646 [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
58/* Include OpenSSL header files */
59#include "openssl/rsa.h"
60#include "openssl/crypto.h"
61#include "openssl/x509.h"
62#include "openssl/x509v3.h"
63#include "openssl/pem.h"
64#include "openssl/ssl.h"
65#include "openssl/err.h"
66#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020067#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010068
69/* SSL error object */
70static PyObject *PySSLErrorObject;
71static PyObject *PySSLZeroReturnErrorObject;
72static PyObject *PySSLWantReadErrorObject;
73static PyObject *PySSLWantWriteErrorObject;
74static PyObject *PySSLSyscallErrorObject;
75static PyObject *PySSLEOFErrorObject;
76
77/* Error mappings */
78static PyObject *err_codes_to_names;
79static PyObject *err_names_to_codes;
80static PyObject *lib_codes_to_names;
81
82struct py_ssl_error_code {
83 const char *mnemonic;
84 int library, reason;
85};
86struct py_ssl_library_code {
87 const char *library;
88 int code;
89};
90
91/* Include generated data (error codes) */
92#include "_ssl_data.h"
93
94/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
95 http://www.openssl.org/news/changelog.html
96 */
97#if OPENSSL_VERSION_NUMBER >= 0x10001000L
98# define HAVE_TLSv1_2 1
99#else
100# define HAVE_TLSv1_2 0
101#endif
102
Christian Heimes470fba12013-11-28 15:12:15 +0100103/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100104 * This includes the SSL_set_SSL_CTX() function.
105 */
106#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
107# define HAVE_SNI 1
108#else
109# define HAVE_SNI 0
110#endif
111
Benjamin Petersond3308222015-09-27 00:09:02 -0700112#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500113# define HAVE_ALPN
114#endif
115
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000116enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000117 /* these mirror ssl.h */
118 PY_SSL_ERROR_NONE,
119 PY_SSL_ERROR_SSL,
120 PY_SSL_ERROR_WANT_READ,
121 PY_SSL_ERROR_WANT_WRITE,
122 PY_SSL_ERROR_WANT_X509_LOOKUP,
123 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
124 PY_SSL_ERROR_ZERO_RETURN,
125 PY_SSL_ERROR_WANT_CONNECT,
126 /* start of non ssl.h errorcodes */
127 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
128 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
129 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000130};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Thomas Woutersed03b412007-08-28 21:37:11 +0000132enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000133 PY_SSL_CLIENT,
134 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000135};
136
137enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000138 PY_SSL_CERT_NONE,
139 PY_SSL_CERT_OPTIONAL,
140 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000141};
142
143enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200145 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000146 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147#if HAVE_TLSv1_2
148 PY_SSL_VERSION_TLS1,
149 PY_SSL_VERSION_TLS1_1,
150 PY_SSL_VERSION_TLS1_2
151#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000152 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100154};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200155
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000156#ifdef WITH_THREAD
157
158/* serves as a flag to see whether we've initialized the SSL thread support. */
159/* 0 means no, greater than 0 means yes */
160
161static unsigned int _ssl_locks_count = 0;
162
163#endif /* def WITH_THREAD */
164
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000165/* SSL socket object */
166
167#define X509_NAME_MAXLEN 256
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100182
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000183typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000184 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000185 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100186#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500187 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100188 int npn_protocols_len;
189#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500190#ifdef HAVE_ALPN
191 unsigned char *alpn_protocols;
192 int alpn_protocols_len;
193#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100194#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200195 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100196#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100197 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000198} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000199
Antoine Pitrou152efa22010-05-16 18:19:27 +0000200typedef struct {
201 PyObject_HEAD
202 PyObject *Socket; /* weakref to socket on which we're layered */
203 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100204 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000205 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200206 char shutdown_seen_zero;
207 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200208 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200209 PyObject *owner; /* Python level "owner" passed to servername callback */
210 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000212
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200213typedef struct {
214 PyObject_HEAD
215 BIO *bio;
216 int eof_written;
217} PySSLMemoryBIO;
218
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219static PyTypeObject PySSLContext_Type;
220static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200221static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300223/*[clinic input]
224module _ssl
225class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
226class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
227class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
228[clinic start generated code]*/
229/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
230
231#include "clinic/_ssl.c.h"
232
Victor Stinner14690702015-04-06 22:46:13 +0200233static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
236#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200237#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000239typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000240 SOCKET_IS_NONBLOCKING,
241 SOCKET_IS_BLOCKING,
242 SOCKET_HAS_TIMED_OUT,
243 SOCKET_HAS_BEEN_CLOSED,
244 SOCKET_TOO_LARGE_FOR_SELECT,
245 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000246} timeout_state;
247
Thomas Woutersed03b412007-08-28 21:37:11 +0000248/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000249#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200250#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000251
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200252/* Get the socket from a PySSLSocket, if it has one */
253#define GET_SOCKET(obj) ((obj)->Socket ? \
254 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200255
Victor Stinner14690702015-04-06 22:46:13 +0200256/* If sock is NULL, use a timeout of 0 second */
257#define GET_SOCKET_TIMEOUT(sock) \
258 ((sock != NULL) ? (sock)->sock_timeout : 0)
259
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200260/*
261 * SSL errors.
262 */
263
264PyDoc_STRVAR(SSLError_doc,
265"An error occurred in the SSL implementation.");
266
267PyDoc_STRVAR(SSLZeroReturnError_doc,
268"SSL/TLS session closed cleanly.");
269
270PyDoc_STRVAR(SSLWantReadError_doc,
271"Non-blocking SSL socket needs to read more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLWantWriteError_doc,
275"Non-blocking SSL socket needs to write more data\n"
276"before the requested operation can be completed.");
277
278PyDoc_STRVAR(SSLSyscallError_doc,
279"System error when attempting SSL operation.");
280
281PyDoc_STRVAR(SSLEOFError_doc,
282"SSL/TLS connection terminated abruptly.");
283
284static PyObject *
285SSLError_str(PyOSErrorObject *self)
286{
287 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
288 Py_INCREF(self->strerror);
289 return self->strerror;
290 }
291 else
292 return PyObject_Str(self->args);
293}
294
295static PyType_Slot sslerror_type_slots[] = {
296 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
297 {Py_tp_doc, SSLError_doc},
298 {Py_tp_str, SSLError_str},
299 {0, 0},
300};
301
302static PyType_Spec sslerror_type_spec = {
303 "ssl.SSLError",
304 sizeof(PyOSErrorObject),
305 0,
306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
307 sslerror_type_slots
308};
309
310static void
311fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
312 int lineno, unsigned long errcode)
313{
314 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
315 PyObject *init_value, *msg, *key;
316 _Py_IDENTIFIER(reason);
317 _Py_IDENTIFIER(library);
318
319 if (errcode != 0) {
320 int lib, reason;
321
322 lib = ERR_GET_LIB(errcode);
323 reason = ERR_GET_REASON(errcode);
324 key = Py_BuildValue("ii", lib, reason);
325 if (key == NULL)
326 goto fail;
327 reason_obj = PyDict_GetItem(err_codes_to_names, key);
328 Py_DECREF(key);
329 if (reason_obj == NULL) {
330 /* XXX if reason < 100, it might reflect a library number (!!) */
331 PyErr_Clear();
332 }
333 key = PyLong_FromLong(lib);
334 if (key == NULL)
335 goto fail;
336 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
337 Py_DECREF(key);
338 if (lib_obj == NULL) {
339 PyErr_Clear();
340 }
341 if (errstr == NULL)
342 errstr = ERR_reason_error_string(errcode);
343 }
344 if (errstr == NULL)
345 errstr = "unknown error";
346
347 if (reason_obj && lib_obj)
348 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
349 lib_obj, reason_obj, errstr, lineno);
350 else if (lib_obj)
351 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
352 lib_obj, errstr, lineno);
353 else
354 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355 if (msg == NULL)
356 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100357
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200358 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100359 if (init_value == NULL)
360 goto fail;
361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 err_value = PyObject_CallObject(type, init_value);
363 Py_DECREF(init_value);
364 if (err_value == NULL)
365 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100366
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 if (reason_obj == NULL)
368 reason_obj = Py_None;
369 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
370 goto fail;
371 if (lib_obj == NULL)
372 lib_obj = Py_None;
373 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
374 goto fail;
375 PyErr_SetObject(type, err_value);
376fail:
377 Py_XDECREF(err_value);
378}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
380static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200383 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 int err;
386 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200390 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 if (obj->ssl != NULL) {
393 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 switch (err) {
396 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 errstr = "TLS/SSL connection has been closed (EOF)";
398 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 p = PY_SSL_ERROR_ZERO_RETURN;
400 break;
401 case SSL_ERROR_WANT_READ:
402 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200403 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 p = PY_SSL_ERROR_WANT_READ;
405 break;
406 case SSL_ERROR_WANT_WRITE:
407 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200408 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 errstr = "The operation did not complete (write)";
410 break;
411 case SSL_ERROR_WANT_X509_LOOKUP:
412 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000413 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 break;
415 case SSL_ERROR_WANT_CONNECT:
416 p = PY_SSL_ERROR_WANT_CONNECT;
417 errstr = "The operation did not complete (connect)";
418 break;
419 case SSL_ERROR_SYSCALL:
420 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200422 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000423 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000424 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200425 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000426 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200427 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000429 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000430 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200431 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000432 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200436 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000437 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 }
439 } else {
440 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 }
442 break;
443 }
444 case SSL_ERROR_SSL:
445 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447 if (e == 0)
448 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000449 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 break;
451 }
452 default:
453 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
454 errstr = "Invalid error code";
455 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000458 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000460}
461
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462static PyObject *
463_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
464
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467 else
468 errcode = 0;
469 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000470 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472}
473
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474/*
475 * SSL objects
476 */
477
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000480 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200481 char *server_hostname,
482 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100485 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200486 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200487 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 if (self == NULL)
491 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 self->peer_cert = NULL;
494 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100496 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200497 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200498 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200499 self->owner = NULL;
500 if (server_hostname != NULL) {
501 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
502 "idna", "strict");
503 if (hostname == NULL) {
504 Py_DECREF(self);
505 return NULL;
506 }
507 self->server_hostname = hostname;
508 } else
509 self->server_hostname = NULL;
510
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100511 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 /* Make sure the SSL error state is initialized */
514 (void) ERR_get_state();
515 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000518 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000519 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200520 SSL_set_app_data(self->ssl, self);
521 if (sock) {
522 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
523 } else {
524 /* BIOs are reference counted and SSL_set_bio borrows our reference.
525 * To prevent a double free in memory_bio_dealloc() we need to take an
526 * extra reference here. */
527 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
528 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
529 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
530 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200531 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000532#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200533 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000534#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200535 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000536
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100537#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000538 if (server_hostname != NULL)
539 SSL_set_tlsext_host_name(self->ssl, server_hostname);
540#endif
541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 /* If the socket is in non-blocking mode or timeout mode, set the BIO
543 * to non-blocking mode (blocking is the default)
544 */
Victor Stinnere2452312015-03-28 03:00:46 +0100545 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
547 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
548 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 PySSL_BEGIN_ALLOW_THREADS
551 if (socket_type == PY_SSL_CLIENT)
552 SSL_set_connect_state(self->ssl);
553 else
554 SSL_set_accept_state(self->ssl);
555 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000556
Antoine Pitroud6494802011-07-21 01:11:30 +0200557 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200558 if (sock != NULL) {
559 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
560 if (self->Socket == NULL) {
561 Py_DECREF(self);
562 Py_XDECREF(self->server_hostname);
563 return NULL;
564 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100565 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000567}
568
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569/* SSL object methods */
570
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300571/*[clinic input]
572_ssl._SSLSocket.do_handshake
573[clinic start generated code]*/
574
575static PyObject *
576_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
577/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000578{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 int ret;
580 int err;
581 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200582 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200583 _PyTime_t timeout, deadline = 0;
584 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000585
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200586 if (sock) {
587 if (((PyObject*)sock) == Py_None) {
588 _setSSLError("Underlying socket connection gone",
589 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
590 return NULL;
591 }
592 Py_INCREF(sock);
593
594 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100595 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
597 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000599
Victor Stinner14690702015-04-06 22:46:13 +0200600 timeout = GET_SOCKET_TIMEOUT(sock);
601 has_timeout = (timeout > 0);
602 if (has_timeout)
603 deadline = _PyTime_GetMonotonicClock() + timeout;
604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 /* Actually negotiate SSL connection */
606 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000608 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 ret = SSL_do_handshake(self->ssl);
610 err = SSL_get_error(self->ssl, ret);
611 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200612
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000613 if (PyErr_CheckSignals())
614 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200615
Victor Stinner14690702015-04-06 22:46:13 +0200616 if (has_timeout)
617 timeout = deadline - _PyTime_GetMonotonicClock();
618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200620 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200622 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 } else {
624 sockstate = SOCKET_OPERATION_OK;
625 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000628 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000629 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000630 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
632 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000634 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
636 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000638 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
640 break;
641 }
642 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200643 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 if (ret < 1)
645 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 if (self->peer_cert)
648 X509_free (self->peer_cert);
649 PySSL_BEGIN_ALLOW_THREADS
650 self->peer_cert = SSL_get_peer_certificate(self->ssl);
651 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200652 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653
654 Py_INCREF(Py_None);
655 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000656
657error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200658 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000659 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000660}
661
Thomas Woutersed03b412007-08-28 21:37:11 +0000662static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 char namebuf[X509_NAME_MAXLEN];
666 int buflen;
667 PyObject *name_obj;
668 PyObject *value_obj;
669 PyObject *attr;
670 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
673 if (buflen < 0) {
674 _setSSLError(NULL, 0, __FILE__, __LINE__);
675 goto fail;
676 }
677 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
678 if (name_obj == NULL)
679 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
682 if (buflen < 0) {
683 _setSSLError(NULL, 0, __FILE__, __LINE__);
684 Py_DECREF(name_obj);
685 goto fail;
686 }
687 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000688 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 OPENSSL_free(valuebuf);
690 if (value_obj == NULL) {
691 Py_DECREF(name_obj);
692 goto fail;
693 }
694 attr = PyTuple_New(2);
695 if (attr == NULL) {
696 Py_DECREF(name_obj);
697 Py_DECREF(value_obj);
698 goto fail;
699 }
700 PyTuple_SET_ITEM(attr, 0, name_obj);
701 PyTuple_SET_ITEM(attr, 1, value_obj);
702 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000703
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000706}
707
708static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000710{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
712 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
713 PyObject *rdnt;
714 PyObject *attr = NULL; /* tuple to hold an attribute */
715 int entry_count = X509_NAME_entry_count(xname);
716 X509_NAME_ENTRY *entry;
717 ASN1_OBJECT *name;
718 ASN1_STRING *value;
719 int index_counter;
720 int rdn_level = -1;
721 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 dn = PyList_New(0);
724 if (dn == NULL)
725 return NULL;
726 /* now create another tuple to hold the top-level RDN */
727 rdn = PyList_New(0);
728 if (rdn == NULL)
729 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 for (index_counter = 0;
732 index_counter < entry_count;
733 index_counter++)
734 {
735 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 /* check to see if we've gotten to a new RDN */
738 if (rdn_level >= 0) {
739 if (rdn_level != entry->set) {
740 /* yes, new RDN */
741 /* add old RDN to DN */
742 rdnt = PyList_AsTuple(rdn);
743 Py_DECREF(rdn);
744 if (rdnt == NULL)
745 goto fail0;
746 retcode = PyList_Append(dn, rdnt);
747 Py_DECREF(rdnt);
748 if (retcode < 0)
749 goto fail0;
750 /* create new RDN */
751 rdn = PyList_New(0);
752 if (rdn == NULL)
753 goto fail0;
754 }
755 }
756 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 /* now add this attribute to the current RDN */
759 name = X509_NAME_ENTRY_get_object(entry);
760 value = X509_NAME_ENTRY_get_data(entry);
761 attr = _create_tuple_for_attribute(name, value);
762 /*
763 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
764 entry->set,
765 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
766 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
767 */
768 if (attr == NULL)
769 goto fail1;
770 retcode = PyList_Append(rdn, attr);
771 Py_DECREF(attr);
772 if (retcode < 0)
773 goto fail1;
774 }
775 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100776 if (rdn != NULL) {
777 if (PyList_GET_SIZE(rdn) > 0) {
778 rdnt = PyList_AsTuple(rdn);
779 Py_DECREF(rdn);
780 if (rdnt == NULL)
781 goto fail0;
782 retcode = PyList_Append(dn, rdnt);
783 Py_DECREF(rdnt);
784 if (retcode < 0)
785 goto fail0;
786 }
787 else {
788 Py_DECREF(rdn);
789 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 /* convert list to tuple */
793 rdnt = PyList_AsTuple(dn);
794 Py_DECREF(dn);
795 if (rdnt == NULL)
796 return NULL;
797 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
799 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801
802 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 Py_XDECREF(dn);
804 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805}
806
807static PyObject *
808_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 /* this code follows the procedure outlined in
811 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
812 function to extract the STACK_OF(GENERAL_NAME),
813 then iterates through the stack to add the
814 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 int i, j;
817 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200818 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 X509_EXTENSION *ext = NULL;
820 GENERAL_NAMES *names = NULL;
821 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000822 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 BIO *biobuf = NULL;
824 char buf[2048];
825 char *vptr;
826 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 if (certificate == NULL)
830 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* get a memory buffer */
833 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200835 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 while ((i = X509_get_ext_by_NID(
837 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 if (peer_alt_names == Py_None) {
840 peer_alt_names = PyList_New(0);
841 if (peer_alt_names == NULL)
842 goto fail;
843 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 /* now decode the altName */
846 ext = X509_get_ext(certificate, i);
847 if(!(method = X509V3_EXT_get(ext))) {
848 PyErr_SetString
849 (PySSLErrorObject,
850 ERRSTR("No method for internalizing subjectAltName!"));
851 goto fail;
852 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 p = ext->value->data;
855 if (method->it)
856 names = (GENERAL_NAMES*)
857 (ASN1_item_d2i(NULL,
858 &p,
859 ext->value->length,
860 ASN1_ITEM_ptr(method->it)));
861 else
862 names = (GENERAL_NAMES*)
863 (method->d2i(NULL,
864 &p,
865 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200869 int gntype;
870 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200873 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200874 switch (gntype) {
875 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 /* we special-case DirName as a tuple of
877 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 t = PyTuple_New(2);
880 if (t == NULL) {
881 goto fail;
882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 v = PyUnicode_FromString("DirName");
885 if (v == NULL) {
886 Py_DECREF(t);
887 goto fail;
888 }
889 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 v = _create_tuple_for_X509_NAME (name->d.dirn);
892 if (v == NULL) {
893 Py_DECREF(t);
894 goto fail;
895 }
896 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200897 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000898
Christian Heimes824f7f32013-08-17 00:54:47 +0200899 case GEN_EMAIL:
900 case GEN_DNS:
901 case GEN_URI:
902 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
903 correctly, CVE-2013-4238 */
904 t = PyTuple_New(2);
905 if (t == NULL)
906 goto fail;
907 switch (gntype) {
908 case GEN_EMAIL:
909 v = PyUnicode_FromString("email");
910 as = name->d.rfc822Name;
911 break;
912 case GEN_DNS:
913 v = PyUnicode_FromString("DNS");
914 as = name->d.dNSName;
915 break;
916 case GEN_URI:
917 v = PyUnicode_FromString("URI");
918 as = name->d.uniformResourceIdentifier;
919 break;
920 }
921 if (v == NULL) {
922 Py_DECREF(t);
923 goto fail;
924 }
925 PyTuple_SET_ITEM(t, 0, v);
926 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
927 ASN1_STRING_length(as));
928 if (v == NULL) {
929 Py_DECREF(t);
930 goto fail;
931 }
932 PyTuple_SET_ITEM(t, 1, v);
933 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Christian Heimes824f7f32013-08-17 00:54:47 +0200935 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 switch (gntype) {
938 /* check for new general name type */
939 case GEN_OTHERNAME:
940 case GEN_X400:
941 case GEN_EDIPARTY:
942 case GEN_IPADD:
943 case GEN_RID:
944 break;
945 default:
946 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
947 "Unknown general name type %d",
948 gntype) == -1) {
949 goto fail;
950 }
951 break;
952 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 (void) BIO_reset(biobuf);
954 GENERAL_NAME_print(biobuf, name);
955 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
956 if (len < 0) {
957 _setSSLError(NULL, 0, __FILE__, __LINE__);
958 goto fail;
959 }
960 vptr = strchr(buf, ':');
961 if (vptr == NULL)
962 goto fail;
963 t = PyTuple_New(2);
964 if (t == NULL)
965 goto fail;
966 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
967 if (v == NULL) {
968 Py_DECREF(t);
969 goto fail;
970 }
971 PyTuple_SET_ITEM(t, 0, v);
972 v = PyUnicode_FromStringAndSize((vptr + 1),
973 (len - (vptr - buf + 1)));
974 if (v == NULL) {
975 Py_DECREF(t);
976 goto fail;
977 }
978 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200979 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 if (PyList_Append(peer_alt_names, t) < 0) {
985 Py_DECREF(t);
986 goto fail;
987 }
988 Py_DECREF(t);
989 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100990 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 }
992 BIO_free(biobuf);
993 if (peer_alt_names != Py_None) {
994 v = PyList_AsTuple(peer_alt_names);
995 Py_DECREF(peer_alt_names);
996 return v;
997 } else {
998 return peer_alt_names;
999 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001000
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001
1002 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 if (biobuf != NULL)
1004 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 if (peer_alt_names != Py_None) {
1007 Py_XDECREF(peer_alt_names);
1008 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011}
1012
1013static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001014_get_aia_uri(X509 *certificate, int nid) {
1015 PyObject *lst = NULL, *ostr = NULL;
1016 int i, result;
1017 AUTHORITY_INFO_ACCESS *info;
1018
1019 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001020 if (info == NULL)
1021 return Py_None;
1022 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1023 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001024 return Py_None;
1025 }
1026
1027 if ((lst = PyList_New(0)) == NULL) {
1028 goto fail;
1029 }
1030
1031 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1032 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1033 ASN1_IA5STRING *uri;
1034
1035 if ((OBJ_obj2nid(ad->method) != nid) ||
1036 (ad->location->type != GEN_URI)) {
1037 continue;
1038 }
1039 uri = ad->location->d.uniformResourceIdentifier;
1040 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1041 uri->length);
1042 if (ostr == NULL) {
1043 goto fail;
1044 }
1045 result = PyList_Append(lst, ostr);
1046 Py_DECREF(ostr);
1047 if (result < 0) {
1048 goto fail;
1049 }
1050 }
1051 AUTHORITY_INFO_ACCESS_free(info);
1052
1053 /* convert to tuple or None */
1054 if (PyList_Size(lst) == 0) {
1055 Py_DECREF(lst);
1056 return Py_None;
1057 } else {
1058 PyObject *tup;
1059 tup = PyList_AsTuple(lst);
1060 Py_DECREF(lst);
1061 return tup;
1062 }
1063
1064 fail:
1065 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001066 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001067 return NULL;
1068}
1069
1070static PyObject *
1071_get_crl_dp(X509 *certificate) {
1072 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001073 int i, j;
1074 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001075
Christian Heimes949ec142013-11-21 16:26:51 +01001076#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001077 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001078#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001079 /* Calls x509v3_cache_extensions and sets up crldp */
1080 X509_check_ca(certificate);
1081 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001082#endif
1083
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001084 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001085 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001086
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001087 lst = PyList_New(0);
1088 if (lst == NULL)
1089 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001090
1091 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1092 DIST_POINT *dp;
1093 STACK_OF(GENERAL_NAME) *gns;
1094
1095 dp = sk_DIST_POINT_value(dps, i);
1096 gns = dp->distpoint->name.fullname;
1097
1098 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1099 GENERAL_NAME *gn;
1100 ASN1_IA5STRING *uri;
1101 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001102 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001103
1104 gn = sk_GENERAL_NAME_value(gns, j);
1105 if (gn->type != GEN_URI) {
1106 continue;
1107 }
1108 uri = gn->d.uniformResourceIdentifier;
1109 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1110 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001111 if (ouri == NULL)
1112 goto done;
1113
1114 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001115 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001116 if (err < 0)
1117 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001118 }
1119 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001120
1121 /* Convert to tuple. */
1122 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1123
1124 done:
1125 Py_XDECREF(lst);
1126#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001127 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001128#endif
1129 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001130}
1131
1132static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001133_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 PyObject *retval = NULL;
1136 BIO *biobuf = NULL;
1137 PyObject *peer;
1138 PyObject *peer_alt_names = NULL;
1139 PyObject *issuer;
1140 PyObject *version;
1141 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001142 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 ASN1_INTEGER *serialNumber;
1144 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001145 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 ASN1_TIME *notBefore, *notAfter;
1147 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 retval = PyDict_New();
1150 if (retval == NULL)
1151 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 peer = _create_tuple_for_X509_NAME(
1154 X509_get_subject_name(certificate));
1155 if (peer == NULL)
1156 goto fail0;
1157 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1158 Py_DECREF(peer);
1159 goto fail0;
1160 }
1161 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001162
Antoine Pitroufb046912010-11-09 20:21:19 +00001163 issuer = _create_tuple_for_X509_NAME(
1164 X509_get_issuer_name(certificate));
1165 if (issuer == NULL)
1166 goto fail0;
1167 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001169 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001171 Py_DECREF(issuer);
1172
1173 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001174 if (version == NULL)
1175 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001176 if (PyDict_SetItemString(retval, "version", version) < 0) {
1177 Py_DECREF(version);
1178 goto fail0;
1179 }
1180 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 /* get a memory buffer */
1183 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001184
Antoine Pitroufb046912010-11-09 20:21:19 +00001185 (void) BIO_reset(biobuf);
1186 serialNumber = X509_get_serialNumber(certificate);
1187 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1188 i2a_ASN1_INTEGER(biobuf, serialNumber);
1189 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1190 if (len < 0) {
1191 _setSSLError(NULL, 0, __FILE__, __LINE__);
1192 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001194 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1195 if (sn_obj == NULL)
1196 goto fail1;
1197 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1198 Py_DECREF(sn_obj);
1199 goto fail1;
1200 }
1201 Py_DECREF(sn_obj);
1202
1203 (void) BIO_reset(biobuf);
1204 notBefore = X509_get_notBefore(certificate);
1205 ASN1_TIME_print(biobuf, notBefore);
1206 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1207 if (len < 0) {
1208 _setSSLError(NULL, 0, __FILE__, __LINE__);
1209 goto fail1;
1210 }
1211 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1212 if (pnotBefore == NULL)
1213 goto fail1;
1214 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1215 Py_DECREF(pnotBefore);
1216 goto fail1;
1217 }
1218 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 (void) BIO_reset(biobuf);
1221 notAfter = X509_get_notAfter(certificate);
1222 ASN1_TIME_print(biobuf, notAfter);
1223 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1224 if (len < 0) {
1225 _setSSLError(NULL, 0, __FILE__, __LINE__);
1226 goto fail1;
1227 }
1228 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1229 if (pnotAfter == NULL)
1230 goto fail1;
1231 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1232 Py_DECREF(pnotAfter);
1233 goto fail1;
1234 }
1235 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 peer_alt_names = _get_peer_alt_names(certificate);
1240 if (peer_alt_names == NULL)
1241 goto fail1;
1242 else if (peer_alt_names != Py_None) {
1243 if (PyDict_SetItemString(retval, "subjectAltName",
1244 peer_alt_names) < 0) {
1245 Py_DECREF(peer_alt_names);
1246 goto fail1;
1247 }
1248 Py_DECREF(peer_alt_names);
1249 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001250
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001251 /* Authority Information Access: OCSP URIs */
1252 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1253 if (obj == NULL) {
1254 goto fail1;
1255 } else if (obj != Py_None) {
1256 result = PyDict_SetItemString(retval, "OCSP", obj);
1257 Py_DECREF(obj);
1258 if (result < 0) {
1259 goto fail1;
1260 }
1261 }
1262
1263 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1264 if (obj == NULL) {
1265 goto fail1;
1266 } else if (obj != Py_None) {
1267 result = PyDict_SetItemString(retval, "caIssuers", obj);
1268 Py_DECREF(obj);
1269 if (result < 0) {
1270 goto fail1;
1271 }
1272 }
1273
1274 /* CDP (CRL distribution points) */
1275 obj = _get_crl_dp(certificate);
1276 if (obj == NULL) {
1277 goto fail1;
1278 } else if (obj != Py_None) {
1279 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1280 Py_DECREF(obj);
1281 if (result < 0) {
1282 goto fail1;
1283 }
1284 }
1285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 BIO_free(biobuf);
1287 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001288
1289 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 if (biobuf != NULL)
1291 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001292 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 Py_XDECREF(retval);
1294 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001295}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001296
Christian Heimes9a5395a2013-06-17 15:44:12 +02001297static PyObject *
1298_certificate_to_der(X509 *certificate)
1299{
1300 unsigned char *bytes_buf = NULL;
1301 int len;
1302 PyObject *retval;
1303
1304 bytes_buf = NULL;
1305 len = i2d_X509(certificate, &bytes_buf);
1306 if (len < 0) {
1307 _setSSLError(NULL, 0, __FILE__, __LINE__);
1308 return NULL;
1309 }
1310 /* this is actually an immutable bytes sequence */
1311 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1312 OPENSSL_free(bytes_buf);
1313 return retval;
1314}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001316/*[clinic input]
1317_ssl._test_decode_cert
1318 path: object(converter="PyUnicode_FSConverter")
1319 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001321[clinic start generated code]*/
1322
1323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001324_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1325/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001326{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 X509 *x=NULL;
1329 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1332 PyErr_SetString(PySSLErrorObject,
1333 "Can't malloc memory to read file");
1334 goto fail0;
1335 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001337 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 PyErr_SetString(PySSLErrorObject,
1339 "Can't open file");
1340 goto fail0;
1341 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1344 if (x == NULL) {
1345 PyErr_SetString(PySSLErrorObject,
1346 "Error decoding PEM-encoded file");
1347 goto fail0;
1348 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001349
Antoine Pitroufb046912010-11-09 20:21:19 +00001350 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001351 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352
1353 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001354 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 if (cert != NULL) BIO_free(cert);
1356 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001357}
1358
1359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001360/*[clinic input]
1361_ssl._SSLSocket.peer_certificate
1362 der as binary_mode: bool = False
1363 /
1364
1365Returns the certificate for the peer.
1366
1367If no certificate was provided, returns None. If a certificate was
1368provided, but not validated, returns an empty dictionary. Otherwise
1369returns a dict containing information about the peer certificate.
1370
1371If the optional argument is True, returns a DER-encoded copy of the
1372peer certificate, or None if no certificate was provided. This will
1373return the certificate even if it wasn't validated.
1374[clinic start generated code]*/
1375
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001376static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001377_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1378/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381
Antoine Pitrou20b85552013-09-29 19:50:53 +02001382 if (!self->handshake_done) {
1383 PyErr_SetString(PyExc_ValueError,
1384 "handshake not done yet");
1385 return NULL;
1386 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 if (!self->peer_cert)
1388 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001389
Antoine Pitrou721738f2012-08-15 23:20:39 +02001390 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001392 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001394 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 if ((verification & SSL_VERIFY_PEER) == 0)
1396 return PyDict_New();
1397 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001398 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400}
1401
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001402static PyObject *
1403cipher_to_tuple(const SSL_CIPHER *cipher)
1404{
1405 const char *cipher_name, *cipher_protocol;
1406 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 if (retval == NULL)
1408 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001410 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001412 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 PyTuple_SET_ITEM(retval, 0, Py_None);
1414 } else {
1415 v = PyUnicode_FromString(cipher_name);
1416 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001417 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 PyTuple_SET_ITEM(retval, 0, v);
1419 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001420
1421 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001423 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 PyTuple_SET_ITEM(retval, 1, Py_None);
1425 } else {
1426 v = PyUnicode_FromString(cipher_protocol);
1427 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001428 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001429 PyTuple_SET_ITEM(retval, 1, v);
1430 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001431
1432 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001434 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001438
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001439 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001440 Py_DECREF(retval);
1441 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442}
1443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001444/*[clinic input]
1445_ssl._SSLSocket.shared_ciphers
1446[clinic start generated code]*/
1447
1448static PyObject *
1449_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1450/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001451{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001452 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001453 STACK_OF(SSL_CIPHER) *ciphers;
1454 int i;
1455 PyObject *res;
1456
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001457 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001458 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001459 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001460 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1461 if (!res)
1462 return NULL;
1463 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1464 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1465 if (!tup) {
1466 Py_DECREF(res);
1467 return NULL;
1468 }
1469 PyList_SET_ITEM(res, i, tup);
1470 }
1471 return res;
1472}
1473
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001474/*[clinic input]
1475_ssl._SSLSocket.cipher
1476[clinic start generated code]*/
1477
1478static PyObject *
1479_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1480/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001481{
1482 const SSL_CIPHER *current;
1483
1484 if (self->ssl == NULL)
1485 Py_RETURN_NONE;
1486 current = SSL_get_current_cipher(self->ssl);
1487 if (current == NULL)
1488 Py_RETURN_NONE;
1489 return cipher_to_tuple(current);
1490}
1491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001492/*[clinic input]
1493_ssl._SSLSocket.version
1494[clinic start generated code]*/
1495
1496static PyObject *
1497_ssl__SSLSocket_version_impl(PySSLSocket *self)
1498/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001499{
1500 const char *version;
1501
1502 if (self->ssl == NULL)
1503 Py_RETURN_NONE;
1504 version = SSL_get_version(self->ssl);
1505 if (!strcmp(version, "unknown"))
1506 Py_RETURN_NONE;
1507 return PyUnicode_FromString(version);
1508}
1509
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001510#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001511/*[clinic input]
1512_ssl._SSLSocket.selected_npn_protocol
1513[clinic start generated code]*/
1514
1515static PyObject *
1516_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1517/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1518{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001519 const unsigned char *out;
1520 unsigned int outlen;
1521
Victor Stinner4569cd52013-06-23 14:58:43 +02001522 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001523 &out, &outlen);
1524
1525 if (out == NULL)
1526 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001527 return PyUnicode_FromStringAndSize((char *)out, outlen);
1528}
1529#endif
1530
1531#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001532/*[clinic input]
1533_ssl._SSLSocket.selected_alpn_protocol
1534[clinic start generated code]*/
1535
1536static PyObject *
1537_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1538/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1539{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001540 const unsigned char *out;
1541 unsigned int outlen;
1542
1543 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1544
1545 if (out == NULL)
1546 Py_RETURN_NONE;
1547 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001548}
1549#endif
1550
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001551/*[clinic input]
1552_ssl._SSLSocket.compression
1553[clinic start generated code]*/
1554
1555static PyObject *
1556_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1557/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1558{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001559#ifdef OPENSSL_NO_COMP
1560 Py_RETURN_NONE;
1561#else
1562 const COMP_METHOD *comp_method;
1563 const char *short_name;
1564
1565 if (self->ssl == NULL)
1566 Py_RETURN_NONE;
1567 comp_method = SSL_get_current_compression(self->ssl);
1568 if (comp_method == NULL || comp_method->type == NID_undef)
1569 Py_RETURN_NONE;
1570 short_name = OBJ_nid2sn(comp_method->type);
1571 if (short_name == NULL)
1572 Py_RETURN_NONE;
1573 return PyUnicode_DecodeFSDefault(short_name);
1574#endif
1575}
1576
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001577static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1578 Py_INCREF(self->ctx);
1579 return self->ctx;
1580}
1581
1582static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1583 void *closure) {
1584
1585 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001586#if !HAVE_SNI
1587 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1588 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001589 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001590#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001591 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001592 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001593 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001594#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001595 } else {
1596 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1597 return -1;
1598 }
1599
1600 return 0;
1601}
1602
1603PyDoc_STRVAR(PySSL_set_context_doc,
1604"_setter_context(ctx)\n\
1605\
1606This changes the context associated with the SSLSocket. This is typically\n\
1607used from within a callback function set by the set_servername_callback\n\
1608on the SSLContext to change the certificate information associated with the\n\
1609SSLSocket before the cryptographic exchange handshake messages\n");
1610
1611
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001612static PyObject *
1613PySSL_get_server_side(PySSLSocket *self, void *c)
1614{
1615 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1616}
1617
1618PyDoc_STRVAR(PySSL_get_server_side_doc,
1619"Whether this is a server-side socket.");
1620
1621static PyObject *
1622PySSL_get_server_hostname(PySSLSocket *self, void *c)
1623{
1624 if (self->server_hostname == NULL)
1625 Py_RETURN_NONE;
1626 Py_INCREF(self->server_hostname);
1627 return self->server_hostname;
1628}
1629
1630PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1631"The currently set server hostname (for SNI).");
1632
1633static PyObject *
1634PySSL_get_owner(PySSLSocket *self, void *c)
1635{
1636 PyObject *owner;
1637
1638 if (self->owner == NULL)
1639 Py_RETURN_NONE;
1640
1641 owner = PyWeakref_GetObject(self->owner);
1642 Py_INCREF(owner);
1643 return owner;
1644}
1645
1646static int
1647PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1648{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001649 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001650 if (self->owner == NULL)
1651 return -1;
1652 return 0;
1653}
1654
1655PyDoc_STRVAR(PySSL_get_owner_doc,
1656"The Python-level owner of this object.\
1657Passed as \"self\" in servername callback.");
1658
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001659
Antoine Pitrou152efa22010-05-16 18:19:27 +00001660static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001661{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 if (self->peer_cert) /* Possible not to have one? */
1663 X509_free (self->peer_cert);
1664 if (self->ssl)
1665 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001667 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001668 Py_XDECREF(self->server_hostname);
1669 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001671}
1672
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001673/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001674 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001675 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001677
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001678static int
Victor Stinner14690702015-04-06 22:46:13 +02001679PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001680{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001681 int rc;
1682#ifdef HAVE_POLL
1683 struct pollfd pollfd;
1684 _PyTime_t ms;
1685#else
1686 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001687 fd_set fds;
1688 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001689#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001692 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001694 else if (timeout < 0) {
1695 if (s->sock_timeout > 0)
1696 return SOCKET_HAS_TIMED_OUT;
1697 else
1698 return SOCKET_IS_BLOCKING;
1699 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 /* Guard against closed socket */
1702 if (s->sock_fd < 0)
1703 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 /* Prefer poll, if available, since you can poll() any fd
1706 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001707#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001708 pollfd.fd = s->sock_fd;
1709 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001710
Victor Stinner14690702015-04-06 22:46:13 +02001711 /* timeout is in seconds, poll() uses milliseconds */
1712 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001713 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001714
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001715 PySSL_BEGIN_ALLOW_THREADS
1716 rc = poll(&pollfd, 1, (int)ms);
1717 PySSL_END_ALLOW_THREADS
1718#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001720 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001722
Victor Stinner14690702015-04-06 22:46:13 +02001723 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 FD_ZERO(&fds);
1726 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001727
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001728 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001730 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001731 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001732 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001734 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001736#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1739 (when we are able to write or when there's something to read) */
1740 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001741}
1742
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001743/*[clinic input]
1744_ssl._SSLSocket.write
1745 b: Py_buffer
1746 /
1747
1748Writes the bytes-like object b into the SSL object.
1749
1750Returns the number of bytes written.
1751[clinic start generated code]*/
1752
1753static PyObject *
1754_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1755/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001756{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 int len;
1758 int sockstate;
1759 int err;
1760 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001761 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001762 _PyTime_t timeout, deadline = 0;
1763 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001764
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001765 if (sock != NULL) {
1766 if (((PyObject*)sock) == Py_None) {
1767 _setSSLError("Underlying socket connection gone",
1768 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1769 return NULL;
1770 }
1771 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 }
1773
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001774 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001775 PyErr_Format(PyExc_OverflowError,
1776 "string longer than %d bytes", INT_MAX);
1777 goto error;
1778 }
1779
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001780 if (sock != NULL) {
1781 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001782 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001783 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1784 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1785 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786
Victor Stinner14690702015-04-06 22:46:13 +02001787 timeout = GET_SOCKET_TIMEOUT(sock);
1788 has_timeout = (timeout > 0);
1789 if (has_timeout)
1790 deadline = _PyTime_GetMonotonicClock() + timeout;
1791
1792 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001794 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 "The write operation timed out");
1796 goto error;
1797 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1798 PyErr_SetString(PySSLErrorObject,
1799 "Underlying socket has been closed.");
1800 goto error;
1801 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1802 PyErr_SetString(PySSLErrorObject,
1803 "Underlying socket too large for select().");
1804 goto error;
1805 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001809 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 err = SSL_get_error(self->ssl, len);
1811 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001812
1813 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001815
Victor Stinner14690702015-04-06 22:46:13 +02001816 if (has_timeout)
1817 timeout = deadline - _PyTime_GetMonotonicClock();
1818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001820 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001822 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 } else {
1824 sockstate = SOCKET_OPERATION_OK;
1825 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001828 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 "The write operation timed out");
1830 goto error;
1831 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1832 PyErr_SetString(PySSLErrorObject,
1833 "Underlying socket has been closed.");
1834 goto error;
1835 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1836 break;
1837 }
1838 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001839
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001840 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 if (len > 0)
1842 return PyLong_FromLong(len);
1843 else
1844 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001845
1846error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001847 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001849}
1850
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001851/*[clinic input]
1852_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001853
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001854Returns the number of already decrypted bytes available for read, pending on the connection.
1855[clinic start generated code]*/
1856
1857static PyObject *
1858_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1859/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001860{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 PySSL_BEGIN_ALLOW_THREADS
1864 count = SSL_pending(self->ssl);
1865 PySSL_END_ALLOW_THREADS
1866 if (count < 0)
1867 return PySSL_SetError(self, count, __FILE__, __LINE__);
1868 else
1869 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001870}
1871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001872/*[clinic input]
1873_ssl._SSLSocket.read
1874 size as len: int
1875 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001876 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001877 ]
1878 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001879
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001880Read up to size bytes from the SSL socket.
1881[clinic start generated code]*/
1882
1883static PyObject *
1884_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1885 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001886/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001887{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001890 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 int sockstate;
1892 int err;
1893 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001894 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001895 _PyTime_t timeout, deadline = 0;
1896 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001897
Martin Panter5503d472016-03-27 05:35:19 +00001898 if (!group_right_1 && len < 0) {
1899 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1900 return NULL;
1901 }
1902
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001903 if (sock != NULL) {
1904 if (((PyObject*)sock) == Py_None) {
1905 _setSSLError("Underlying socket connection gone",
1906 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1907 return NULL;
1908 }
1909 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001910 }
1911
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001912 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001913 dest = PyBytes_FromStringAndSize(NULL, len);
1914 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001915 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00001916 if (len == 0) {
1917 Py_XDECREF(sock);
1918 return dest;
1919 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001920 mem = PyBytes_AS_STRING(dest);
1921 }
1922 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001923 mem = buffer->buf;
1924 if (len <= 0 || len > buffer->len) {
1925 len = (int) buffer->len;
1926 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001927 PyErr_SetString(PyExc_OverflowError,
1928 "maximum length can't fit in a C 'int'");
1929 goto error;
1930 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00001931 if (len == 0) {
1932 count = 0;
1933 goto done;
1934 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001935 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 }
1937
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001938 if (sock != NULL) {
1939 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001940 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001941 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1942 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1943 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944
Victor Stinner14690702015-04-06 22:46:13 +02001945 timeout = GET_SOCKET_TIMEOUT(sock);
1946 has_timeout = (timeout > 0);
1947 if (has_timeout)
1948 deadline = _PyTime_GetMonotonicClock() + timeout;
1949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 PySSL_BEGIN_ALLOW_THREADS
1952 count = SSL_read(self->ssl, mem, len);
1953 err = SSL_get_error(self->ssl, count);
1954 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 if (PyErr_CheckSignals())
1957 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001958
Victor Stinner14690702015-04-06 22:46:13 +02001959 if (has_timeout)
1960 timeout = deadline - _PyTime_GetMonotonicClock();
1961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001963 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001965 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001966 } else if (err == SSL_ERROR_ZERO_RETURN &&
1967 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 {
1969 count = 0;
1970 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001972 else
1973 sockstate = SOCKET_OPERATION_OK;
1974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001976 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 "The read operation timed out");
1978 goto error;
1979 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1980 break;
1981 }
1982 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 if (count <= 0) {
1985 PySSL_SetError(self, count, __FILE__, __LINE__);
1986 goto error;
1987 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001988
1989done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001990 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001991 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001992 _PyBytes_Resize(&dest, count);
1993 return dest;
1994 }
1995 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 return PyLong_FromLong(count);
1997 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001998
1999error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002000 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002001 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002002 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002004}
2005
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002006/*[clinic input]
2007_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002008
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002009Does the SSL shutdown handshake with the remote end.
2010
2011Returns the underlying socket object.
2012[clinic start generated code]*/
2013
2014static PyObject *
2015_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2016/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002017{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002018 int err, ssl_err, sockstate, nonblocking;
2019 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002020 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002021 _PyTime_t timeout, deadline = 0;
2022 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002023
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002024 if (sock != NULL) {
2025 /* Guard against closed socket */
2026 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
2027 _setSSLError("Underlying socket connection gone",
2028 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2029 return NULL;
2030 }
2031 Py_INCREF(sock);
2032
2033 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002034 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002035 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2036 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002037 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002038
Victor Stinner14690702015-04-06 22:46:13 +02002039 timeout = GET_SOCKET_TIMEOUT(sock);
2040 has_timeout = (timeout > 0);
2041 if (has_timeout)
2042 deadline = _PyTime_GetMonotonicClock() + timeout;
2043
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002044 while (1) {
2045 PySSL_BEGIN_ALLOW_THREADS
2046 /* Disable read-ahead so that unwrap can work correctly.
2047 * Otherwise OpenSSL might read in too much data,
2048 * eating clear text data that happens to be
2049 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002050 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002051 * function is used and the shutdown_seen_zero != 0
2052 * condition is met.
2053 */
2054 if (self->shutdown_seen_zero)
2055 SSL_set_read_ahead(self->ssl, 0);
2056 err = SSL_shutdown(self->ssl);
2057 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002059 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2060 if (err > 0)
2061 break;
2062 if (err == 0) {
2063 /* Don't loop endlessly; instead preserve legacy
2064 behaviour of trying SSL_shutdown() only twice.
2065 This looks necessary for OpenSSL < 0.9.8m */
2066 if (++zeros > 1)
2067 break;
2068 /* Shutdown was sent, now try receiving */
2069 self->shutdown_seen_zero = 1;
2070 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002071 }
2072
Victor Stinner14690702015-04-06 22:46:13 +02002073 if (has_timeout)
2074 timeout = deadline - _PyTime_GetMonotonicClock();
2075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 /* Possibly retry shutdown until timeout or failure */
2077 ssl_err = SSL_get_error(self->ssl, err);
2078 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002079 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002081 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 else
2083 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002085 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2086 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002087 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 "The read operation timed out");
2089 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002090 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002092 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 }
2094 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2095 PyErr_SetString(PySSLErrorObject,
2096 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002097 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 }
2099 else if (sockstate != SOCKET_OPERATION_OK)
2100 /* Retain the SSL error code */
2101 break;
2102 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002103
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002104 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002105 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002107 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002108 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002109 /* It's already INCREF'ed */
2110 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002111 else
2112 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002113
2114error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002115 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002116 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002117}
2118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002119/*[clinic input]
2120_ssl._SSLSocket.tls_unique_cb
2121
2122Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2123
2124If the TLS handshake is not yet complete, None is returned.
2125[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002126
Antoine Pitroud6494802011-07-21 01:11:30 +02002127static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002128_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2129/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002130{
2131 PyObject *retval = NULL;
2132 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002133 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002134
2135 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2136 /* if session is resumed XOR we are the client */
2137 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2138 }
2139 else {
2140 /* if a new session XOR we are the server */
2141 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2142 }
2143
2144 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002145 if (len == 0)
2146 Py_RETURN_NONE;
2147
2148 retval = PyBytes_FromStringAndSize(buf, len);
2149
2150 return retval;
2151}
2152
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002153static PyGetSetDef ssl_getsetlist[] = {
2154 {"context", (getter) PySSL_get_context,
2155 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002156 {"server_side", (getter) PySSL_get_server_side, NULL,
2157 PySSL_get_server_side_doc},
2158 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2159 PySSL_get_server_hostname_doc},
2160 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2161 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002162 {NULL}, /* sentinel */
2163};
2164
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002165static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002166 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2167 _SSL__SSLSOCKET_WRITE_METHODDEF
2168 _SSL__SSLSOCKET_READ_METHODDEF
2169 _SSL__SSLSOCKET_PENDING_METHODDEF
2170 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2171 _SSL__SSLSOCKET_CIPHER_METHODDEF
2172 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2173 _SSL__SSLSOCKET_VERSION_METHODDEF
2174 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2175 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2176 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2177 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2178 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002180};
2181
Antoine Pitrou152efa22010-05-16 18:19:27 +00002182static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002184 "_ssl._SSLSocket", /*tp_name*/
2185 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 0, /*tp_itemsize*/
2187 /* methods */
2188 (destructor)PySSL_dealloc, /*tp_dealloc*/
2189 0, /*tp_print*/
2190 0, /*tp_getattr*/
2191 0, /*tp_setattr*/
2192 0, /*tp_reserved*/
2193 0, /*tp_repr*/
2194 0, /*tp_as_number*/
2195 0, /*tp_as_sequence*/
2196 0, /*tp_as_mapping*/
2197 0, /*tp_hash*/
2198 0, /*tp_call*/
2199 0, /*tp_str*/
2200 0, /*tp_getattro*/
2201 0, /*tp_setattro*/
2202 0, /*tp_as_buffer*/
2203 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2204 0, /*tp_doc*/
2205 0, /*tp_traverse*/
2206 0, /*tp_clear*/
2207 0, /*tp_richcompare*/
2208 0, /*tp_weaklistoffset*/
2209 0, /*tp_iter*/
2210 0, /*tp_iternext*/
2211 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002212 0, /*tp_members*/
2213 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002214};
2215
Antoine Pitrou152efa22010-05-16 18:19:27 +00002216
2217/*
2218 * _SSLContext objects
2219 */
2220
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002221/*[clinic input]
2222@classmethod
2223_ssl._SSLContext.__new__
2224 protocol as proto_version: int
2225 /
2226[clinic start generated code]*/
2227
Antoine Pitrou152efa22010-05-16 18:19:27 +00002228static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002229_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2230/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002231{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002233 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002234 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002235#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002236 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002237#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002238
Antoine Pitrou152efa22010-05-16 18:19:27 +00002239 PySSL_BEGIN_ALLOW_THREADS
2240 if (proto_version == PY_SSL_VERSION_TLS1)
2241 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002242#if HAVE_TLSv1_2
2243 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2244 ctx = SSL_CTX_new(TLSv1_1_method());
2245 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2246 ctx = SSL_CTX_new(TLSv1_2_method());
2247#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002248#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002249 else if (proto_version == PY_SSL_VERSION_SSL3)
2250 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002251#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002252#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002253 else if (proto_version == PY_SSL_VERSION_SSL2)
2254 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002255#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002256 else if (proto_version == PY_SSL_VERSION_SSL23)
2257 ctx = SSL_CTX_new(SSLv23_method());
2258 else
2259 proto_version = -1;
2260 PySSL_END_ALLOW_THREADS
2261
2262 if (proto_version == -1) {
2263 PyErr_SetString(PyExc_ValueError,
2264 "invalid protocol version");
2265 return NULL;
2266 }
2267 if (ctx == NULL) {
2268 PyErr_SetString(PySSLErrorObject,
2269 "failed to allocate SSL context");
2270 return NULL;
2271 }
2272
2273 assert(type != NULL && type->tp_alloc != NULL);
2274 self = (PySSLContext *) type->tp_alloc(type, 0);
2275 if (self == NULL) {
2276 SSL_CTX_free(ctx);
2277 return NULL;
2278 }
2279 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002280#ifdef OPENSSL_NPN_NEGOTIATED
2281 self->npn_protocols = NULL;
2282#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002283#ifdef HAVE_ALPN
2284 self->alpn_protocols = NULL;
2285#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002286#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002287 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002288#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002289 /* Don't check host name by default */
2290 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002291 /* Defaults */
2292 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002293 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2294 if (proto_version != PY_SSL_VERSION_SSL2)
2295 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002296 if (proto_version != PY_SSL_VERSION_SSL3)
2297 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002298 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002299
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002300#if defined(SSL_MODE_RELEASE_BUFFERS)
2301 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2302 usage for no cost at all. However, don't do this for OpenSSL versions
2303 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2304 2014-0198. I can't find exactly which beta fixed this CVE, so be
2305 conservative and assume it wasn't fixed until release. We do this check
2306 at runtime to avoid problems from the dynamic linker.
2307 See #25672 for more on this. */
2308 libver = SSLeay();
2309 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2310 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2311 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2312 }
2313#endif
2314
2315
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002316#ifndef OPENSSL_NO_ECDH
2317 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2318 prime256v1 by default. This is Apache mod_ssl's initialization
2319 policy, so we should be safe. */
2320#if defined(SSL_CTX_set_ecdh_auto)
2321 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2322#else
2323 {
2324 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2325 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2326 EC_KEY_free(key);
2327 }
2328#endif
2329#endif
2330
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002331#define SID_CTX "Python"
2332 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2333 sizeof(SID_CTX));
2334#undef SID_CTX
2335
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002336#ifdef X509_V_FLAG_TRUSTED_FIRST
2337 {
2338 /* Improve trust chain building when cross-signed intermediate
2339 certificates are present. See https://bugs.python.org/issue23476. */
2340 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2341 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2342 }
2343#endif
2344
Antoine Pitrou152efa22010-05-16 18:19:27 +00002345 return (PyObject *)self;
2346}
2347
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002348static int
2349context_traverse(PySSLContext *self, visitproc visit, void *arg)
2350{
2351#ifndef OPENSSL_NO_TLSEXT
2352 Py_VISIT(self->set_hostname);
2353#endif
2354 return 0;
2355}
2356
2357static int
2358context_clear(PySSLContext *self)
2359{
2360#ifndef OPENSSL_NO_TLSEXT
2361 Py_CLEAR(self->set_hostname);
2362#endif
2363 return 0;
2364}
2365
Antoine Pitrou152efa22010-05-16 18:19:27 +00002366static void
2367context_dealloc(PySSLContext *self)
2368{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002369 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002370 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002371#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002372 PyMem_FREE(self->npn_protocols);
2373#endif
2374#ifdef HAVE_ALPN
2375 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002376#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002377 Py_TYPE(self)->tp_free(self);
2378}
2379
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002380/*[clinic input]
2381_ssl._SSLContext.set_ciphers
2382 cipherlist: str
2383 /
2384[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002385
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002386static PyObject *
2387_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2388/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2389{
2390 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002391 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002392 /* Clearing the error queue is necessary on some OpenSSL versions,
2393 otherwise the error will be reported again when another SSL call
2394 is done. */
2395 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002396 PyErr_SetString(PySSLErrorObject,
2397 "No cipher can be selected.");
2398 return NULL;
2399 }
2400 Py_RETURN_NONE;
2401}
2402
Benjamin Petersonc54de472015-01-28 12:06:39 -05002403#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002404static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002405do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2406 const unsigned char *server_protocols, unsigned int server_protocols_len,
2407 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002408{
Benjamin Peterson88615022015-01-23 17:30:26 -05002409 int ret;
2410 if (client_protocols == NULL) {
2411 client_protocols = (unsigned char *)"";
2412 client_protocols_len = 0;
2413 }
2414 if (server_protocols == NULL) {
2415 server_protocols = (unsigned char *)"";
2416 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002417 }
2418
Benjamin Peterson88615022015-01-23 17:30:26 -05002419 ret = SSL_select_next_proto(out, outlen,
2420 server_protocols, server_protocols_len,
2421 client_protocols, client_protocols_len);
2422 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2423 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002424
2425 return SSL_TLSEXT_ERR_OK;
2426}
2427
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002428/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2429static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002430_advertiseNPN_cb(SSL *s,
2431 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002432 void *args)
2433{
2434 PySSLContext *ssl_ctx = (PySSLContext *) args;
2435
2436 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002437 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002438 *len = 0;
2439 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002440 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002441 *len = ssl_ctx->npn_protocols_len;
2442 }
2443
2444 return SSL_TLSEXT_ERR_OK;
2445}
2446/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2447static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002448_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002449 unsigned char **out, unsigned char *outlen,
2450 const unsigned char *server, unsigned int server_len,
2451 void *args)
2452{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002453 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002454 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002455 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002456}
2457#endif
2458
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459/*[clinic input]
2460_ssl._SSLContext._set_npn_protocols
2461 protos: Py_buffer
2462 /
2463[clinic start generated code]*/
2464
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002465static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002466_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2467 Py_buffer *protos)
2468/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002469{
2470#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002471 PyMem_Free(self->npn_protocols);
2472 self->npn_protocols = PyMem_Malloc(protos->len);
2473 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002474 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002475 memcpy(self->npn_protocols, protos->buf, protos->len);
2476 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002477
2478 /* set both server and client callbacks, because the context can
2479 * be used to create both types of sockets */
2480 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2481 _advertiseNPN_cb,
2482 self);
2483 SSL_CTX_set_next_proto_select_cb(self->ctx,
2484 _selectNPN_cb,
2485 self);
2486
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002487 Py_RETURN_NONE;
2488#else
2489 PyErr_SetString(PyExc_NotImplementedError,
2490 "The NPN extension requires OpenSSL 1.0.1 or later.");
2491 return NULL;
2492#endif
2493}
2494
Benjamin Petersoncca27322015-01-23 16:35:37 -05002495#ifdef HAVE_ALPN
2496static int
2497_selectALPN_cb(SSL *s,
2498 const unsigned char **out, unsigned char *outlen,
2499 const unsigned char *client_protocols, unsigned int client_protocols_len,
2500 void *args)
2501{
2502 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002503 return do_protocol_selection(1, (unsigned char **)out, outlen,
2504 ctx->alpn_protocols, ctx->alpn_protocols_len,
2505 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002506}
2507#endif
2508
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002509/*[clinic input]
2510_ssl._SSLContext._set_alpn_protocols
2511 protos: Py_buffer
2512 /
2513[clinic start generated code]*/
2514
Benjamin Petersoncca27322015-01-23 16:35:37 -05002515static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002516_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2517 Py_buffer *protos)
2518/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002519{
2520#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002521 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002522 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002523 if (!self->alpn_protocols)
2524 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002525 memcpy(self->alpn_protocols, protos->buf, protos->len);
2526 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002527
2528 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2529 return PyErr_NoMemory();
2530 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2531
Benjamin Petersoncca27322015-01-23 16:35:37 -05002532 Py_RETURN_NONE;
2533#else
2534 PyErr_SetString(PyExc_NotImplementedError,
2535 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2536 return NULL;
2537#endif
2538}
2539
Antoine Pitrou152efa22010-05-16 18:19:27 +00002540static PyObject *
2541get_verify_mode(PySSLContext *self, void *c)
2542{
2543 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2544 case SSL_VERIFY_NONE:
2545 return PyLong_FromLong(PY_SSL_CERT_NONE);
2546 case SSL_VERIFY_PEER:
2547 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2548 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2549 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2550 }
2551 PyErr_SetString(PySSLErrorObject,
2552 "invalid return value from SSL_CTX_get_verify_mode");
2553 return NULL;
2554}
2555
2556static int
2557set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2558{
2559 int n, mode;
2560 if (!PyArg_Parse(arg, "i", &n))
2561 return -1;
2562 if (n == PY_SSL_CERT_NONE)
2563 mode = SSL_VERIFY_NONE;
2564 else if (n == PY_SSL_CERT_OPTIONAL)
2565 mode = SSL_VERIFY_PEER;
2566 else if (n == PY_SSL_CERT_REQUIRED)
2567 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2568 else {
2569 PyErr_SetString(PyExc_ValueError,
2570 "invalid value for verify_mode");
2571 return -1;
2572 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002573 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2574 PyErr_SetString(PyExc_ValueError,
2575 "Cannot set verify_mode to CERT_NONE when "
2576 "check_hostname is enabled.");
2577 return -1;
2578 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002579 SSL_CTX_set_verify(self->ctx, mode, NULL);
2580 return 0;
2581}
2582
2583static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002584get_verify_flags(PySSLContext *self, void *c)
2585{
2586 X509_STORE *store;
2587 unsigned long flags;
2588
2589 store = SSL_CTX_get_cert_store(self->ctx);
2590 flags = X509_VERIFY_PARAM_get_flags(store->param);
2591 return PyLong_FromUnsignedLong(flags);
2592}
2593
2594static int
2595set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2596{
2597 X509_STORE *store;
2598 unsigned long new_flags, flags, set, clear;
2599
2600 if (!PyArg_Parse(arg, "k", &new_flags))
2601 return -1;
2602 store = SSL_CTX_get_cert_store(self->ctx);
2603 flags = X509_VERIFY_PARAM_get_flags(store->param);
2604 clear = flags & ~new_flags;
2605 set = ~flags & new_flags;
2606 if (clear) {
2607 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2608 _setSSLError(NULL, 0, __FILE__, __LINE__);
2609 return -1;
2610 }
2611 }
2612 if (set) {
2613 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2614 _setSSLError(NULL, 0, __FILE__, __LINE__);
2615 return -1;
2616 }
2617 }
2618 return 0;
2619}
2620
2621static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002622get_options(PySSLContext *self, void *c)
2623{
2624 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2625}
2626
2627static int
2628set_options(PySSLContext *self, PyObject *arg, void *c)
2629{
2630 long new_opts, opts, set, clear;
2631 if (!PyArg_Parse(arg, "l", &new_opts))
2632 return -1;
2633 opts = SSL_CTX_get_options(self->ctx);
2634 clear = opts & ~new_opts;
2635 set = ~opts & new_opts;
2636 if (clear) {
2637#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2638 SSL_CTX_clear_options(self->ctx, clear);
2639#else
2640 PyErr_SetString(PyExc_ValueError,
2641 "can't clear options before OpenSSL 0.9.8m");
2642 return -1;
2643#endif
2644 }
2645 if (set)
2646 SSL_CTX_set_options(self->ctx, set);
2647 return 0;
2648}
2649
Christian Heimes1aa9a752013-12-02 02:41:19 +01002650static PyObject *
2651get_check_hostname(PySSLContext *self, void *c)
2652{
2653 return PyBool_FromLong(self->check_hostname);
2654}
2655
2656static int
2657set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2658{
2659 int check_hostname;
2660 if (!PyArg_Parse(arg, "p", &check_hostname))
2661 return -1;
2662 if (check_hostname &&
2663 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2664 PyErr_SetString(PyExc_ValueError,
2665 "check_hostname needs a SSL context with either "
2666 "CERT_OPTIONAL or CERT_REQUIRED");
2667 return -1;
2668 }
2669 self->check_hostname = check_hostname;
2670 return 0;
2671}
2672
2673
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002674typedef struct {
2675 PyThreadState *thread_state;
2676 PyObject *callable;
2677 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002678 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002679 int error;
2680} _PySSLPasswordInfo;
2681
2682static int
2683_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2684 const char *bad_type_error)
2685{
2686 /* Set the password and size fields of a _PySSLPasswordInfo struct
2687 from a unicode, bytes, or byte array object.
2688 The password field will be dynamically allocated and must be freed
2689 by the caller */
2690 PyObject *password_bytes = NULL;
2691 const char *data = NULL;
2692 Py_ssize_t size;
2693
2694 if (PyUnicode_Check(password)) {
2695 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2696 if (!password_bytes) {
2697 goto error;
2698 }
2699 data = PyBytes_AS_STRING(password_bytes);
2700 size = PyBytes_GET_SIZE(password_bytes);
2701 } else if (PyBytes_Check(password)) {
2702 data = PyBytes_AS_STRING(password);
2703 size = PyBytes_GET_SIZE(password);
2704 } else if (PyByteArray_Check(password)) {
2705 data = PyByteArray_AS_STRING(password);
2706 size = PyByteArray_GET_SIZE(password);
2707 } else {
2708 PyErr_SetString(PyExc_TypeError, bad_type_error);
2709 goto error;
2710 }
2711
Victor Stinner9ee02032013-06-23 15:08:23 +02002712 if (size > (Py_ssize_t)INT_MAX) {
2713 PyErr_Format(PyExc_ValueError,
2714 "password cannot be longer than %d bytes", INT_MAX);
2715 goto error;
2716 }
2717
Victor Stinner11ebff22013-07-07 17:07:52 +02002718 PyMem_Free(pw_info->password);
2719 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002720 if (!pw_info->password) {
2721 PyErr_SetString(PyExc_MemoryError,
2722 "unable to allocate password buffer");
2723 goto error;
2724 }
2725 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002726 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002727
2728 Py_XDECREF(password_bytes);
2729 return 1;
2730
2731error:
2732 Py_XDECREF(password_bytes);
2733 return 0;
2734}
2735
2736static int
2737_password_callback(char *buf, int size, int rwflag, void *userdata)
2738{
2739 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2740 PyObject *fn_ret = NULL;
2741
2742 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2743
2744 if (pw_info->callable) {
2745 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2746 if (!fn_ret) {
2747 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2748 core python API, so we could use it to add a frame here */
2749 goto error;
2750 }
2751
2752 if (!_pwinfo_set(pw_info, fn_ret,
2753 "password callback must return a string")) {
2754 goto error;
2755 }
2756 Py_CLEAR(fn_ret);
2757 }
2758
2759 if (pw_info->size > size) {
2760 PyErr_Format(PyExc_ValueError,
2761 "password cannot be longer than %d bytes", size);
2762 goto error;
2763 }
2764
2765 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2766 memcpy(buf, pw_info->password, pw_info->size);
2767 return pw_info->size;
2768
2769error:
2770 Py_XDECREF(fn_ret);
2771 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2772 pw_info->error = 1;
2773 return -1;
2774}
2775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002776/*[clinic input]
2777_ssl._SSLContext.load_cert_chain
2778 certfile: object
2779 keyfile: object = NULL
2780 password: object = NULL
2781
2782[clinic start generated code]*/
2783
Antoine Pitroub5218772010-05-21 09:56:06 +00002784static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002785_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2786 PyObject *keyfile, PyObject *password)
2787/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002789 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002790 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2791 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2792 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 int r;
2794
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002795 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002796 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002797 if (keyfile == Py_None)
2798 keyfile = NULL;
2799 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2800 PyErr_SetString(PyExc_TypeError,
2801 "certfile should be a valid filesystem path");
2802 return NULL;
2803 }
2804 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2805 PyErr_SetString(PyExc_TypeError,
2806 "keyfile should be a valid filesystem path");
2807 goto error;
2808 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002809 if (password && password != Py_None) {
2810 if (PyCallable_Check(password)) {
2811 pw_info.callable = password;
2812 } else if (!_pwinfo_set(&pw_info, password,
2813 "password should be a string or callable")) {
2814 goto error;
2815 }
2816 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2817 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2818 }
2819 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2821 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002822 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002823 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002824 if (pw_info.error) {
2825 ERR_clear_error();
2826 /* the password callback has already set the error information */
2827 }
2828 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002829 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002830 PyErr_SetFromErrno(PyExc_IOError);
2831 }
2832 else {
2833 _setSSLError(NULL, 0, __FILE__, __LINE__);
2834 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002835 goto error;
2836 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002837 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002838 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002839 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2840 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002841 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2842 Py_CLEAR(keyfile_bytes);
2843 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002844 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002845 if (pw_info.error) {
2846 ERR_clear_error();
2847 /* the password callback has already set the error information */
2848 }
2849 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002850 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002851 PyErr_SetFromErrno(PyExc_IOError);
2852 }
2853 else {
2854 _setSSLError(NULL, 0, __FILE__, __LINE__);
2855 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002856 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002857 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002858 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002860 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002861 if (r != 1) {
2862 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002863 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002864 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002865 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2866 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002867 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 Py_RETURN_NONE;
2869
2870error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002871 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2872 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002873 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002874 Py_XDECREF(keyfile_bytes);
2875 Py_XDECREF(certfile_bytes);
2876 return NULL;
2877}
2878
Christian Heimesefff7062013-11-21 03:35:02 +01002879/* internal helper function, returns -1 on error
2880 */
2881static int
2882_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2883 int filetype)
2884{
2885 BIO *biobuf = NULL;
2886 X509_STORE *store;
2887 int retval = 0, err, loaded = 0;
2888
2889 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2890
2891 if (len <= 0) {
2892 PyErr_SetString(PyExc_ValueError,
2893 "Empty certificate data");
2894 return -1;
2895 } else if (len > INT_MAX) {
2896 PyErr_SetString(PyExc_OverflowError,
2897 "Certificate data is too long.");
2898 return -1;
2899 }
2900
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002901 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002902 if (biobuf == NULL) {
2903 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2904 return -1;
2905 }
2906
2907 store = SSL_CTX_get_cert_store(self->ctx);
2908 assert(store != NULL);
2909
2910 while (1) {
2911 X509 *cert = NULL;
2912 int r;
2913
2914 if (filetype == SSL_FILETYPE_ASN1) {
2915 cert = d2i_X509_bio(biobuf, NULL);
2916 } else {
2917 cert = PEM_read_bio_X509(biobuf, NULL,
2918 self->ctx->default_passwd_callback,
2919 self->ctx->default_passwd_callback_userdata);
2920 }
2921 if (cert == NULL) {
2922 break;
2923 }
2924 r = X509_STORE_add_cert(store, cert);
2925 X509_free(cert);
2926 if (!r) {
2927 err = ERR_peek_last_error();
2928 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2929 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2930 /* cert already in hash table, not an error */
2931 ERR_clear_error();
2932 } else {
2933 break;
2934 }
2935 }
2936 loaded++;
2937 }
2938
2939 err = ERR_peek_last_error();
2940 if ((filetype == SSL_FILETYPE_ASN1) &&
2941 (loaded > 0) &&
2942 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2943 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2944 /* EOF ASN1 file, not an error */
2945 ERR_clear_error();
2946 retval = 0;
2947 } else if ((filetype == SSL_FILETYPE_PEM) &&
2948 (loaded > 0) &&
2949 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2950 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2951 /* EOF PEM file, not an error */
2952 ERR_clear_error();
2953 retval = 0;
2954 } else {
2955 _setSSLError(NULL, 0, __FILE__, __LINE__);
2956 retval = -1;
2957 }
2958
2959 BIO_free(biobuf);
2960 return retval;
2961}
2962
2963
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002964/*[clinic input]
2965_ssl._SSLContext.load_verify_locations
2966 cafile: object = NULL
2967 capath: object = NULL
2968 cadata: object = NULL
2969
2970[clinic start generated code]*/
2971
Antoine Pitrou152efa22010-05-16 18:19:27 +00002972static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002973_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2974 PyObject *cafile,
2975 PyObject *capath,
2976 PyObject *cadata)
2977/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002978{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002979 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2980 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002981 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002983 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002984 if (cafile == Py_None)
2985 cafile = NULL;
2986 if (capath == Py_None)
2987 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002988 if (cadata == Py_None)
2989 cadata = NULL;
2990
2991 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002992 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002993 "cafile, capath and cadata cannot be all omitted");
2994 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002995 }
2996 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2997 PyErr_SetString(PyExc_TypeError,
2998 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002999 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003000 }
3001 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003002 PyErr_SetString(PyExc_TypeError,
3003 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003004 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003005 }
Christian Heimesefff7062013-11-21 03:35:02 +01003006
3007 /* validata cadata type and load cadata */
3008 if (cadata) {
3009 Py_buffer buf;
3010 PyObject *cadata_ascii = NULL;
3011
3012 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3013 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3014 PyBuffer_Release(&buf);
3015 PyErr_SetString(PyExc_TypeError,
3016 "cadata should be a contiguous buffer with "
3017 "a single dimension");
3018 goto error;
3019 }
3020 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3021 PyBuffer_Release(&buf);
3022 if (r == -1) {
3023 goto error;
3024 }
3025 } else {
3026 PyErr_Clear();
3027 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3028 if (cadata_ascii == NULL) {
3029 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003030 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003031 "bytes-like object");
3032 goto error;
3033 }
3034 r = _add_ca_certs(self,
3035 PyBytes_AS_STRING(cadata_ascii),
3036 PyBytes_GET_SIZE(cadata_ascii),
3037 SSL_FILETYPE_PEM);
3038 Py_DECREF(cadata_ascii);
3039 if (r == -1) {
3040 goto error;
3041 }
3042 }
3043 }
3044
3045 /* load cafile or capath */
3046 if (cafile || capath) {
3047 if (cafile)
3048 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3049 if (capath)
3050 capath_buf = PyBytes_AS_STRING(capath_bytes);
3051 PySSL_BEGIN_ALLOW_THREADS
3052 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3053 PySSL_END_ALLOW_THREADS
3054 if (r != 1) {
3055 ok = 0;
3056 if (errno != 0) {
3057 ERR_clear_error();
3058 PyErr_SetFromErrno(PyExc_IOError);
3059 }
3060 else {
3061 _setSSLError(NULL, 0, __FILE__, __LINE__);
3062 }
3063 goto error;
3064 }
3065 }
3066 goto end;
3067
3068 error:
3069 ok = 0;
3070 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003071 Py_XDECREF(cafile_bytes);
3072 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003073 if (ok) {
3074 Py_RETURN_NONE;
3075 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003076 return NULL;
3077 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078}
3079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003080/*[clinic input]
3081_ssl._SSLContext.load_dh_params
3082 path as filepath: object
3083 /
3084
3085[clinic start generated code]*/
3086
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003088_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3089/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003090{
3091 FILE *f;
3092 DH *dh;
3093
Victor Stinnerdaf45552013-08-28 00:53:59 +02003094 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003095 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003096 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003097
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003098 errno = 0;
3099 PySSL_BEGIN_ALLOW_THREADS
3100 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003101 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003102 PySSL_END_ALLOW_THREADS
3103 if (dh == NULL) {
3104 if (errno != 0) {
3105 ERR_clear_error();
3106 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3107 }
3108 else {
3109 _setSSLError(NULL, 0, __FILE__, __LINE__);
3110 }
3111 return NULL;
3112 }
3113 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3114 _setSSLError(NULL, 0, __FILE__, __LINE__);
3115 DH_free(dh);
3116 Py_RETURN_NONE;
3117}
3118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003119/*[clinic input]
3120_ssl._SSLContext._wrap_socket
3121 sock: object(subclass_of="PySocketModule.Sock_Type")
3122 server_side: int
3123 server_hostname as hostname_obj: object = None
3124
3125[clinic start generated code]*/
3126
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003127static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003128_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3129 int server_side, PyObject *hostname_obj)
3130/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003131{
Antoine Pitroud5323212010-10-22 18:19:07 +00003132 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003133 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003134
Antoine Pitroud5323212010-10-22 18:19:07 +00003135 /* server_hostname is either None (or absent), or to be encoded
3136 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003137 if (hostname_obj != Py_None) {
3138 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003139 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003140 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003142 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3143 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003144 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003145 if (hostname != NULL)
3146 PyMem_Free(hostname);
3147 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003148}
3149
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003150/*[clinic input]
3151_ssl._SSLContext._wrap_bio
3152 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3153 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3154 server_side: int
3155 server_hostname as hostname_obj: object = None
3156
3157[clinic start generated code]*/
3158
Antoine Pitroub0182c82010-10-12 20:09:02 +00003159static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003160_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3161 PySSLMemoryBIO *outgoing, int server_side,
3162 PyObject *hostname_obj)
3163/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003164{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003165 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003166 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003167
3168 /* server_hostname is either None (or absent), or to be encoded
3169 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003170 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003171 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3172 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003173 }
3174
3175 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3176 incoming, outgoing);
3177
3178 PyMem_Free(hostname);
3179 return res;
3180}
3181
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003182/*[clinic input]
3183_ssl._SSLContext.session_stats
3184[clinic start generated code]*/
3185
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003186static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003187_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3188/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003189{
3190 int r;
3191 PyObject *value, *stats = PyDict_New();
3192 if (!stats)
3193 return NULL;
3194
3195#define ADD_STATS(SSL_NAME, KEY_NAME) \
3196 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3197 if (value == NULL) \
3198 goto error; \
3199 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3200 Py_DECREF(value); \
3201 if (r < 0) \
3202 goto error;
3203
3204 ADD_STATS(number, "number");
3205 ADD_STATS(connect, "connect");
3206 ADD_STATS(connect_good, "connect_good");
3207 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3208 ADD_STATS(accept, "accept");
3209 ADD_STATS(accept_good, "accept_good");
3210 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3211 ADD_STATS(accept, "accept");
3212 ADD_STATS(hits, "hits");
3213 ADD_STATS(misses, "misses");
3214 ADD_STATS(timeouts, "timeouts");
3215 ADD_STATS(cache_full, "cache_full");
3216
3217#undef ADD_STATS
3218
3219 return stats;
3220
3221error:
3222 Py_DECREF(stats);
3223 return NULL;
3224}
3225
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003226/*[clinic input]
3227_ssl._SSLContext.set_default_verify_paths
3228[clinic start generated code]*/
3229
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003230static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003231_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3232/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003233{
3234 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3235 _setSSLError(NULL, 0, __FILE__, __LINE__);
3236 return NULL;
3237 }
3238 Py_RETURN_NONE;
3239}
3240
Antoine Pitrou501da612011-12-21 09:27:41 +01003241#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003242/*[clinic input]
3243_ssl._SSLContext.set_ecdh_curve
3244 name: object
3245 /
3246
3247[clinic start generated code]*/
3248
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003249static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003250_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3251/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003252{
3253 PyObject *name_bytes;
3254 int nid;
3255 EC_KEY *key;
3256
3257 if (!PyUnicode_FSConverter(name, &name_bytes))
3258 return NULL;
3259 assert(PyBytes_Check(name_bytes));
3260 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3261 Py_DECREF(name_bytes);
3262 if (nid == 0) {
3263 PyErr_Format(PyExc_ValueError,
3264 "unknown elliptic curve name %R", name);
3265 return NULL;
3266 }
3267 key = EC_KEY_new_by_curve_name(nid);
3268 if (key == NULL) {
3269 _setSSLError(NULL, 0, __FILE__, __LINE__);
3270 return NULL;
3271 }
3272 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3273 EC_KEY_free(key);
3274 Py_RETURN_NONE;
3275}
Antoine Pitrou501da612011-12-21 09:27:41 +01003276#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003277
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003278#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003279static int
3280_servername_callback(SSL *s, int *al, void *args)
3281{
3282 int ret;
3283 PySSLContext *ssl_ctx = (PySSLContext *) args;
3284 PySSLSocket *ssl;
3285 PyObject *servername_o;
3286 PyObject *servername_idna;
3287 PyObject *result;
3288 /* The high-level ssl.SSLSocket object */
3289 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003290 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003291#ifdef WITH_THREAD
3292 PyGILState_STATE gstate = PyGILState_Ensure();
3293#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294
3295 if (ssl_ctx->set_hostname == NULL) {
3296 /* remove race condition in this the call back while if removing the
3297 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003298#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003299 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003300#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003301 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003302 }
3303
3304 ssl = SSL_get_app_data(s);
3305 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003306
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003307 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003308 * SSL connection and that has a .context attribute that can be changed to
3309 * identify the requested hostname. Since the official API is the Python
3310 * level API we want to pass the callback a Python level object rather than
3311 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3312 * SSLObject) that will be passed. Otherwise if there's a socket then that
3313 * will be passed. If both do not exist only then the C-level object is
3314 * passed. */
3315 if (ssl->owner)
3316 ssl_socket = PyWeakref_GetObject(ssl->owner);
3317 else if (ssl->Socket)
3318 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3319 else
3320 ssl_socket = (PyObject *) ssl;
3321
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003322 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003323 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003324 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003325
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003326 if (servername == NULL) {
3327 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3328 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003329 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003330 else {
3331 servername_o = PyBytes_FromString(servername);
3332 if (servername_o == NULL) {
3333 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3334 goto error;
3335 }
3336 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3337 if (servername_idna == NULL) {
3338 PyErr_WriteUnraisable(servername_o);
3339 Py_DECREF(servername_o);
3340 goto error;
3341 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003342 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003343 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3344 servername_idna, ssl_ctx, NULL);
3345 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003346 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003347 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003348
3349 if (result == NULL) {
3350 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3351 *al = SSL_AD_HANDSHAKE_FAILURE;
3352 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3353 }
3354 else {
3355 if (result != Py_None) {
3356 *al = (int) PyLong_AsLong(result);
3357 if (PyErr_Occurred()) {
3358 PyErr_WriteUnraisable(result);
3359 *al = SSL_AD_INTERNAL_ERROR;
3360 }
3361 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3362 }
3363 else {
3364 ret = SSL_TLSEXT_ERR_OK;
3365 }
3366 Py_DECREF(result);
3367 }
3368
Stefan Krah20d60802013-01-17 17:07:17 +01003369#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003370 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003371#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003372 return ret;
3373
3374error:
3375 Py_DECREF(ssl_socket);
3376 *al = SSL_AD_INTERNAL_ERROR;
3377 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003378#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003379 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003380#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003381 return ret;
3382}
Antoine Pitroua5963382013-03-30 16:39:00 +01003383#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003385/*[clinic input]
3386_ssl._SSLContext.set_servername_callback
3387 method as cb: object
3388 /
3389
3390Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3391
3392If the argument is None then the callback is disabled. The method is called
3393with the SSLSocket, the server name as a string, and the SSLContext object.
3394See RFC 6066 for details of the SNI extension.
3395[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003396
3397static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003398_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3399/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003400{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003401#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003402 Py_CLEAR(self->set_hostname);
3403 if (cb == Py_None) {
3404 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3405 }
3406 else {
3407 if (!PyCallable_Check(cb)) {
3408 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3409 PyErr_SetString(PyExc_TypeError,
3410 "not a callable object");
3411 return NULL;
3412 }
3413 Py_INCREF(cb);
3414 self->set_hostname = cb;
3415 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3416 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3417 }
3418 Py_RETURN_NONE;
3419#else
3420 PyErr_SetString(PyExc_NotImplementedError,
3421 "The TLS extension servername callback, "
3422 "SSL_CTX_set_tlsext_servername_callback, "
3423 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003424 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003425#endif
3426}
3427
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003428/*[clinic input]
3429_ssl._SSLContext.cert_store_stats
3430
3431Returns quantities of loaded X.509 certificates.
3432
3433X.509 certificates with a CA extension and certificate revocation lists
3434inside the context's cert store.
3435
3436NOTE: Certificates in a capath directory aren't loaded unless they have
3437been used at least once.
3438[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003439
3440static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003441_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3442/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003443{
3444 X509_STORE *store;
3445 X509_OBJECT *obj;
3446 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3447
3448 store = SSL_CTX_get_cert_store(self->ctx);
3449 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3450 obj = sk_X509_OBJECT_value(store->objs, i);
3451 switch (obj->type) {
3452 case X509_LU_X509:
3453 x509++;
3454 if (X509_check_ca(obj->data.x509)) {
3455 ca++;
3456 }
3457 break;
3458 case X509_LU_CRL:
3459 crl++;
3460 break;
3461 case X509_LU_PKEY:
3462 pkey++;
3463 break;
3464 default:
3465 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3466 * As far as I can tell they are internal states and never
3467 * stored in a cert store */
3468 break;
3469 }
3470 }
3471 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3472 "x509_ca", ca);
3473}
3474
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003475/*[clinic input]
3476_ssl._SSLContext.get_ca_certs
3477 binary_form: bool = False
3478
3479Returns a list of dicts with information of loaded CA certs.
3480
3481If the optional argument is True, returns a DER-encoded copy of the CA
3482certificate.
3483
3484NOTE: Certificates in a capath directory aren't loaded unless they have
3485been used at least once.
3486[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003487
3488static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003489_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3490/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003491{
3492 X509_STORE *store;
3493 PyObject *ci = NULL, *rlist = NULL;
3494 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003495
3496 if ((rlist = PyList_New(0)) == NULL) {
3497 return NULL;
3498 }
3499
3500 store = SSL_CTX_get_cert_store(self->ctx);
3501 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3502 X509_OBJECT *obj;
3503 X509 *cert;
3504
3505 obj = sk_X509_OBJECT_value(store->objs, i);
3506 if (obj->type != X509_LU_X509) {
3507 /* not a x509 cert */
3508 continue;
3509 }
3510 /* CA for any purpose */
3511 cert = obj->data.x509;
3512 if (!X509_check_ca(cert)) {
3513 continue;
3514 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003515 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003516 ci = _certificate_to_der(cert);
3517 } else {
3518 ci = _decode_certificate(cert);
3519 }
3520 if (ci == NULL) {
3521 goto error;
3522 }
3523 if (PyList_Append(rlist, ci) == -1) {
3524 goto error;
3525 }
3526 Py_CLEAR(ci);
3527 }
3528 return rlist;
3529
3530 error:
3531 Py_XDECREF(ci);
3532 Py_XDECREF(rlist);
3533 return NULL;
3534}
3535
3536
Antoine Pitrou152efa22010-05-16 18:19:27 +00003537static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003538 {"check_hostname", (getter) get_check_hostname,
3539 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003540 {"options", (getter) get_options,
3541 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003542 {"verify_flags", (getter) get_verify_flags,
3543 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003544 {"verify_mode", (getter) get_verify_mode,
3545 (setter) set_verify_mode, NULL},
3546 {NULL}, /* sentinel */
3547};
3548
3549static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003550 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3551 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3552 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3553 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3554 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3555 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3556 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3557 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3558 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3559 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3560 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3561 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3562 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3563 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003564 {NULL, NULL} /* sentinel */
3565};
3566
3567static PyTypeObject PySSLContext_Type = {
3568 PyVarObject_HEAD_INIT(NULL, 0)
3569 "_ssl._SSLContext", /*tp_name*/
3570 sizeof(PySSLContext), /*tp_basicsize*/
3571 0, /*tp_itemsize*/
3572 (destructor)context_dealloc, /*tp_dealloc*/
3573 0, /*tp_print*/
3574 0, /*tp_getattr*/
3575 0, /*tp_setattr*/
3576 0, /*tp_reserved*/
3577 0, /*tp_repr*/
3578 0, /*tp_as_number*/
3579 0, /*tp_as_sequence*/
3580 0, /*tp_as_mapping*/
3581 0, /*tp_hash*/
3582 0, /*tp_call*/
3583 0, /*tp_str*/
3584 0, /*tp_getattro*/
3585 0, /*tp_setattro*/
3586 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003588 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003589 (traverseproc) context_traverse, /*tp_traverse*/
3590 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003591 0, /*tp_richcompare*/
3592 0, /*tp_weaklistoffset*/
3593 0, /*tp_iter*/
3594 0, /*tp_iternext*/
3595 context_methods, /*tp_methods*/
3596 0, /*tp_members*/
3597 context_getsetlist, /*tp_getset*/
3598 0, /*tp_base*/
3599 0, /*tp_dict*/
3600 0, /*tp_descr_get*/
3601 0, /*tp_descr_set*/
3602 0, /*tp_dictoffset*/
3603 0, /*tp_init*/
3604 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003605 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003606};
3607
3608
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003609/*
3610 * MemoryBIO objects
3611 */
3612
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003613/*[clinic input]
3614@classmethod
3615_ssl.MemoryBIO.__new__
3616
3617[clinic start generated code]*/
3618
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003619static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003620_ssl_MemoryBIO_impl(PyTypeObject *type)
3621/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003622{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003623 BIO *bio;
3624 PySSLMemoryBIO *self;
3625
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626 bio = BIO_new(BIO_s_mem());
3627 if (bio == NULL) {
3628 PyErr_SetString(PySSLErrorObject,
3629 "failed to allocate BIO");
3630 return NULL;
3631 }
3632 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3633 * just that no data is currently available. The SSL routines should retry
3634 * the read, which we can achieve by calling BIO_set_retry_read(). */
3635 BIO_set_retry_read(bio);
3636 BIO_set_mem_eof_return(bio, -1);
3637
3638 assert(type != NULL && type->tp_alloc != NULL);
3639 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3640 if (self == NULL) {
3641 BIO_free(bio);
3642 return NULL;
3643 }
3644 self->bio = bio;
3645 self->eof_written = 0;
3646
3647 return (PyObject *) self;
3648}
3649
3650static void
3651memory_bio_dealloc(PySSLMemoryBIO *self)
3652{
3653 BIO_free(self->bio);
3654 Py_TYPE(self)->tp_free(self);
3655}
3656
3657static PyObject *
3658memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3659{
3660 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3661}
3662
3663PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3664"The number of bytes pending in the memory BIO.");
3665
3666static PyObject *
3667memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3668{
3669 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3670 && self->eof_written);
3671}
3672
3673PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3674"Whether the memory BIO is at EOF.");
3675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003676/*[clinic input]
3677_ssl.MemoryBIO.read
3678 size as len: int = -1
3679 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003680
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003681Read up to size bytes from the memory BIO.
3682
3683If size is not specified, read the entire buffer.
3684If the return value is an empty bytes instance, this means either
3685EOF or that no data is available. Use the "eof" property to
3686distinguish between the two.
3687[clinic start generated code]*/
3688
3689static PyObject *
3690_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3691/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3692{
3693 int avail, nbytes;
3694 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003695
3696 avail = BIO_ctrl_pending(self->bio);
3697 if ((len < 0) || (len > avail))
3698 len = avail;
3699
3700 result = PyBytes_FromStringAndSize(NULL, len);
3701 if ((result == NULL) || (len == 0))
3702 return result;
3703
3704 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3705 /* There should never be any short reads but check anyway. */
3706 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3707 Py_DECREF(result);
3708 return NULL;
3709 }
3710
3711 return result;
3712}
3713
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003714/*[clinic input]
3715_ssl.MemoryBIO.write
3716 b: Py_buffer
3717 /
3718
3719Writes the bytes b into the memory BIO.
3720
3721Returns the number of bytes written.
3722[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003723
3724static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003725_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3726/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003727{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003728 int nbytes;
3729
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003730 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003731 PyErr_Format(PyExc_OverflowError,
3732 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003733 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003734 }
3735
3736 if (self->eof_written) {
3737 PyErr_SetString(PySSLErrorObject,
3738 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003739 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003740 }
3741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003742 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003743 if (nbytes < 0) {
3744 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003745 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003746 }
3747
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003748 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003749}
3750
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003751/*[clinic input]
3752_ssl.MemoryBIO.write_eof
3753
3754Write an EOF marker to the memory BIO.
3755
3756When all data has been read, the "eof" property will be True.
3757[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003758
3759static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003760_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3761/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003762{
3763 self->eof_written = 1;
3764 /* After an EOF is written, a zero return from read() should be a real EOF
3765 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3766 BIO_clear_retry_flags(self->bio);
3767 BIO_set_mem_eof_return(self->bio, 0);
3768
3769 Py_RETURN_NONE;
3770}
3771
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003772static PyGetSetDef memory_bio_getsetlist[] = {
3773 {"pending", (getter) memory_bio_get_pending, NULL,
3774 PySSL_memory_bio_pending_doc},
3775 {"eof", (getter) memory_bio_get_eof, NULL,
3776 PySSL_memory_bio_eof_doc},
3777 {NULL}, /* sentinel */
3778};
3779
3780static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003781 _SSL_MEMORYBIO_READ_METHODDEF
3782 _SSL_MEMORYBIO_WRITE_METHODDEF
3783 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003784 {NULL, NULL} /* sentinel */
3785};
3786
3787static PyTypeObject PySSLMemoryBIO_Type = {
3788 PyVarObject_HEAD_INIT(NULL, 0)
3789 "_ssl.MemoryBIO", /*tp_name*/
3790 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3791 0, /*tp_itemsize*/
3792 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3793 0, /*tp_print*/
3794 0, /*tp_getattr*/
3795 0, /*tp_setattr*/
3796 0, /*tp_reserved*/
3797 0, /*tp_repr*/
3798 0, /*tp_as_number*/
3799 0, /*tp_as_sequence*/
3800 0, /*tp_as_mapping*/
3801 0, /*tp_hash*/
3802 0, /*tp_call*/
3803 0, /*tp_str*/
3804 0, /*tp_getattro*/
3805 0, /*tp_setattro*/
3806 0, /*tp_as_buffer*/
3807 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3808 0, /*tp_doc*/
3809 0, /*tp_traverse*/
3810 0, /*tp_clear*/
3811 0, /*tp_richcompare*/
3812 0, /*tp_weaklistoffset*/
3813 0, /*tp_iter*/
3814 0, /*tp_iternext*/
3815 memory_bio_methods, /*tp_methods*/
3816 0, /*tp_members*/
3817 memory_bio_getsetlist, /*tp_getset*/
3818 0, /*tp_base*/
3819 0, /*tp_dict*/
3820 0, /*tp_descr_get*/
3821 0, /*tp_descr_set*/
3822 0, /*tp_dictoffset*/
3823 0, /*tp_init*/
3824 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003825 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003826};
3827
Antoine Pitrou152efa22010-05-16 18:19:27 +00003828
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003829/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003830/*[clinic input]
3831_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003832 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003833 entropy: double
3834 /
3835
3836Mix string into the OpenSSL PRNG state.
3837
3838entropy (a float) is a lower bound on the entropy contained in
3839string. See RFC 1750.
3840[clinic start generated code]*/
3841
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003842static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003843_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
3844/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003845{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003846 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003847 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003848
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003849 buf = (const char *)view->buf;
3850 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003851 do {
3852 written = Py_MIN(len, INT_MAX);
3853 RAND_add(buf, (int)written, entropy);
3854 buf += written;
3855 len -= written;
3856 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003857 Py_INCREF(Py_None);
3858 return Py_None;
3859}
3860
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003861static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003862PySSL_RAND(int len, int pseudo)
3863{
3864 int ok;
3865 PyObject *bytes;
3866 unsigned long err;
3867 const char *errstr;
3868 PyObject *v;
3869
Victor Stinner1e81a392013-12-19 16:47:04 +01003870 if (len < 0) {
3871 PyErr_SetString(PyExc_ValueError, "num must be positive");
3872 return NULL;
3873 }
3874
Victor Stinner99c8b162011-05-24 12:05:19 +02003875 bytes = PyBytes_FromStringAndSize(NULL, len);
3876 if (bytes == NULL)
3877 return NULL;
3878 if (pseudo) {
3879 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3880 if (ok == 0 || ok == 1)
3881 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3882 }
3883 else {
3884 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3885 if (ok == 1)
3886 return bytes;
3887 }
3888 Py_DECREF(bytes);
3889
3890 err = ERR_get_error();
3891 errstr = ERR_reason_error_string(err);
3892 v = Py_BuildValue("(ks)", err, errstr);
3893 if (v != NULL) {
3894 PyErr_SetObject(PySSLErrorObject, v);
3895 Py_DECREF(v);
3896 }
3897 return NULL;
3898}
3899
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003900/*[clinic input]
3901_ssl.RAND_bytes
3902 n: int
3903 /
3904
3905Generate n cryptographically strong pseudo-random bytes.
3906[clinic start generated code]*/
3907
Victor Stinner99c8b162011-05-24 12:05:19 +02003908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003909_ssl_RAND_bytes_impl(PyObject *module, int n)
3910/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003911{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003912 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003913}
3914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003915/*[clinic input]
3916_ssl.RAND_pseudo_bytes
3917 n: int
3918 /
3919
3920Generate n pseudo-random bytes.
3921
3922Return a pair (bytes, is_cryptographic). is_cryptographic is True
3923if the bytes generated are cryptographically strong.
3924[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003925
3926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003927_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
3928/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003929{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003930 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003931}
3932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003933/*[clinic input]
3934_ssl.RAND_status
3935
3936Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3937
3938It is necessary to seed the PRNG with RAND_add() on some platforms before
3939using the ssl() function.
3940[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003941
3942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003943_ssl_RAND_status_impl(PyObject *module)
3944/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003945{
Christian Heimes217cfd12007-12-02 14:31:20 +00003946 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003947}
3948
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003949#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003950/*[clinic input]
3951_ssl.RAND_egd
3952 path: object(converter="PyUnicode_FSConverter")
3953 /
3954
3955Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3956
3957Returns number of bytes read. Raises SSLError if connection to EGD
3958fails or if it does not provide enough data to seed PRNG.
3959[clinic start generated code]*/
3960
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003961static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003962_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
3963/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003964{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003966 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003967 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003968 PyErr_SetString(PySSLErrorObject,
3969 "EGD connection failed or EGD did not return "
3970 "enough data to seed the PRNG");
3971 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003972 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003973 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003974}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003975#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003976
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003977
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978
3979/*[clinic input]
3980_ssl.get_default_verify_paths
3981
3982Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3983
3984The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3985[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003986
3987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003988_ssl_get_default_verify_paths_impl(PyObject *module)
3989/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003990{
3991 PyObject *ofile_env = NULL;
3992 PyObject *ofile = NULL;
3993 PyObject *odir_env = NULL;
3994 PyObject *odir = NULL;
3995
Benjamin Petersond113c962015-07-18 10:59:13 -07003996#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003997 const char *tmp = (info); \
3998 target = NULL; \
3999 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4000 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4001 target = PyBytes_FromString(tmp); } \
4002 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004003 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004004
Benjamin Petersond113c962015-07-18 10:59:13 -07004005 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4006 CONVERT(X509_get_default_cert_file(), ofile);
4007 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4008 CONVERT(X509_get_default_cert_dir(), odir);
4009#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004010
Christian Heimes200bb1b2013-06-14 15:14:29 +02004011 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004012
4013 error:
4014 Py_XDECREF(ofile_env);
4015 Py_XDECREF(ofile);
4016 Py_XDECREF(odir_env);
4017 Py_XDECREF(odir);
4018 return NULL;
4019}
4020
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004021static PyObject*
4022asn1obj2py(ASN1_OBJECT *obj)
4023{
4024 int nid;
4025 const char *ln, *sn;
4026 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004027 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004028
4029 nid = OBJ_obj2nid(obj);
4030 if (nid == NID_undef) {
4031 PyErr_Format(PyExc_ValueError, "Unknown object");
4032 return NULL;
4033 }
4034 sn = OBJ_nid2sn(nid);
4035 ln = OBJ_nid2ln(nid);
4036 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4037 if (buflen < 0) {
4038 _setSSLError(NULL, 0, __FILE__, __LINE__);
4039 return NULL;
4040 }
4041 if (buflen) {
4042 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4043 } else {
4044 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4045 }
4046}
4047
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004048/*[clinic input]
4049_ssl.txt2obj
4050 txt: str
4051 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004052
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004053Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4054
4055By default objects are looked up by OID. With name=True short and
4056long name are also matched.
4057[clinic start generated code]*/
4058
4059static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004060_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4061/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004062{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004063 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004064 ASN1_OBJECT *obj;
4065
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004066 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4067 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004068 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004069 return NULL;
4070 }
4071 result = asn1obj2py(obj);
4072 ASN1_OBJECT_free(obj);
4073 return result;
4074}
4075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076/*[clinic input]
4077_ssl.nid2obj
4078 nid: int
4079 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004081Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4082[clinic start generated code]*/
4083
4084static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004085_ssl_nid2obj_impl(PyObject *module, int nid)
4086/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004087{
4088 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004089 ASN1_OBJECT *obj;
4090
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004091 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004092 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004093 return NULL;
4094 }
4095 obj = OBJ_nid2obj(nid);
4096 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004097 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004098 return NULL;
4099 }
4100 result = asn1obj2py(obj);
4101 ASN1_OBJECT_free(obj);
4102 return result;
4103}
4104
Christian Heimes46bebee2013-06-09 19:03:31 +02004105#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004106
4107static PyObject*
4108certEncodingType(DWORD encodingType)
4109{
4110 static PyObject *x509_asn = NULL;
4111 static PyObject *pkcs_7_asn = NULL;
4112
4113 if (x509_asn == NULL) {
4114 x509_asn = PyUnicode_InternFromString("x509_asn");
4115 if (x509_asn == NULL)
4116 return NULL;
4117 }
4118 if (pkcs_7_asn == NULL) {
4119 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4120 if (pkcs_7_asn == NULL)
4121 return NULL;
4122 }
4123 switch(encodingType) {
4124 case X509_ASN_ENCODING:
4125 Py_INCREF(x509_asn);
4126 return x509_asn;
4127 case PKCS_7_ASN_ENCODING:
4128 Py_INCREF(pkcs_7_asn);
4129 return pkcs_7_asn;
4130 default:
4131 return PyLong_FromLong(encodingType);
4132 }
4133}
4134
4135static PyObject*
4136parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4137{
4138 CERT_ENHKEY_USAGE *usage;
4139 DWORD size, error, i;
4140 PyObject *retval;
4141
4142 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4143 error = GetLastError();
4144 if (error == CRYPT_E_NOT_FOUND) {
4145 Py_RETURN_TRUE;
4146 }
4147 return PyErr_SetFromWindowsErr(error);
4148 }
4149
4150 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4151 if (usage == NULL) {
4152 return PyErr_NoMemory();
4153 }
4154
4155 /* Now get the actual enhanced usage property */
4156 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4157 PyMem_Free(usage);
4158 error = GetLastError();
4159 if (error == CRYPT_E_NOT_FOUND) {
4160 Py_RETURN_TRUE;
4161 }
4162 return PyErr_SetFromWindowsErr(error);
4163 }
4164 retval = PySet_New(NULL);
4165 if (retval == NULL) {
4166 goto error;
4167 }
4168 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4169 if (usage->rgpszUsageIdentifier[i]) {
4170 PyObject *oid;
4171 int err;
4172 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4173 if (oid == NULL) {
4174 Py_CLEAR(retval);
4175 goto error;
4176 }
4177 err = PySet_Add(retval, oid);
4178 Py_DECREF(oid);
4179 if (err == -1) {
4180 Py_CLEAR(retval);
4181 goto error;
4182 }
4183 }
4184 }
4185 error:
4186 PyMem_Free(usage);
4187 return retval;
4188}
4189
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004190/*[clinic input]
4191_ssl.enum_certificates
4192 store_name: str
4193
4194Retrieve certificates from Windows' cert store.
4195
4196store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4197more cert storages, too. The function returns a list of (bytes,
4198encoding_type, trust) tuples. The encoding_type flag can be interpreted
4199with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4200a set of OIDs or the boolean True.
4201[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004202
Christian Heimes46bebee2013-06-09 19:03:31 +02004203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004204_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4205/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004206{
Christian Heimes46bebee2013-06-09 19:03:31 +02004207 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004208 PCCERT_CONTEXT pCertCtx = NULL;
4209 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004210 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004211
Christian Heimes44109d72013-11-22 01:51:30 +01004212 result = PyList_New(0);
4213 if (result == NULL) {
4214 return NULL;
4215 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004216 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4217 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4218 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004219 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004220 Py_DECREF(result);
4221 return PyErr_SetFromWindowsErr(GetLastError());
4222 }
4223
Christian Heimes44109d72013-11-22 01:51:30 +01004224 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4225 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4226 pCertCtx->cbCertEncoded);
4227 if (!cert) {
4228 Py_CLEAR(result);
4229 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004230 }
Christian Heimes44109d72013-11-22 01:51:30 +01004231 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4232 Py_CLEAR(result);
4233 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004234 }
Christian Heimes44109d72013-11-22 01:51:30 +01004235 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4236 if (keyusage == Py_True) {
4237 Py_DECREF(keyusage);
4238 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004239 }
Christian Heimes44109d72013-11-22 01:51:30 +01004240 if (keyusage == NULL) {
4241 Py_CLEAR(result);
4242 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004243 }
Christian Heimes44109d72013-11-22 01:51:30 +01004244 if ((tup = PyTuple_New(3)) == NULL) {
4245 Py_CLEAR(result);
4246 break;
4247 }
4248 PyTuple_SET_ITEM(tup, 0, cert);
4249 cert = NULL;
4250 PyTuple_SET_ITEM(tup, 1, enc);
4251 enc = NULL;
4252 PyTuple_SET_ITEM(tup, 2, keyusage);
4253 keyusage = NULL;
4254 if (PyList_Append(result, tup) < 0) {
4255 Py_CLEAR(result);
4256 break;
4257 }
4258 Py_CLEAR(tup);
4259 }
4260 if (pCertCtx) {
4261 /* loop ended with an error, need to clean up context manually */
4262 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004263 }
4264
4265 /* In error cases cert, enc and tup may not be NULL */
4266 Py_XDECREF(cert);
4267 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004268 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004269 Py_XDECREF(tup);
4270
4271 if (!CertCloseStore(hStore, 0)) {
4272 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004273 Py_XDECREF(result);
4274 return PyErr_SetFromWindowsErr(GetLastError());
4275 }
4276 return result;
4277}
4278
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004279/*[clinic input]
4280_ssl.enum_crls
4281 store_name: str
4282
4283Retrieve CRLs from Windows' cert store.
4284
4285store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4286more cert storages, too. The function returns a list of (bytes,
4287encoding_type) tuples. The encoding_type flag can be interpreted with
4288X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4289[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004290
4291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004292_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4293/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004294{
Christian Heimes44109d72013-11-22 01:51:30 +01004295 HCERTSTORE hStore = NULL;
4296 PCCRL_CONTEXT pCrlCtx = NULL;
4297 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4298 PyObject *result = NULL;
4299
Christian Heimes44109d72013-11-22 01:51:30 +01004300 result = PyList_New(0);
4301 if (result == NULL) {
4302 return NULL;
4303 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004304 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4305 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4306 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004307 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004308 Py_DECREF(result);
4309 return PyErr_SetFromWindowsErr(GetLastError());
4310 }
Christian Heimes44109d72013-11-22 01:51:30 +01004311
4312 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4313 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4314 pCrlCtx->cbCrlEncoded);
4315 if (!crl) {
4316 Py_CLEAR(result);
4317 break;
4318 }
4319 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4320 Py_CLEAR(result);
4321 break;
4322 }
4323 if ((tup = PyTuple_New(2)) == NULL) {
4324 Py_CLEAR(result);
4325 break;
4326 }
4327 PyTuple_SET_ITEM(tup, 0, crl);
4328 crl = NULL;
4329 PyTuple_SET_ITEM(tup, 1, enc);
4330 enc = NULL;
4331
4332 if (PyList_Append(result, tup) < 0) {
4333 Py_CLEAR(result);
4334 break;
4335 }
4336 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004337 }
Christian Heimes44109d72013-11-22 01:51:30 +01004338 if (pCrlCtx) {
4339 /* loop ended with an error, need to clean up context manually */
4340 CertFreeCRLContext(pCrlCtx);
4341 }
4342
4343 /* In error cases cert, enc and tup may not be NULL */
4344 Py_XDECREF(crl);
4345 Py_XDECREF(enc);
4346 Py_XDECREF(tup);
4347
4348 if (!CertCloseStore(hStore, 0)) {
4349 /* This error case might shadow another exception.*/
4350 Py_XDECREF(result);
4351 return PyErr_SetFromWindowsErr(GetLastError());
4352 }
4353 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004354}
Christian Heimes44109d72013-11-22 01:51:30 +01004355
4356#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004357
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004358/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004359static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004360 _SSL__TEST_DECODE_CERT_METHODDEF
4361 _SSL_RAND_ADD_METHODDEF
4362 _SSL_RAND_BYTES_METHODDEF
4363 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4364 _SSL_RAND_EGD_METHODDEF
4365 _SSL_RAND_STATUS_METHODDEF
4366 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4367 _SSL_ENUM_CERTIFICATES_METHODDEF
4368 _SSL_ENUM_CRLS_METHODDEF
4369 _SSL_TXT2OBJ_METHODDEF
4370 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004371 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004372};
4373
4374
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375#ifdef WITH_THREAD
4376
4377/* an implementation of OpenSSL threading operations in terms
4378 of the Python C thread library */
4379
4380static PyThread_type_lock *_ssl_locks = NULL;
4381
Christian Heimes4d98ca92013-08-19 17:36:29 +02004382#if OPENSSL_VERSION_NUMBER >= 0x10000000
4383/* use new CRYPTO_THREADID API. */
4384static void
4385_ssl_threadid_callback(CRYPTO_THREADID *id)
4386{
4387 CRYPTO_THREADID_set_numeric(id,
4388 (unsigned long)PyThread_get_thread_ident());
4389}
4390#else
4391/* deprecated CRYPTO_set_id_callback() API. */
4392static unsigned long
4393_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004394 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004395}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004396#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397
Bill Janssen6e027db2007-11-15 22:23:56 +00004398static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004399 (int mode, int n, const char *file, int line) {
4400 /* this function is needed to perform locking on shared data
4401 structures. (Note that OpenSSL uses a number of global data
4402 structures that will be implicitly shared whenever multiple
4403 threads use OpenSSL.) Multi-threaded applications will
4404 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004406 locking_function() must be able to handle up to
4407 CRYPTO_num_locks() different mutex locks. It sets the n-th
4408 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004410 file and line are the file number of the function setting the
4411 lock. They can be useful for debugging.
4412 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004414 if ((_ssl_locks == NULL) ||
4415 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4416 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004418 if (mode & CRYPTO_LOCK) {
4419 PyThread_acquire_lock(_ssl_locks[n], 1);
4420 } else {
4421 PyThread_release_lock(_ssl_locks[n]);
4422 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423}
4424
4425static int _setup_ssl_threads(void) {
4426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004427 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004428
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004429 if (_ssl_locks == NULL) {
4430 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004431 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4432 if (_ssl_locks == NULL) {
4433 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004434 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004435 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004436 memset(_ssl_locks, 0,
4437 sizeof(PyThread_type_lock) * _ssl_locks_count);
4438 for (i = 0; i < _ssl_locks_count; i++) {
4439 _ssl_locks[i] = PyThread_allocate_lock();
4440 if (_ssl_locks[i] == NULL) {
4441 unsigned int j;
4442 for (j = 0; j < i; j++) {
4443 PyThread_free_lock(_ssl_locks[j]);
4444 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004445 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004446 return 0;
4447 }
4448 }
4449 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004450#if OPENSSL_VERSION_NUMBER >= 0x10000000
4451 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4452#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004453 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004454#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004455 }
4456 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004457}
4458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004459#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004461PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004462"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004463for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004464
Martin v. Löwis1a214512008-06-11 05:26:20 +00004465
4466static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004467 PyModuleDef_HEAD_INIT,
4468 "_ssl",
4469 module_doc,
4470 -1,
4471 PySSL_methods,
4472 NULL,
4473 NULL,
4474 NULL,
4475 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004476};
4477
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004478
4479static void
4480parse_openssl_version(unsigned long libver,
4481 unsigned int *major, unsigned int *minor,
4482 unsigned int *fix, unsigned int *patch,
4483 unsigned int *status)
4484{
4485 *status = libver & 0xF;
4486 libver >>= 4;
4487 *patch = libver & 0xFF;
4488 libver >>= 8;
4489 *fix = libver & 0xFF;
4490 libver >>= 8;
4491 *minor = libver & 0xFF;
4492 libver >>= 8;
4493 *major = libver & 0xFF;
4494}
4495
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004496PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004497PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004498{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004499 PyObject *m, *d, *r;
4500 unsigned long libver;
4501 unsigned int major, minor, fix, patch, status;
4502 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004503 struct py_ssl_error_code *errcode;
4504 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004505
Antoine Pitrou152efa22010-05-16 18:19:27 +00004506 if (PyType_Ready(&PySSLContext_Type) < 0)
4507 return NULL;
4508 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004509 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004510 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4511 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004513 m = PyModule_Create(&_sslmodule);
4514 if (m == NULL)
4515 return NULL;
4516 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004518 /* Load _socket module and its C API */
4519 socket_api = PySocketModule_ImportModuleAndAPI();
4520 if (!socket_api)
4521 return NULL;
4522 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004524 /* Init OpenSSL */
4525 SSL_load_error_strings();
4526 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004527#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004528 /* note that this will start threading if not already started */
4529 if (!_setup_ssl_threads()) {
4530 return NULL;
4531 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004532#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004533 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004535 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004536 sslerror_type_slots[0].pfunc = PyExc_OSError;
4537 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004538 if (PySSLErrorObject == NULL)
4539 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004540
Antoine Pitrou41032a62011-10-27 23:56:55 +02004541 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4542 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4543 PySSLErrorObject, NULL);
4544 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4545 "ssl.SSLWantReadError", SSLWantReadError_doc,
4546 PySSLErrorObject, NULL);
4547 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4548 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4549 PySSLErrorObject, NULL);
4550 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4551 "ssl.SSLSyscallError", SSLSyscallError_doc,
4552 PySSLErrorObject, NULL);
4553 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4554 "ssl.SSLEOFError", SSLEOFError_doc,
4555 PySSLErrorObject, NULL);
4556 if (PySSLZeroReturnErrorObject == NULL
4557 || PySSLWantReadErrorObject == NULL
4558 || PySSLWantWriteErrorObject == NULL
4559 || PySSLSyscallErrorObject == NULL
4560 || PySSLEOFErrorObject == NULL)
4561 return NULL;
4562 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4563 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4564 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4565 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4566 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4567 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004568 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004569 if (PyDict_SetItemString(d, "_SSLContext",
4570 (PyObject *)&PySSLContext_Type) != 0)
4571 return NULL;
4572 if (PyDict_SetItemString(d, "_SSLSocket",
4573 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004574 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004575 if (PyDict_SetItemString(d, "MemoryBIO",
4576 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4577 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004578 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4579 PY_SSL_ERROR_ZERO_RETURN);
4580 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4581 PY_SSL_ERROR_WANT_READ);
4582 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4583 PY_SSL_ERROR_WANT_WRITE);
4584 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4585 PY_SSL_ERROR_WANT_X509_LOOKUP);
4586 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4587 PY_SSL_ERROR_SYSCALL);
4588 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4589 PY_SSL_ERROR_SSL);
4590 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4591 PY_SSL_ERROR_WANT_CONNECT);
4592 /* non ssl.h errorcodes */
4593 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4594 PY_SSL_ERROR_EOF);
4595 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4596 PY_SSL_ERROR_INVALID_ERROR_CODE);
4597 /* cert requirements */
4598 PyModule_AddIntConstant(m, "CERT_NONE",
4599 PY_SSL_CERT_NONE);
4600 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4601 PY_SSL_CERT_OPTIONAL);
4602 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4603 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004604 /* CRL verification for verification_flags */
4605 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4606 0);
4607 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4608 X509_V_FLAG_CRL_CHECK);
4609 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4610 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4611 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4612 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004613#ifdef X509_V_FLAG_TRUSTED_FIRST
4614 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4615 X509_V_FLAG_TRUSTED_FIRST);
4616#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004617
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004618 /* Alert Descriptions from ssl.h */
4619 /* note RESERVED constants no longer intended for use have been removed */
4620 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4621
4622#define ADD_AD_CONSTANT(s) \
4623 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4624 SSL_AD_##s)
4625
4626 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4627 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4628 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4629 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4630 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4631 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4632 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4633 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4634 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4635 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4636 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4637 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4638 ADD_AD_CONSTANT(UNKNOWN_CA);
4639 ADD_AD_CONSTANT(ACCESS_DENIED);
4640 ADD_AD_CONSTANT(DECODE_ERROR);
4641 ADD_AD_CONSTANT(DECRYPT_ERROR);
4642 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4643 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4644 ADD_AD_CONSTANT(INTERNAL_ERROR);
4645 ADD_AD_CONSTANT(USER_CANCELLED);
4646 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004647 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004648#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4649 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4650#endif
4651#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4652 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4653#endif
4654#ifdef SSL_AD_UNRECOGNIZED_NAME
4655 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4656#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004657#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4658 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4659#endif
4660#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4661 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4662#endif
4663#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4664 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4665#endif
4666
4667#undef ADD_AD_CONSTANT
4668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004669 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004670#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004671 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4672 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004673#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004674#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004675 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4676 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004677#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004678 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4679 PY_SSL_VERSION_SSL23);
4680 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4681 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004682#if HAVE_TLSv1_2
4683 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4684 PY_SSL_VERSION_TLS1_1);
4685 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4686 PY_SSL_VERSION_TLS1_2);
4687#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004688
Antoine Pitroub5218772010-05-21 09:56:06 +00004689 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004690 PyModule_AddIntConstant(m, "OP_ALL",
4691 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004692 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4693 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4694 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004695#if HAVE_TLSv1_2
4696 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4697 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4698#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004699 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4700 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004701 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004702#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004703 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004704#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004705#ifdef SSL_OP_NO_COMPRESSION
4706 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4707 SSL_OP_NO_COMPRESSION);
4708#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004709
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004710#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004711 r = Py_True;
4712#else
4713 r = Py_False;
4714#endif
4715 Py_INCREF(r);
4716 PyModule_AddObject(m, "HAS_SNI", r);
4717
Antoine Pitroud6494802011-07-21 01:11:30 +02004718 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004719 Py_INCREF(r);
4720 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4721
Antoine Pitrou501da612011-12-21 09:27:41 +01004722#ifdef OPENSSL_NO_ECDH
4723 r = Py_False;
4724#else
4725 r = Py_True;
4726#endif
4727 Py_INCREF(r);
4728 PyModule_AddObject(m, "HAS_ECDH", r);
4729
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004730#ifdef OPENSSL_NPN_NEGOTIATED
4731 r = Py_True;
4732#else
4733 r = Py_False;
4734#endif
4735 Py_INCREF(r);
4736 PyModule_AddObject(m, "HAS_NPN", r);
4737
Benjamin Petersoncca27322015-01-23 16:35:37 -05004738#ifdef HAVE_ALPN
4739 r = Py_True;
4740#else
4741 r = Py_False;
4742#endif
4743 Py_INCREF(r);
4744 PyModule_AddObject(m, "HAS_ALPN", r);
4745
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004746 /* Mappings for error codes */
4747 err_codes_to_names = PyDict_New();
4748 err_names_to_codes = PyDict_New();
4749 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4750 return NULL;
4751 errcode = error_codes;
4752 while (errcode->mnemonic != NULL) {
4753 PyObject *mnemo, *key;
4754 mnemo = PyUnicode_FromString(errcode->mnemonic);
4755 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4756 if (mnemo == NULL || key == NULL)
4757 return NULL;
4758 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4759 return NULL;
4760 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4761 return NULL;
4762 Py_DECREF(key);
4763 Py_DECREF(mnemo);
4764 errcode++;
4765 }
4766 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4767 return NULL;
4768 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4769 return NULL;
4770
4771 lib_codes_to_names = PyDict_New();
4772 if (lib_codes_to_names == NULL)
4773 return NULL;
4774 libcode = library_codes;
4775 while (libcode->library != NULL) {
4776 PyObject *mnemo, *key;
4777 key = PyLong_FromLong(libcode->code);
4778 mnemo = PyUnicode_FromString(libcode->library);
4779 if (key == NULL || mnemo == NULL)
4780 return NULL;
4781 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4782 return NULL;
4783 Py_DECREF(key);
4784 Py_DECREF(mnemo);
4785 libcode++;
4786 }
4787 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4788 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004790 /* OpenSSL version */
4791 /* SSLeay() gives us the version of the library linked against,
4792 which could be different from the headers version.
4793 */
4794 libver = SSLeay();
4795 r = PyLong_FromUnsignedLong(libver);
4796 if (r == NULL)
4797 return NULL;
4798 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4799 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004800 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004801 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4802 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4803 return NULL;
4804 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4805 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4806 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004807
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004808 libver = OPENSSL_VERSION_NUMBER;
4809 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4810 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4811 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4812 return NULL;
4813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004814 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004815}