blob: 67402fe0a4c72c814e84547c3fef16802861e03d [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 *
1324_ssl__test_decode_cert_impl(PyModuleDef *module, PyObject *path)
1325/*[clinic end generated code: output=679e01db282804e9 input=cdeaaf02d4346628]*/
1326{
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);
1592 Py_DECREF(self->ctx);
1593 self->ctx = (PySSLContext *) value;
1594 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001595#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001596 } else {
1597 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1598 return -1;
1599 }
1600
1601 return 0;
1602}
1603
1604PyDoc_STRVAR(PySSL_set_context_doc,
1605"_setter_context(ctx)\n\
1606\
1607This changes the context associated with the SSLSocket. This is typically\n\
1608used from within a callback function set by the set_servername_callback\n\
1609on the SSLContext to change the certificate information associated with the\n\
1610SSLSocket before the cryptographic exchange handshake messages\n");
1611
1612
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001613static PyObject *
1614PySSL_get_server_side(PySSLSocket *self, void *c)
1615{
1616 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1617}
1618
1619PyDoc_STRVAR(PySSL_get_server_side_doc,
1620"Whether this is a server-side socket.");
1621
1622static PyObject *
1623PySSL_get_server_hostname(PySSLSocket *self, void *c)
1624{
1625 if (self->server_hostname == NULL)
1626 Py_RETURN_NONE;
1627 Py_INCREF(self->server_hostname);
1628 return self->server_hostname;
1629}
1630
1631PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1632"The currently set server hostname (for SNI).");
1633
1634static PyObject *
1635PySSL_get_owner(PySSLSocket *self, void *c)
1636{
1637 PyObject *owner;
1638
1639 if (self->owner == NULL)
1640 Py_RETURN_NONE;
1641
1642 owner = PyWeakref_GetObject(self->owner);
1643 Py_INCREF(owner);
1644 return owner;
1645}
1646
1647static int
1648PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1649{
1650 Py_XDECREF(self->owner);
1651 self->owner = PyWeakref_NewRef(value, NULL);
1652 if (self->owner == NULL)
1653 return -1;
1654 return 0;
1655}
1656
1657PyDoc_STRVAR(PySSL_get_owner_doc,
1658"The Python-level owner of this object.\
1659Passed as \"self\" in servername callback.");
1660
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001661
Antoine Pitrou152efa22010-05-16 18:19:27 +00001662static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 if (self->peer_cert) /* Possible not to have one? */
1665 X509_free (self->peer_cert);
1666 if (self->ssl)
1667 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001669 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001670 Py_XDECREF(self->server_hostname);
1671 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001673}
1674
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001677 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001678 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001679
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001680static int
Victor Stinner14690702015-04-06 22:46:13 +02001681PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001682{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001683 int rc;
1684#ifdef HAVE_POLL
1685 struct pollfd pollfd;
1686 _PyTime_t ms;
1687#else
1688 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 fd_set fds;
1690 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001691#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001694 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001696 else if (timeout < 0) {
1697 if (s->sock_timeout > 0)
1698 return SOCKET_HAS_TIMED_OUT;
1699 else
1700 return SOCKET_IS_BLOCKING;
1701 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 /* Guard against closed socket */
1704 if (s->sock_fd < 0)
1705 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 /* Prefer poll, if available, since you can poll() any fd
1708 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001709#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001710 pollfd.fd = s->sock_fd;
1711 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001712
Victor Stinner14690702015-04-06 22:46:13 +02001713 /* timeout is in seconds, poll() uses milliseconds */
1714 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001715 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001716
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001717 PySSL_BEGIN_ALLOW_THREADS
1718 rc = poll(&pollfd, 1, (int)ms);
1719 PySSL_END_ALLOW_THREADS
1720#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001722 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001724
Victor Stinner14690702015-04-06 22:46:13 +02001725 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 FD_ZERO(&fds);
1728 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001729
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001730 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001731 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001732 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001734 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001736 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001738#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1741 (when we are able to write or when there's something to read) */
1742 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001743}
1744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745/*[clinic input]
1746_ssl._SSLSocket.write
1747 b: Py_buffer
1748 /
1749
1750Writes the bytes-like object b into the SSL object.
1751
1752Returns the number of bytes written.
1753[clinic start generated code]*/
1754
1755static PyObject *
1756_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1757/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 int len;
1760 int sockstate;
1761 int err;
1762 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001763 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001764 _PyTime_t timeout, deadline = 0;
1765 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001766
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001767 if (sock != NULL) {
1768 if (((PyObject*)sock) == Py_None) {
1769 _setSSLError("Underlying socket connection gone",
1770 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1771 return NULL;
1772 }
1773 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 }
1775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001776 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001777 PyErr_Format(PyExc_OverflowError,
1778 "string longer than %d bytes", INT_MAX);
1779 goto error;
1780 }
1781
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001782 if (sock != NULL) {
1783 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001784 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001785 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1786 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1787 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788
Victor Stinner14690702015-04-06 22:46:13 +02001789 timeout = GET_SOCKET_TIMEOUT(sock);
1790 has_timeout = (timeout > 0);
1791 if (has_timeout)
1792 deadline = _PyTime_GetMonotonicClock() + timeout;
1793
1794 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001796 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 "The write operation timed out");
1798 goto error;
1799 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1800 PyErr_SetString(PySSLErrorObject,
1801 "Underlying socket has been closed.");
1802 goto error;
1803 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1804 PyErr_SetString(PySSLErrorObject,
1805 "Underlying socket too large for select().");
1806 goto error;
1807 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001811 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 err = SSL_get_error(self->ssl, len);
1813 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001814
1815 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001816 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001817
Victor Stinner14690702015-04-06 22:46:13 +02001818 if (has_timeout)
1819 timeout = deadline - _PyTime_GetMonotonicClock();
1820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001822 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001824 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 } else {
1826 sockstate = SOCKET_OPERATION_OK;
1827 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001830 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 "The write operation timed out");
1832 goto error;
1833 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1834 PyErr_SetString(PySSLErrorObject,
1835 "Underlying socket has been closed.");
1836 goto error;
1837 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1838 break;
1839 }
1840 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001842 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 if (len > 0)
1844 return PyLong_FromLong(len);
1845 else
1846 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001847
1848error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001849 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001851}
1852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001853/*[clinic input]
1854_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001855
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001856Returns the number of already decrypted bytes available for read, pending on the connection.
1857[clinic start generated code]*/
1858
1859static PyObject *
1860_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1861/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001862{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 PySSL_BEGIN_ALLOW_THREADS
1866 count = SSL_pending(self->ssl);
1867 PySSL_END_ALLOW_THREADS
1868 if (count < 0)
1869 return PySSL_SetError(self, count, __FILE__, __LINE__);
1870 else
1871 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001872}
1873
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001874/*[clinic input]
1875_ssl._SSLSocket.read
1876 size as len: int
1877 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001878 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879 ]
1880 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001882Read up to size bytes from the SSL socket.
1883[clinic start generated code]*/
1884
1885static PyObject *
1886_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1887 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001888/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001889{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001892 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 int sockstate;
1894 int err;
1895 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001896 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001897 _PyTime_t timeout, deadline = 0;
1898 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001899
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001900 if (sock != NULL) {
1901 if (((PyObject*)sock) == Py_None) {
1902 _setSSLError("Underlying socket connection gone",
1903 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1904 return NULL;
1905 }
1906 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 }
1908
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001909 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001910 dest = PyBytes_FromStringAndSize(NULL, len);
1911 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001912 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001913 mem = PyBytes_AS_STRING(dest);
1914 }
1915 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001916 mem = buffer->buf;
1917 if (len <= 0 || len > buffer->len) {
1918 len = (int) buffer->len;
1919 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001920 PyErr_SetString(PyExc_OverflowError,
1921 "maximum length can't fit in a C 'int'");
1922 goto error;
1923 }
1924 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 }
1926
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001927 if (sock != NULL) {
1928 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001929 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001930 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1931 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1932 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933
Victor Stinner14690702015-04-06 22:46:13 +02001934 timeout = GET_SOCKET_TIMEOUT(sock);
1935 has_timeout = (timeout > 0);
1936 if (has_timeout)
1937 deadline = _PyTime_GetMonotonicClock() + timeout;
1938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 PySSL_BEGIN_ALLOW_THREADS
1941 count = SSL_read(self->ssl, mem, len);
1942 err = SSL_get_error(self->ssl, count);
1943 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 if (PyErr_CheckSignals())
1946 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001947
Victor Stinner14690702015-04-06 22:46:13 +02001948 if (has_timeout)
1949 timeout = deadline - _PyTime_GetMonotonicClock();
1950
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001952 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001954 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001955 } else if (err == SSL_ERROR_ZERO_RETURN &&
1956 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 {
1958 count = 0;
1959 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001961 else
1962 sockstate = SOCKET_OPERATION_OK;
1963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001965 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 "The read operation timed out");
1967 goto error;
1968 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1969 break;
1970 }
1971 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 if (count <= 0) {
1974 PySSL_SetError(self, count, __FILE__, __LINE__);
1975 goto error;
1976 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001977
1978done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001979 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001980 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001981 _PyBytes_Resize(&dest, count);
1982 return dest;
1983 }
1984 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 return PyLong_FromLong(count);
1986 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001987
1988error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001989 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001990 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001991 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001993}
1994
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001995/*[clinic input]
1996_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001997
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001998Does the SSL shutdown handshake with the remote end.
1999
2000Returns the underlying socket object.
2001[clinic start generated code]*/
2002
2003static PyObject *
2004_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2005/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002006{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 int err, ssl_err, sockstate, nonblocking;
2008 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002009 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002010 _PyTime_t timeout, deadline = 0;
2011 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002012
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002013 if (sock != NULL) {
2014 /* Guard against closed socket */
2015 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
2016 _setSSLError("Underlying socket connection gone",
2017 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2018 return NULL;
2019 }
2020 Py_INCREF(sock);
2021
2022 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002023 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002024 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2025 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027
Victor Stinner14690702015-04-06 22:46:13 +02002028 timeout = GET_SOCKET_TIMEOUT(sock);
2029 has_timeout = (timeout > 0);
2030 if (has_timeout)
2031 deadline = _PyTime_GetMonotonicClock() + timeout;
2032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002033 while (1) {
2034 PySSL_BEGIN_ALLOW_THREADS
2035 /* Disable read-ahead so that unwrap can work correctly.
2036 * Otherwise OpenSSL might read in too much data,
2037 * eating clear text data that happens to be
2038 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002039 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002040 * function is used and the shutdown_seen_zero != 0
2041 * condition is met.
2042 */
2043 if (self->shutdown_seen_zero)
2044 SSL_set_read_ahead(self->ssl, 0);
2045 err = SSL_shutdown(self->ssl);
2046 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2049 if (err > 0)
2050 break;
2051 if (err == 0) {
2052 /* Don't loop endlessly; instead preserve legacy
2053 behaviour of trying SSL_shutdown() only twice.
2054 This looks necessary for OpenSSL < 0.9.8m */
2055 if (++zeros > 1)
2056 break;
2057 /* Shutdown was sent, now try receiving */
2058 self->shutdown_seen_zero = 1;
2059 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002060 }
2061
Victor Stinner14690702015-04-06 22:46:13 +02002062 if (has_timeout)
2063 timeout = deadline - _PyTime_GetMonotonicClock();
2064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002065 /* Possibly retry shutdown until timeout or failure */
2066 ssl_err = SSL_get_error(self->ssl, err);
2067 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002068 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002069 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002070 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 else
2072 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002074 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2075 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002076 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 "The read operation timed out");
2078 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002079 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002081 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 }
2083 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2084 PyErr_SetString(PySSLErrorObject,
2085 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002086 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 }
2088 else if (sockstate != SOCKET_OPERATION_OK)
2089 /* Retain the SSL error code */
2090 break;
2091 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002092
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002093 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002094 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002096 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002097 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002098 /* It's already INCREF'ed */
2099 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002100 else
2101 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002102
2103error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002104 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002105 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002106}
2107
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002108/*[clinic input]
2109_ssl._SSLSocket.tls_unique_cb
2110
2111Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2112
2113If the TLS handshake is not yet complete, None is returned.
2114[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002115
Antoine Pitroud6494802011-07-21 01:11:30 +02002116static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002117_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2118/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002119{
2120 PyObject *retval = NULL;
2121 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002122 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002123
2124 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2125 /* if session is resumed XOR we are the client */
2126 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2127 }
2128 else {
2129 /* if a new session XOR we are the server */
2130 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2131 }
2132
2133 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002134 if (len == 0)
2135 Py_RETURN_NONE;
2136
2137 retval = PyBytes_FromStringAndSize(buf, len);
2138
2139 return retval;
2140}
2141
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002142static PyGetSetDef ssl_getsetlist[] = {
2143 {"context", (getter) PySSL_get_context,
2144 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002145 {"server_side", (getter) PySSL_get_server_side, NULL,
2146 PySSL_get_server_side_doc},
2147 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2148 PySSL_get_server_hostname_doc},
2149 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2150 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002151 {NULL}, /* sentinel */
2152};
2153
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002154static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002155 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2156 _SSL__SSLSOCKET_WRITE_METHODDEF
2157 _SSL__SSLSOCKET_READ_METHODDEF
2158 _SSL__SSLSOCKET_PENDING_METHODDEF
2159 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2160 _SSL__SSLSOCKET_CIPHER_METHODDEF
2161 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2162 _SSL__SSLSOCKET_VERSION_METHODDEF
2163 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2164 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2165 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2166 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2167 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002169};
2170
Antoine Pitrou152efa22010-05-16 18:19:27 +00002171static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173 "_ssl._SSLSocket", /*tp_name*/
2174 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 0, /*tp_itemsize*/
2176 /* methods */
2177 (destructor)PySSL_dealloc, /*tp_dealloc*/
2178 0, /*tp_print*/
2179 0, /*tp_getattr*/
2180 0, /*tp_setattr*/
2181 0, /*tp_reserved*/
2182 0, /*tp_repr*/
2183 0, /*tp_as_number*/
2184 0, /*tp_as_sequence*/
2185 0, /*tp_as_mapping*/
2186 0, /*tp_hash*/
2187 0, /*tp_call*/
2188 0, /*tp_str*/
2189 0, /*tp_getattro*/
2190 0, /*tp_setattro*/
2191 0, /*tp_as_buffer*/
2192 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2193 0, /*tp_doc*/
2194 0, /*tp_traverse*/
2195 0, /*tp_clear*/
2196 0, /*tp_richcompare*/
2197 0, /*tp_weaklistoffset*/
2198 0, /*tp_iter*/
2199 0, /*tp_iternext*/
2200 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002201 0, /*tp_members*/
2202 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002203};
2204
Antoine Pitrou152efa22010-05-16 18:19:27 +00002205
2206/*
2207 * _SSLContext objects
2208 */
2209
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002210/*[clinic input]
2211@classmethod
2212_ssl._SSLContext.__new__
2213 protocol as proto_version: int
2214 /
2215[clinic start generated code]*/
2216
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002218_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2219/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002220{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002222 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002223 SSL_CTX *ctx = NULL;
2224
Antoine Pitrou152efa22010-05-16 18:19:27 +00002225 PySSL_BEGIN_ALLOW_THREADS
2226 if (proto_version == PY_SSL_VERSION_TLS1)
2227 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002228#if HAVE_TLSv1_2
2229 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2230 ctx = SSL_CTX_new(TLSv1_1_method());
2231 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2232 ctx = SSL_CTX_new(TLSv1_2_method());
2233#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002234#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002235 else if (proto_version == PY_SSL_VERSION_SSL3)
2236 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002237#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002238#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002239 else if (proto_version == PY_SSL_VERSION_SSL2)
2240 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002241#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002242 else if (proto_version == PY_SSL_VERSION_SSL23)
2243 ctx = SSL_CTX_new(SSLv23_method());
2244 else
2245 proto_version = -1;
2246 PySSL_END_ALLOW_THREADS
2247
2248 if (proto_version == -1) {
2249 PyErr_SetString(PyExc_ValueError,
2250 "invalid protocol version");
2251 return NULL;
2252 }
2253 if (ctx == NULL) {
2254 PyErr_SetString(PySSLErrorObject,
2255 "failed to allocate SSL context");
2256 return NULL;
2257 }
2258
2259 assert(type != NULL && type->tp_alloc != NULL);
2260 self = (PySSLContext *) type->tp_alloc(type, 0);
2261 if (self == NULL) {
2262 SSL_CTX_free(ctx);
2263 return NULL;
2264 }
2265 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002266#ifdef OPENSSL_NPN_NEGOTIATED
2267 self->npn_protocols = NULL;
2268#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002269#ifdef HAVE_ALPN
2270 self->alpn_protocols = NULL;
2271#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002272#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002273 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002274#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002275 /* Don't check host name by default */
2276 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002277 /* Defaults */
2278 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002279 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2280 if (proto_version != PY_SSL_VERSION_SSL2)
2281 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002282 if (proto_version != PY_SSL_VERSION_SSL3)
2283 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002284 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002285
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002286#ifndef OPENSSL_NO_ECDH
2287 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2288 prime256v1 by default. This is Apache mod_ssl's initialization
2289 policy, so we should be safe. */
2290#if defined(SSL_CTX_set_ecdh_auto)
2291 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2292#else
2293 {
2294 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2295 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2296 EC_KEY_free(key);
2297 }
2298#endif
2299#endif
2300
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002301#define SID_CTX "Python"
2302 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2303 sizeof(SID_CTX));
2304#undef SID_CTX
2305
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002306#ifdef X509_V_FLAG_TRUSTED_FIRST
2307 {
2308 /* Improve trust chain building when cross-signed intermediate
2309 certificates are present. See https://bugs.python.org/issue23476. */
2310 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2311 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2312 }
2313#endif
2314
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315 return (PyObject *)self;
2316}
2317
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002318static int
2319context_traverse(PySSLContext *self, visitproc visit, void *arg)
2320{
2321#ifndef OPENSSL_NO_TLSEXT
2322 Py_VISIT(self->set_hostname);
2323#endif
2324 return 0;
2325}
2326
2327static int
2328context_clear(PySSLContext *self)
2329{
2330#ifndef OPENSSL_NO_TLSEXT
2331 Py_CLEAR(self->set_hostname);
2332#endif
2333 return 0;
2334}
2335
Antoine Pitrou152efa22010-05-16 18:19:27 +00002336static void
2337context_dealloc(PySSLContext *self)
2338{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002339 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002341#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002342 PyMem_FREE(self->npn_protocols);
2343#endif
2344#ifdef HAVE_ALPN
2345 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002346#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002347 Py_TYPE(self)->tp_free(self);
2348}
2349
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002350/*[clinic input]
2351_ssl._SSLContext.set_ciphers
2352 cipherlist: str
2353 /
2354[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002356static PyObject *
2357_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2358/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2359{
2360 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002361 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002362 /* Clearing the error queue is necessary on some OpenSSL versions,
2363 otherwise the error will be reported again when another SSL call
2364 is done. */
2365 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002366 PyErr_SetString(PySSLErrorObject,
2367 "No cipher can be selected.");
2368 return NULL;
2369 }
2370 Py_RETURN_NONE;
2371}
2372
Benjamin Petersonc54de472015-01-28 12:06:39 -05002373#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002374static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002375do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2376 const unsigned char *server_protocols, unsigned int server_protocols_len,
2377 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002378{
Benjamin Peterson88615022015-01-23 17:30:26 -05002379 int ret;
2380 if (client_protocols == NULL) {
2381 client_protocols = (unsigned char *)"";
2382 client_protocols_len = 0;
2383 }
2384 if (server_protocols == NULL) {
2385 server_protocols = (unsigned char *)"";
2386 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002387 }
2388
Benjamin Peterson88615022015-01-23 17:30:26 -05002389 ret = SSL_select_next_proto(out, outlen,
2390 server_protocols, server_protocols_len,
2391 client_protocols, client_protocols_len);
2392 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2393 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002394
2395 return SSL_TLSEXT_ERR_OK;
2396}
2397
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002398/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2399static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002400_advertiseNPN_cb(SSL *s,
2401 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002402 void *args)
2403{
2404 PySSLContext *ssl_ctx = (PySSLContext *) args;
2405
2406 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002407 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002408 *len = 0;
2409 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002410 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002411 *len = ssl_ctx->npn_protocols_len;
2412 }
2413
2414 return SSL_TLSEXT_ERR_OK;
2415}
2416/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2417static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002418_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002419 unsigned char **out, unsigned char *outlen,
2420 const unsigned char *server, unsigned int server_len,
2421 void *args)
2422{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002423 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002424 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002425 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002426}
2427#endif
2428
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002429/*[clinic input]
2430_ssl._SSLContext._set_npn_protocols
2431 protos: Py_buffer
2432 /
2433[clinic start generated code]*/
2434
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002435static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002436_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2437 Py_buffer *protos)
2438/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002439{
2440#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002441 PyMem_Free(self->npn_protocols);
2442 self->npn_protocols = PyMem_Malloc(protos->len);
2443 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002444 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002445 memcpy(self->npn_protocols, protos->buf, protos->len);
2446 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002447
2448 /* set both server and client callbacks, because the context can
2449 * be used to create both types of sockets */
2450 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2451 _advertiseNPN_cb,
2452 self);
2453 SSL_CTX_set_next_proto_select_cb(self->ctx,
2454 _selectNPN_cb,
2455 self);
2456
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002457 Py_RETURN_NONE;
2458#else
2459 PyErr_SetString(PyExc_NotImplementedError,
2460 "The NPN extension requires OpenSSL 1.0.1 or later.");
2461 return NULL;
2462#endif
2463}
2464
Benjamin Petersoncca27322015-01-23 16:35:37 -05002465#ifdef HAVE_ALPN
2466static int
2467_selectALPN_cb(SSL *s,
2468 const unsigned char **out, unsigned char *outlen,
2469 const unsigned char *client_protocols, unsigned int client_protocols_len,
2470 void *args)
2471{
2472 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002473 return do_protocol_selection(1, (unsigned char **)out, outlen,
2474 ctx->alpn_protocols, ctx->alpn_protocols_len,
2475 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002476}
2477#endif
2478
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002479/*[clinic input]
2480_ssl._SSLContext._set_alpn_protocols
2481 protos: Py_buffer
2482 /
2483[clinic start generated code]*/
2484
Benjamin Petersoncca27322015-01-23 16:35:37 -05002485static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002486_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2487 Py_buffer *protos)
2488/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002489{
2490#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002491 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002493 if (!self->alpn_protocols)
2494 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002495 memcpy(self->alpn_protocols, protos->buf, protos->len);
2496 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002497
2498 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2499 return PyErr_NoMemory();
2500 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2501
Benjamin Petersoncca27322015-01-23 16:35:37 -05002502 Py_RETURN_NONE;
2503#else
2504 PyErr_SetString(PyExc_NotImplementedError,
2505 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2506 return NULL;
2507#endif
2508}
2509
Antoine Pitrou152efa22010-05-16 18:19:27 +00002510static PyObject *
2511get_verify_mode(PySSLContext *self, void *c)
2512{
2513 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2514 case SSL_VERIFY_NONE:
2515 return PyLong_FromLong(PY_SSL_CERT_NONE);
2516 case SSL_VERIFY_PEER:
2517 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2518 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2519 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2520 }
2521 PyErr_SetString(PySSLErrorObject,
2522 "invalid return value from SSL_CTX_get_verify_mode");
2523 return NULL;
2524}
2525
2526static int
2527set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2528{
2529 int n, mode;
2530 if (!PyArg_Parse(arg, "i", &n))
2531 return -1;
2532 if (n == PY_SSL_CERT_NONE)
2533 mode = SSL_VERIFY_NONE;
2534 else if (n == PY_SSL_CERT_OPTIONAL)
2535 mode = SSL_VERIFY_PEER;
2536 else if (n == PY_SSL_CERT_REQUIRED)
2537 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2538 else {
2539 PyErr_SetString(PyExc_ValueError,
2540 "invalid value for verify_mode");
2541 return -1;
2542 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002543 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2544 PyErr_SetString(PyExc_ValueError,
2545 "Cannot set verify_mode to CERT_NONE when "
2546 "check_hostname is enabled.");
2547 return -1;
2548 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002549 SSL_CTX_set_verify(self->ctx, mode, NULL);
2550 return 0;
2551}
2552
2553static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002554get_verify_flags(PySSLContext *self, void *c)
2555{
2556 X509_STORE *store;
2557 unsigned long flags;
2558
2559 store = SSL_CTX_get_cert_store(self->ctx);
2560 flags = X509_VERIFY_PARAM_get_flags(store->param);
2561 return PyLong_FromUnsignedLong(flags);
2562}
2563
2564static int
2565set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2566{
2567 X509_STORE *store;
2568 unsigned long new_flags, flags, set, clear;
2569
2570 if (!PyArg_Parse(arg, "k", &new_flags))
2571 return -1;
2572 store = SSL_CTX_get_cert_store(self->ctx);
2573 flags = X509_VERIFY_PARAM_get_flags(store->param);
2574 clear = flags & ~new_flags;
2575 set = ~flags & new_flags;
2576 if (clear) {
2577 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2578 _setSSLError(NULL, 0, __FILE__, __LINE__);
2579 return -1;
2580 }
2581 }
2582 if (set) {
2583 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2584 _setSSLError(NULL, 0, __FILE__, __LINE__);
2585 return -1;
2586 }
2587 }
2588 return 0;
2589}
2590
2591static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002592get_options(PySSLContext *self, void *c)
2593{
2594 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2595}
2596
2597static int
2598set_options(PySSLContext *self, PyObject *arg, void *c)
2599{
2600 long new_opts, opts, set, clear;
2601 if (!PyArg_Parse(arg, "l", &new_opts))
2602 return -1;
2603 opts = SSL_CTX_get_options(self->ctx);
2604 clear = opts & ~new_opts;
2605 set = ~opts & new_opts;
2606 if (clear) {
2607#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2608 SSL_CTX_clear_options(self->ctx, clear);
2609#else
2610 PyErr_SetString(PyExc_ValueError,
2611 "can't clear options before OpenSSL 0.9.8m");
2612 return -1;
2613#endif
2614 }
2615 if (set)
2616 SSL_CTX_set_options(self->ctx, set);
2617 return 0;
2618}
2619
Christian Heimes1aa9a752013-12-02 02:41:19 +01002620static PyObject *
2621get_check_hostname(PySSLContext *self, void *c)
2622{
2623 return PyBool_FromLong(self->check_hostname);
2624}
2625
2626static int
2627set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2628{
2629 int check_hostname;
2630 if (!PyArg_Parse(arg, "p", &check_hostname))
2631 return -1;
2632 if (check_hostname &&
2633 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2634 PyErr_SetString(PyExc_ValueError,
2635 "check_hostname needs a SSL context with either "
2636 "CERT_OPTIONAL or CERT_REQUIRED");
2637 return -1;
2638 }
2639 self->check_hostname = check_hostname;
2640 return 0;
2641}
2642
2643
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002644typedef struct {
2645 PyThreadState *thread_state;
2646 PyObject *callable;
2647 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002648 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002649 int error;
2650} _PySSLPasswordInfo;
2651
2652static int
2653_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2654 const char *bad_type_error)
2655{
2656 /* Set the password and size fields of a _PySSLPasswordInfo struct
2657 from a unicode, bytes, or byte array object.
2658 The password field will be dynamically allocated and must be freed
2659 by the caller */
2660 PyObject *password_bytes = NULL;
2661 const char *data = NULL;
2662 Py_ssize_t size;
2663
2664 if (PyUnicode_Check(password)) {
2665 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2666 if (!password_bytes) {
2667 goto error;
2668 }
2669 data = PyBytes_AS_STRING(password_bytes);
2670 size = PyBytes_GET_SIZE(password_bytes);
2671 } else if (PyBytes_Check(password)) {
2672 data = PyBytes_AS_STRING(password);
2673 size = PyBytes_GET_SIZE(password);
2674 } else if (PyByteArray_Check(password)) {
2675 data = PyByteArray_AS_STRING(password);
2676 size = PyByteArray_GET_SIZE(password);
2677 } else {
2678 PyErr_SetString(PyExc_TypeError, bad_type_error);
2679 goto error;
2680 }
2681
Victor Stinner9ee02032013-06-23 15:08:23 +02002682 if (size > (Py_ssize_t)INT_MAX) {
2683 PyErr_Format(PyExc_ValueError,
2684 "password cannot be longer than %d bytes", INT_MAX);
2685 goto error;
2686 }
2687
Victor Stinner11ebff22013-07-07 17:07:52 +02002688 PyMem_Free(pw_info->password);
2689 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002690 if (!pw_info->password) {
2691 PyErr_SetString(PyExc_MemoryError,
2692 "unable to allocate password buffer");
2693 goto error;
2694 }
2695 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002696 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002697
2698 Py_XDECREF(password_bytes);
2699 return 1;
2700
2701error:
2702 Py_XDECREF(password_bytes);
2703 return 0;
2704}
2705
2706static int
2707_password_callback(char *buf, int size, int rwflag, void *userdata)
2708{
2709 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2710 PyObject *fn_ret = NULL;
2711
2712 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2713
2714 if (pw_info->callable) {
2715 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2716 if (!fn_ret) {
2717 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2718 core python API, so we could use it to add a frame here */
2719 goto error;
2720 }
2721
2722 if (!_pwinfo_set(pw_info, fn_ret,
2723 "password callback must return a string")) {
2724 goto error;
2725 }
2726 Py_CLEAR(fn_ret);
2727 }
2728
2729 if (pw_info->size > size) {
2730 PyErr_Format(PyExc_ValueError,
2731 "password cannot be longer than %d bytes", size);
2732 goto error;
2733 }
2734
2735 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2736 memcpy(buf, pw_info->password, pw_info->size);
2737 return pw_info->size;
2738
2739error:
2740 Py_XDECREF(fn_ret);
2741 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2742 pw_info->error = 1;
2743 return -1;
2744}
2745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002746/*[clinic input]
2747_ssl._SSLContext.load_cert_chain
2748 certfile: object
2749 keyfile: object = NULL
2750 password: object = NULL
2751
2752[clinic start generated code]*/
2753
Antoine Pitroub5218772010-05-21 09:56:06 +00002754static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002755_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2756 PyObject *keyfile, PyObject *password)
2757/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002758{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002759 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002760 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2761 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2762 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002763 int r;
2764
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002765 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002766 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002767 if (keyfile == Py_None)
2768 keyfile = NULL;
2769 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2770 PyErr_SetString(PyExc_TypeError,
2771 "certfile should be a valid filesystem path");
2772 return NULL;
2773 }
2774 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2775 PyErr_SetString(PyExc_TypeError,
2776 "keyfile should be a valid filesystem path");
2777 goto error;
2778 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002779 if (password && password != Py_None) {
2780 if (PyCallable_Check(password)) {
2781 pw_info.callable = password;
2782 } else if (!_pwinfo_set(&pw_info, password,
2783 "password should be a string or callable")) {
2784 goto error;
2785 }
2786 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2787 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2788 }
2789 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2791 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002792 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002794 if (pw_info.error) {
2795 ERR_clear_error();
2796 /* the password callback has already set the error information */
2797 }
2798 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002799 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002800 PyErr_SetFromErrno(PyExc_IOError);
2801 }
2802 else {
2803 _setSSLError(NULL, 0, __FILE__, __LINE__);
2804 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805 goto error;
2806 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002807 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002808 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002809 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2810 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002811 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2812 Py_CLEAR(keyfile_bytes);
2813 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002814 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002815 if (pw_info.error) {
2816 ERR_clear_error();
2817 /* the password callback has already set the error information */
2818 }
2819 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002820 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002821 PyErr_SetFromErrno(PyExc_IOError);
2822 }
2823 else {
2824 _setSSLError(NULL, 0, __FILE__, __LINE__);
2825 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002826 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002828 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002829 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002830 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831 if (r != 1) {
2832 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002833 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002834 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002835 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2836 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002837 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002838 Py_RETURN_NONE;
2839
2840error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002841 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2842 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002843 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002844 Py_XDECREF(keyfile_bytes);
2845 Py_XDECREF(certfile_bytes);
2846 return NULL;
2847}
2848
Christian Heimesefff7062013-11-21 03:35:02 +01002849/* internal helper function, returns -1 on error
2850 */
2851static int
2852_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2853 int filetype)
2854{
2855 BIO *biobuf = NULL;
2856 X509_STORE *store;
2857 int retval = 0, err, loaded = 0;
2858
2859 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2860
2861 if (len <= 0) {
2862 PyErr_SetString(PyExc_ValueError,
2863 "Empty certificate data");
2864 return -1;
2865 } else if (len > INT_MAX) {
2866 PyErr_SetString(PyExc_OverflowError,
2867 "Certificate data is too long.");
2868 return -1;
2869 }
2870
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002871 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002872 if (biobuf == NULL) {
2873 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2874 return -1;
2875 }
2876
2877 store = SSL_CTX_get_cert_store(self->ctx);
2878 assert(store != NULL);
2879
2880 while (1) {
2881 X509 *cert = NULL;
2882 int r;
2883
2884 if (filetype == SSL_FILETYPE_ASN1) {
2885 cert = d2i_X509_bio(biobuf, NULL);
2886 } else {
2887 cert = PEM_read_bio_X509(biobuf, NULL,
2888 self->ctx->default_passwd_callback,
2889 self->ctx->default_passwd_callback_userdata);
2890 }
2891 if (cert == NULL) {
2892 break;
2893 }
2894 r = X509_STORE_add_cert(store, cert);
2895 X509_free(cert);
2896 if (!r) {
2897 err = ERR_peek_last_error();
2898 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2899 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2900 /* cert already in hash table, not an error */
2901 ERR_clear_error();
2902 } else {
2903 break;
2904 }
2905 }
2906 loaded++;
2907 }
2908
2909 err = ERR_peek_last_error();
2910 if ((filetype == SSL_FILETYPE_ASN1) &&
2911 (loaded > 0) &&
2912 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2913 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2914 /* EOF ASN1 file, not an error */
2915 ERR_clear_error();
2916 retval = 0;
2917 } else if ((filetype == SSL_FILETYPE_PEM) &&
2918 (loaded > 0) &&
2919 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2920 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2921 /* EOF PEM file, not an error */
2922 ERR_clear_error();
2923 retval = 0;
2924 } else {
2925 _setSSLError(NULL, 0, __FILE__, __LINE__);
2926 retval = -1;
2927 }
2928
2929 BIO_free(biobuf);
2930 return retval;
2931}
2932
2933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002934/*[clinic input]
2935_ssl._SSLContext.load_verify_locations
2936 cafile: object = NULL
2937 capath: object = NULL
2938 cadata: object = NULL
2939
2940[clinic start generated code]*/
2941
Antoine Pitrou152efa22010-05-16 18:19:27 +00002942static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002943_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2944 PyObject *cafile,
2945 PyObject *capath,
2946 PyObject *cadata)
2947/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002948{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2950 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002951 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002952
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002953 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 if (cafile == Py_None)
2955 cafile = NULL;
2956 if (capath == Py_None)
2957 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002958 if (cadata == Py_None)
2959 cadata = NULL;
2960
2961 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002963 "cafile, capath and cadata cannot be all omitted");
2964 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002965 }
2966 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2967 PyErr_SetString(PyExc_TypeError,
2968 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002969 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002970 }
2971 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002972 PyErr_SetString(PyExc_TypeError,
2973 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002974 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002975 }
Christian Heimesefff7062013-11-21 03:35:02 +01002976
2977 /* validata cadata type and load cadata */
2978 if (cadata) {
2979 Py_buffer buf;
2980 PyObject *cadata_ascii = NULL;
2981
2982 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2983 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2984 PyBuffer_Release(&buf);
2985 PyErr_SetString(PyExc_TypeError,
2986 "cadata should be a contiguous buffer with "
2987 "a single dimension");
2988 goto error;
2989 }
2990 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2991 PyBuffer_Release(&buf);
2992 if (r == -1) {
2993 goto error;
2994 }
2995 } else {
2996 PyErr_Clear();
2997 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2998 if (cadata_ascii == NULL) {
2999 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003000 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003001 "bytes-like object");
3002 goto error;
3003 }
3004 r = _add_ca_certs(self,
3005 PyBytes_AS_STRING(cadata_ascii),
3006 PyBytes_GET_SIZE(cadata_ascii),
3007 SSL_FILETYPE_PEM);
3008 Py_DECREF(cadata_ascii);
3009 if (r == -1) {
3010 goto error;
3011 }
3012 }
3013 }
3014
3015 /* load cafile or capath */
3016 if (cafile || capath) {
3017 if (cafile)
3018 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3019 if (capath)
3020 capath_buf = PyBytes_AS_STRING(capath_bytes);
3021 PySSL_BEGIN_ALLOW_THREADS
3022 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3023 PySSL_END_ALLOW_THREADS
3024 if (r != 1) {
3025 ok = 0;
3026 if (errno != 0) {
3027 ERR_clear_error();
3028 PyErr_SetFromErrno(PyExc_IOError);
3029 }
3030 else {
3031 _setSSLError(NULL, 0, __FILE__, __LINE__);
3032 }
3033 goto error;
3034 }
3035 }
3036 goto end;
3037
3038 error:
3039 ok = 0;
3040 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003041 Py_XDECREF(cafile_bytes);
3042 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003043 if (ok) {
3044 Py_RETURN_NONE;
3045 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003046 return NULL;
3047 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003048}
3049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003050/*[clinic input]
3051_ssl._SSLContext.load_dh_params
3052 path as filepath: object
3053 /
3054
3055[clinic start generated code]*/
3056
Antoine Pitrou152efa22010-05-16 18:19:27 +00003057static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003058_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3059/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003060{
3061 FILE *f;
3062 DH *dh;
3063
Victor Stinnerdaf45552013-08-28 00:53:59 +02003064 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003065 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003066 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003067
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003068 errno = 0;
3069 PySSL_BEGIN_ALLOW_THREADS
3070 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003071 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003072 PySSL_END_ALLOW_THREADS
3073 if (dh == NULL) {
3074 if (errno != 0) {
3075 ERR_clear_error();
3076 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3077 }
3078 else {
3079 _setSSLError(NULL, 0, __FILE__, __LINE__);
3080 }
3081 return NULL;
3082 }
3083 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3084 _setSSLError(NULL, 0, __FILE__, __LINE__);
3085 DH_free(dh);
3086 Py_RETURN_NONE;
3087}
3088
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003089/*[clinic input]
3090_ssl._SSLContext._wrap_socket
3091 sock: object(subclass_of="PySocketModule.Sock_Type")
3092 server_side: int
3093 server_hostname as hostname_obj: object = None
3094
3095[clinic start generated code]*/
3096
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003097static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003098_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3099 int server_side, PyObject *hostname_obj)
3100/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003101{
Antoine Pitroud5323212010-10-22 18:19:07 +00003102 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003103 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003104
Antoine Pitroud5323212010-10-22 18:19:07 +00003105 /* server_hostname is either None (or absent), or to be encoded
3106 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003107 if (hostname_obj != Py_None) {
3108 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003109 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003110 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003112 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3113 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003114 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003115 if (hostname != NULL)
3116 PyMem_Free(hostname);
3117 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003118}
3119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003120/*[clinic input]
3121_ssl._SSLContext._wrap_bio
3122 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3123 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3124 server_side: int
3125 server_hostname as hostname_obj: object = None
3126
3127[clinic start generated code]*/
3128
Antoine Pitroub0182c82010-10-12 20:09:02 +00003129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003130_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3131 PySSLMemoryBIO *outgoing, int server_side,
3132 PyObject *hostname_obj)
3133/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003134{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003135 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003136 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003137
3138 /* server_hostname is either None (or absent), or to be encoded
3139 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003140 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003141 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3142 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003143 }
3144
3145 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3146 incoming, outgoing);
3147
3148 PyMem_Free(hostname);
3149 return res;
3150}
3151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003152/*[clinic input]
3153_ssl._SSLContext.session_stats
3154[clinic start generated code]*/
3155
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003156static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003157_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3158/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003159{
3160 int r;
3161 PyObject *value, *stats = PyDict_New();
3162 if (!stats)
3163 return NULL;
3164
3165#define ADD_STATS(SSL_NAME, KEY_NAME) \
3166 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3167 if (value == NULL) \
3168 goto error; \
3169 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3170 Py_DECREF(value); \
3171 if (r < 0) \
3172 goto error;
3173
3174 ADD_STATS(number, "number");
3175 ADD_STATS(connect, "connect");
3176 ADD_STATS(connect_good, "connect_good");
3177 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3178 ADD_STATS(accept, "accept");
3179 ADD_STATS(accept_good, "accept_good");
3180 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3181 ADD_STATS(accept, "accept");
3182 ADD_STATS(hits, "hits");
3183 ADD_STATS(misses, "misses");
3184 ADD_STATS(timeouts, "timeouts");
3185 ADD_STATS(cache_full, "cache_full");
3186
3187#undef ADD_STATS
3188
3189 return stats;
3190
3191error:
3192 Py_DECREF(stats);
3193 return NULL;
3194}
3195
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003196/*[clinic input]
3197_ssl._SSLContext.set_default_verify_paths
3198[clinic start generated code]*/
3199
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003200static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003201_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3202/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003203{
3204 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3205 _setSSLError(NULL, 0, __FILE__, __LINE__);
3206 return NULL;
3207 }
3208 Py_RETURN_NONE;
3209}
3210
Antoine Pitrou501da612011-12-21 09:27:41 +01003211#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003212/*[clinic input]
3213_ssl._SSLContext.set_ecdh_curve
3214 name: object
3215 /
3216
3217[clinic start generated code]*/
3218
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003219static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003220_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3221/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003222{
3223 PyObject *name_bytes;
3224 int nid;
3225 EC_KEY *key;
3226
3227 if (!PyUnicode_FSConverter(name, &name_bytes))
3228 return NULL;
3229 assert(PyBytes_Check(name_bytes));
3230 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3231 Py_DECREF(name_bytes);
3232 if (nid == 0) {
3233 PyErr_Format(PyExc_ValueError,
3234 "unknown elliptic curve name %R", name);
3235 return NULL;
3236 }
3237 key = EC_KEY_new_by_curve_name(nid);
3238 if (key == NULL) {
3239 _setSSLError(NULL, 0, __FILE__, __LINE__);
3240 return NULL;
3241 }
3242 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3243 EC_KEY_free(key);
3244 Py_RETURN_NONE;
3245}
Antoine Pitrou501da612011-12-21 09:27:41 +01003246#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003247
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003248#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003249static int
3250_servername_callback(SSL *s, int *al, void *args)
3251{
3252 int ret;
3253 PySSLContext *ssl_ctx = (PySSLContext *) args;
3254 PySSLSocket *ssl;
3255 PyObject *servername_o;
3256 PyObject *servername_idna;
3257 PyObject *result;
3258 /* The high-level ssl.SSLSocket object */
3259 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003260 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003261#ifdef WITH_THREAD
3262 PyGILState_STATE gstate = PyGILState_Ensure();
3263#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003264
3265 if (ssl_ctx->set_hostname == NULL) {
3266 /* remove race condition in this the call back while if removing the
3267 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003268#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003269 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003270#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003271 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003272 }
3273
3274 ssl = SSL_get_app_data(s);
3275 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003276
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003277 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003278 * SSL connection and that has a .context attribute that can be changed to
3279 * identify the requested hostname. Since the official API is the Python
3280 * level API we want to pass the callback a Python level object rather than
3281 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3282 * SSLObject) that will be passed. Otherwise if there's a socket then that
3283 * will be passed. If both do not exist only then the C-level object is
3284 * passed. */
3285 if (ssl->owner)
3286 ssl_socket = PyWeakref_GetObject(ssl->owner);
3287 else if (ssl->Socket)
3288 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3289 else
3290 ssl_socket = (PyObject *) ssl;
3291
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003293 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003295
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003296 if (servername == NULL) {
3297 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3298 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003299 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003300 else {
3301 servername_o = PyBytes_FromString(servername);
3302 if (servername_o == NULL) {
3303 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3304 goto error;
3305 }
3306 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3307 if (servername_idna == NULL) {
3308 PyErr_WriteUnraisable(servername_o);
3309 Py_DECREF(servername_o);
3310 goto error;
3311 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003312 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003313 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3314 servername_idna, ssl_ctx, NULL);
3315 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003316 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003317 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003318
3319 if (result == NULL) {
3320 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3321 *al = SSL_AD_HANDSHAKE_FAILURE;
3322 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3323 }
3324 else {
3325 if (result != Py_None) {
3326 *al = (int) PyLong_AsLong(result);
3327 if (PyErr_Occurred()) {
3328 PyErr_WriteUnraisable(result);
3329 *al = SSL_AD_INTERNAL_ERROR;
3330 }
3331 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3332 }
3333 else {
3334 ret = SSL_TLSEXT_ERR_OK;
3335 }
3336 Py_DECREF(result);
3337 }
3338
Stefan Krah20d60802013-01-17 17:07:17 +01003339#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003340 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003341#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003342 return ret;
3343
3344error:
3345 Py_DECREF(ssl_socket);
3346 *al = SSL_AD_INTERNAL_ERROR;
3347 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003348#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003349 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003350#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003351 return ret;
3352}
Antoine Pitroua5963382013-03-30 16:39:00 +01003353#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003354
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003355/*[clinic input]
3356_ssl._SSLContext.set_servername_callback
3357 method as cb: object
3358 /
3359
3360Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3361
3362If the argument is None then the callback is disabled. The method is called
3363with the SSLSocket, the server name as a string, and the SSLContext object.
3364See RFC 6066 for details of the SNI extension.
3365[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003366
3367static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003368_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3369/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003370{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003371#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003372 Py_CLEAR(self->set_hostname);
3373 if (cb == Py_None) {
3374 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3375 }
3376 else {
3377 if (!PyCallable_Check(cb)) {
3378 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3379 PyErr_SetString(PyExc_TypeError,
3380 "not a callable object");
3381 return NULL;
3382 }
3383 Py_INCREF(cb);
3384 self->set_hostname = cb;
3385 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3386 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3387 }
3388 Py_RETURN_NONE;
3389#else
3390 PyErr_SetString(PyExc_NotImplementedError,
3391 "The TLS extension servername callback, "
3392 "SSL_CTX_set_tlsext_servername_callback, "
3393 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003394 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003395#endif
3396}
3397
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003398/*[clinic input]
3399_ssl._SSLContext.cert_store_stats
3400
3401Returns quantities of loaded X.509 certificates.
3402
3403X.509 certificates with a CA extension and certificate revocation lists
3404inside the context's cert store.
3405
3406NOTE: Certificates in a capath directory aren't loaded unless they have
3407been used at least once.
3408[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003409
3410static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003411_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3412/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003413{
3414 X509_STORE *store;
3415 X509_OBJECT *obj;
3416 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3417
3418 store = SSL_CTX_get_cert_store(self->ctx);
3419 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3420 obj = sk_X509_OBJECT_value(store->objs, i);
3421 switch (obj->type) {
3422 case X509_LU_X509:
3423 x509++;
3424 if (X509_check_ca(obj->data.x509)) {
3425 ca++;
3426 }
3427 break;
3428 case X509_LU_CRL:
3429 crl++;
3430 break;
3431 case X509_LU_PKEY:
3432 pkey++;
3433 break;
3434 default:
3435 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3436 * As far as I can tell they are internal states and never
3437 * stored in a cert store */
3438 break;
3439 }
3440 }
3441 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3442 "x509_ca", ca);
3443}
3444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003445/*[clinic input]
3446_ssl._SSLContext.get_ca_certs
3447 binary_form: bool = False
3448
3449Returns a list of dicts with information of loaded CA certs.
3450
3451If the optional argument is True, returns a DER-encoded copy of the CA
3452certificate.
3453
3454NOTE: Certificates in a capath directory aren't loaded unless they have
3455been used at least once.
3456[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003457
3458static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003459_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3460/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003461{
3462 X509_STORE *store;
3463 PyObject *ci = NULL, *rlist = NULL;
3464 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003465
3466 if ((rlist = PyList_New(0)) == NULL) {
3467 return NULL;
3468 }
3469
3470 store = SSL_CTX_get_cert_store(self->ctx);
3471 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3472 X509_OBJECT *obj;
3473 X509 *cert;
3474
3475 obj = sk_X509_OBJECT_value(store->objs, i);
3476 if (obj->type != X509_LU_X509) {
3477 /* not a x509 cert */
3478 continue;
3479 }
3480 /* CA for any purpose */
3481 cert = obj->data.x509;
3482 if (!X509_check_ca(cert)) {
3483 continue;
3484 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003485 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003486 ci = _certificate_to_der(cert);
3487 } else {
3488 ci = _decode_certificate(cert);
3489 }
3490 if (ci == NULL) {
3491 goto error;
3492 }
3493 if (PyList_Append(rlist, ci) == -1) {
3494 goto error;
3495 }
3496 Py_CLEAR(ci);
3497 }
3498 return rlist;
3499
3500 error:
3501 Py_XDECREF(ci);
3502 Py_XDECREF(rlist);
3503 return NULL;
3504}
3505
3506
Antoine Pitrou152efa22010-05-16 18:19:27 +00003507static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003508 {"check_hostname", (getter) get_check_hostname,
3509 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003510 {"options", (getter) get_options,
3511 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003512 {"verify_flags", (getter) get_verify_flags,
3513 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003514 {"verify_mode", (getter) get_verify_mode,
3515 (setter) set_verify_mode, NULL},
3516 {NULL}, /* sentinel */
3517};
3518
3519static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003520 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3521 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3522 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3523 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3524 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3525 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3526 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3527 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3528 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3529 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3530 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3531 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3532 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3533 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003534 {NULL, NULL} /* sentinel */
3535};
3536
3537static PyTypeObject PySSLContext_Type = {
3538 PyVarObject_HEAD_INIT(NULL, 0)
3539 "_ssl._SSLContext", /*tp_name*/
3540 sizeof(PySSLContext), /*tp_basicsize*/
3541 0, /*tp_itemsize*/
3542 (destructor)context_dealloc, /*tp_dealloc*/
3543 0, /*tp_print*/
3544 0, /*tp_getattr*/
3545 0, /*tp_setattr*/
3546 0, /*tp_reserved*/
3547 0, /*tp_repr*/
3548 0, /*tp_as_number*/
3549 0, /*tp_as_sequence*/
3550 0, /*tp_as_mapping*/
3551 0, /*tp_hash*/
3552 0, /*tp_call*/
3553 0, /*tp_str*/
3554 0, /*tp_getattro*/
3555 0, /*tp_setattro*/
3556 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003557 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003558 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003559 (traverseproc) context_traverse, /*tp_traverse*/
3560 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003561 0, /*tp_richcompare*/
3562 0, /*tp_weaklistoffset*/
3563 0, /*tp_iter*/
3564 0, /*tp_iternext*/
3565 context_methods, /*tp_methods*/
3566 0, /*tp_members*/
3567 context_getsetlist, /*tp_getset*/
3568 0, /*tp_base*/
3569 0, /*tp_dict*/
3570 0, /*tp_descr_get*/
3571 0, /*tp_descr_set*/
3572 0, /*tp_dictoffset*/
3573 0, /*tp_init*/
3574 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003575 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576};
3577
3578
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003579/*
3580 * MemoryBIO objects
3581 */
3582
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003583/*[clinic input]
3584@classmethod
3585_ssl.MemoryBIO.__new__
3586
3587[clinic start generated code]*/
3588
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003589static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003590_ssl_MemoryBIO_impl(PyTypeObject *type)
3591/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003592{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003593 BIO *bio;
3594 PySSLMemoryBIO *self;
3595
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003596 bio = BIO_new(BIO_s_mem());
3597 if (bio == NULL) {
3598 PyErr_SetString(PySSLErrorObject,
3599 "failed to allocate BIO");
3600 return NULL;
3601 }
3602 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3603 * just that no data is currently available. The SSL routines should retry
3604 * the read, which we can achieve by calling BIO_set_retry_read(). */
3605 BIO_set_retry_read(bio);
3606 BIO_set_mem_eof_return(bio, -1);
3607
3608 assert(type != NULL && type->tp_alloc != NULL);
3609 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3610 if (self == NULL) {
3611 BIO_free(bio);
3612 return NULL;
3613 }
3614 self->bio = bio;
3615 self->eof_written = 0;
3616
3617 return (PyObject *) self;
3618}
3619
3620static void
3621memory_bio_dealloc(PySSLMemoryBIO *self)
3622{
3623 BIO_free(self->bio);
3624 Py_TYPE(self)->tp_free(self);
3625}
3626
3627static PyObject *
3628memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3629{
3630 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3631}
3632
3633PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3634"The number of bytes pending in the memory BIO.");
3635
3636static PyObject *
3637memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3638{
3639 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3640 && self->eof_written);
3641}
3642
3643PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3644"Whether the memory BIO is at EOF.");
3645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003646/*[clinic input]
3647_ssl.MemoryBIO.read
3648 size as len: int = -1
3649 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003650
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003651Read up to size bytes from the memory BIO.
3652
3653If size is not specified, read the entire buffer.
3654If the return value is an empty bytes instance, this means either
3655EOF or that no data is available. Use the "eof" property to
3656distinguish between the two.
3657[clinic start generated code]*/
3658
3659static PyObject *
3660_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3661/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3662{
3663 int avail, nbytes;
3664 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003665
3666 avail = BIO_ctrl_pending(self->bio);
3667 if ((len < 0) || (len > avail))
3668 len = avail;
3669
3670 result = PyBytes_FromStringAndSize(NULL, len);
3671 if ((result == NULL) || (len == 0))
3672 return result;
3673
3674 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3675 /* There should never be any short reads but check anyway. */
3676 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3677 Py_DECREF(result);
3678 return NULL;
3679 }
3680
3681 return result;
3682}
3683
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003684/*[clinic input]
3685_ssl.MemoryBIO.write
3686 b: Py_buffer
3687 /
3688
3689Writes the bytes b into the memory BIO.
3690
3691Returns the number of bytes written.
3692[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003693
3694static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003695_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3696/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003697{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003698 int nbytes;
3699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003700 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003701 PyErr_Format(PyExc_OverflowError,
3702 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003703 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003704 }
3705
3706 if (self->eof_written) {
3707 PyErr_SetString(PySSLErrorObject,
3708 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003709 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003710 }
3711
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003712 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003713 if (nbytes < 0) {
3714 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003715 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003716 }
3717
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003718 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003719}
3720
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003721/*[clinic input]
3722_ssl.MemoryBIO.write_eof
3723
3724Write an EOF marker to the memory BIO.
3725
3726When all data has been read, the "eof" property will be True.
3727[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003728
3729static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003730_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3731/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003732{
3733 self->eof_written = 1;
3734 /* After an EOF is written, a zero return from read() should be a real EOF
3735 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3736 BIO_clear_retry_flags(self->bio);
3737 BIO_set_mem_eof_return(self->bio, 0);
3738
3739 Py_RETURN_NONE;
3740}
3741
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003742static PyGetSetDef memory_bio_getsetlist[] = {
3743 {"pending", (getter) memory_bio_get_pending, NULL,
3744 PySSL_memory_bio_pending_doc},
3745 {"eof", (getter) memory_bio_get_eof, NULL,
3746 PySSL_memory_bio_eof_doc},
3747 {NULL}, /* sentinel */
3748};
3749
3750static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003751 _SSL_MEMORYBIO_READ_METHODDEF
3752 _SSL_MEMORYBIO_WRITE_METHODDEF
3753 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003754 {NULL, NULL} /* sentinel */
3755};
3756
3757static PyTypeObject PySSLMemoryBIO_Type = {
3758 PyVarObject_HEAD_INIT(NULL, 0)
3759 "_ssl.MemoryBIO", /*tp_name*/
3760 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3761 0, /*tp_itemsize*/
3762 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3763 0, /*tp_print*/
3764 0, /*tp_getattr*/
3765 0, /*tp_setattr*/
3766 0, /*tp_reserved*/
3767 0, /*tp_repr*/
3768 0, /*tp_as_number*/
3769 0, /*tp_as_sequence*/
3770 0, /*tp_as_mapping*/
3771 0, /*tp_hash*/
3772 0, /*tp_call*/
3773 0, /*tp_str*/
3774 0, /*tp_getattro*/
3775 0, /*tp_setattro*/
3776 0, /*tp_as_buffer*/
3777 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3778 0, /*tp_doc*/
3779 0, /*tp_traverse*/
3780 0, /*tp_clear*/
3781 0, /*tp_richcompare*/
3782 0, /*tp_weaklistoffset*/
3783 0, /*tp_iter*/
3784 0, /*tp_iternext*/
3785 memory_bio_methods, /*tp_methods*/
3786 0, /*tp_members*/
3787 memory_bio_getsetlist, /*tp_getset*/
3788 0, /*tp_base*/
3789 0, /*tp_dict*/
3790 0, /*tp_descr_get*/
3791 0, /*tp_descr_set*/
3792 0, /*tp_dictoffset*/
3793 0, /*tp_init*/
3794 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003795 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003796};
3797
Antoine Pitrou152efa22010-05-16 18:19:27 +00003798
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003799/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003800/*[clinic input]
3801_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003802 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003803 entropy: double
3804 /
3805
3806Mix string into the OpenSSL PRNG state.
3807
3808entropy (a float) is a lower bound on the entropy contained in
3809string. See RFC 1750.
3810[clinic start generated code]*/
3811
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003812static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003813_ssl_RAND_add_impl(PyModuleDef *module, Py_buffer *view, double entropy)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003814/*[clinic end generated code: output=0f8d5c8cce328958 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003815{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003816 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003817 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003818
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003819 buf = (const char *)view->buf;
3820 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003821 do {
3822 written = Py_MIN(len, INT_MAX);
3823 RAND_add(buf, (int)written, entropy);
3824 buf += written;
3825 len -= written;
3826 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003827 Py_INCREF(Py_None);
3828 return Py_None;
3829}
3830
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003831static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003832PySSL_RAND(int len, int pseudo)
3833{
3834 int ok;
3835 PyObject *bytes;
3836 unsigned long err;
3837 const char *errstr;
3838 PyObject *v;
3839
Victor Stinner1e81a392013-12-19 16:47:04 +01003840 if (len < 0) {
3841 PyErr_SetString(PyExc_ValueError, "num must be positive");
3842 return NULL;
3843 }
3844
Victor Stinner99c8b162011-05-24 12:05:19 +02003845 bytes = PyBytes_FromStringAndSize(NULL, len);
3846 if (bytes == NULL)
3847 return NULL;
3848 if (pseudo) {
3849 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3850 if (ok == 0 || ok == 1)
3851 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3852 }
3853 else {
3854 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3855 if (ok == 1)
3856 return bytes;
3857 }
3858 Py_DECREF(bytes);
3859
3860 err = ERR_get_error();
3861 errstr = ERR_reason_error_string(err);
3862 v = Py_BuildValue("(ks)", err, errstr);
3863 if (v != NULL) {
3864 PyErr_SetObject(PySSLErrorObject, v);
3865 Py_DECREF(v);
3866 }
3867 return NULL;
3868}
3869
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003870/*[clinic input]
3871_ssl.RAND_bytes
3872 n: int
3873 /
3874
3875Generate n cryptographically strong pseudo-random bytes.
3876[clinic start generated code]*/
3877
Victor Stinner99c8b162011-05-24 12:05:19 +02003878static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003879_ssl_RAND_bytes_impl(PyModuleDef *module, int n)
3880/*[clinic end generated code: output=7d8741bdc1d435f3 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003881{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003883}
3884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003885/*[clinic input]
3886_ssl.RAND_pseudo_bytes
3887 n: int
3888 /
3889
3890Generate n pseudo-random bytes.
3891
3892Return a pair (bytes, is_cryptographic). is_cryptographic is True
3893if the bytes generated are cryptographically strong.
3894[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003895
3896static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003897_ssl_RAND_pseudo_bytes_impl(PyModuleDef *module, int n)
3898/*[clinic end generated code: output=dd673813107f3875 input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003899{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003900 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003901}
3902
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003903/*[clinic input]
3904_ssl.RAND_status
3905
3906Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3907
3908It is necessary to seed the PRNG with RAND_add() on some platforms before
3909using the ssl() function.
3910[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003911
3912static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003913_ssl_RAND_status_impl(PyModuleDef *module)
3914/*[clinic end generated code: output=7f7ef57bc7dd1d1c input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003915{
Christian Heimes217cfd12007-12-02 14:31:20 +00003916 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003917}
3918
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003919#ifdef HAVE_RAND_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003920/*[clinic input]
3921_ssl.RAND_egd
3922 path: object(converter="PyUnicode_FSConverter")
3923 /
3924
3925Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3926
3927Returns number of bytes read. Raises SSLError if connection to EGD
3928fails or if it does not provide enough data to seed PRNG.
3929[clinic start generated code]*/
3930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003931static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003932_ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path)
3933/*[clinic end generated code: output=8e728e501e28541b input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003934{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003936 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003937 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003938 PyErr_SetString(PySSLErrorObject,
3939 "EGD connection failed or EGD did not return "
3940 "enough data to seed the PRNG");
3941 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003942 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003943 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003944}
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003945#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003946
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003948
3949/*[clinic input]
3950_ssl.get_default_verify_paths
3951
3952Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3953
3954The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3955[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003956
3957static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003958_ssl_get_default_verify_paths_impl(PyModuleDef *module)
3959/*[clinic end generated code: output=5a2820ce7e3304d3 input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003960{
3961 PyObject *ofile_env = NULL;
3962 PyObject *ofile = NULL;
3963 PyObject *odir_env = NULL;
3964 PyObject *odir = NULL;
3965
Benjamin Petersond113c962015-07-18 10:59:13 -07003966#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003967 const char *tmp = (info); \
3968 target = NULL; \
3969 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3970 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3971 target = PyBytes_FromString(tmp); } \
3972 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08003973 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02003974
Benjamin Petersond113c962015-07-18 10:59:13 -07003975 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3976 CONVERT(X509_get_default_cert_file(), ofile);
3977 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3978 CONVERT(X509_get_default_cert_dir(), odir);
3979#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02003980
Christian Heimes200bb1b2013-06-14 15:14:29 +02003981 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003982
3983 error:
3984 Py_XDECREF(ofile_env);
3985 Py_XDECREF(ofile);
3986 Py_XDECREF(odir_env);
3987 Py_XDECREF(odir);
3988 return NULL;
3989}
3990
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003991static PyObject*
3992asn1obj2py(ASN1_OBJECT *obj)
3993{
3994 int nid;
3995 const char *ln, *sn;
3996 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003997 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003998
3999 nid = OBJ_obj2nid(obj);
4000 if (nid == NID_undef) {
4001 PyErr_Format(PyExc_ValueError, "Unknown object");
4002 return NULL;
4003 }
4004 sn = OBJ_nid2sn(nid);
4005 ln = OBJ_nid2ln(nid);
4006 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4007 if (buflen < 0) {
4008 _setSSLError(NULL, 0, __FILE__, __LINE__);
4009 return NULL;
4010 }
4011 if (buflen) {
4012 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4013 } else {
4014 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4015 }
4016}
4017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004018/*[clinic input]
4019_ssl.txt2obj
4020 txt: str
4021 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004023Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4024
4025By default objects are looked up by OID. With name=True short and
4026long name are also matched.
4027[clinic start generated code]*/
4028
4029static PyObject *
4030_ssl_txt2obj_impl(PyModuleDef *module, const char *txt, int name)
4031/*[clinic end generated code: output=2ae2c30531b8809f input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004032{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004033 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004034 ASN1_OBJECT *obj;
4035
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004036 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4037 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004038 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004039 return NULL;
4040 }
4041 result = asn1obj2py(obj);
4042 ASN1_OBJECT_free(obj);
4043 return result;
4044}
4045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004046/*[clinic input]
4047_ssl.nid2obj
4048 nid: int
4049 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004051Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4052[clinic start generated code]*/
4053
4054static PyObject *
4055_ssl_nid2obj_impl(PyModuleDef *module, int nid)
4056/*[clinic end generated code: output=8db1df89e44badb8 input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004057{
4058 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004059 ASN1_OBJECT *obj;
4060
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004061 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004062 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004063 return NULL;
4064 }
4065 obj = OBJ_nid2obj(nid);
4066 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004067 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004068 return NULL;
4069 }
4070 result = asn1obj2py(obj);
4071 ASN1_OBJECT_free(obj);
4072 return result;
4073}
4074
Christian Heimes46bebee2013-06-09 19:03:31 +02004075#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004076
4077static PyObject*
4078certEncodingType(DWORD encodingType)
4079{
4080 static PyObject *x509_asn = NULL;
4081 static PyObject *pkcs_7_asn = NULL;
4082
4083 if (x509_asn == NULL) {
4084 x509_asn = PyUnicode_InternFromString("x509_asn");
4085 if (x509_asn == NULL)
4086 return NULL;
4087 }
4088 if (pkcs_7_asn == NULL) {
4089 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4090 if (pkcs_7_asn == NULL)
4091 return NULL;
4092 }
4093 switch(encodingType) {
4094 case X509_ASN_ENCODING:
4095 Py_INCREF(x509_asn);
4096 return x509_asn;
4097 case PKCS_7_ASN_ENCODING:
4098 Py_INCREF(pkcs_7_asn);
4099 return pkcs_7_asn;
4100 default:
4101 return PyLong_FromLong(encodingType);
4102 }
4103}
4104
4105static PyObject*
4106parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4107{
4108 CERT_ENHKEY_USAGE *usage;
4109 DWORD size, error, i;
4110 PyObject *retval;
4111
4112 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4113 error = GetLastError();
4114 if (error == CRYPT_E_NOT_FOUND) {
4115 Py_RETURN_TRUE;
4116 }
4117 return PyErr_SetFromWindowsErr(error);
4118 }
4119
4120 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4121 if (usage == NULL) {
4122 return PyErr_NoMemory();
4123 }
4124
4125 /* Now get the actual enhanced usage property */
4126 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4127 PyMem_Free(usage);
4128 error = GetLastError();
4129 if (error == CRYPT_E_NOT_FOUND) {
4130 Py_RETURN_TRUE;
4131 }
4132 return PyErr_SetFromWindowsErr(error);
4133 }
4134 retval = PySet_New(NULL);
4135 if (retval == NULL) {
4136 goto error;
4137 }
4138 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4139 if (usage->rgpszUsageIdentifier[i]) {
4140 PyObject *oid;
4141 int err;
4142 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4143 if (oid == NULL) {
4144 Py_CLEAR(retval);
4145 goto error;
4146 }
4147 err = PySet_Add(retval, oid);
4148 Py_DECREF(oid);
4149 if (err == -1) {
4150 Py_CLEAR(retval);
4151 goto error;
4152 }
4153 }
4154 }
4155 error:
4156 PyMem_Free(usage);
4157 return retval;
4158}
4159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160/*[clinic input]
4161_ssl.enum_certificates
4162 store_name: str
4163
4164Retrieve certificates from Windows' cert store.
4165
4166store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4167more cert storages, too. The function returns a list of (bytes,
4168encoding_type, trust) tuples. The encoding_type flag can be interpreted
4169with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4170a set of OIDs or the boolean True.
4171[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004172
Christian Heimes46bebee2013-06-09 19:03:31 +02004173static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174_ssl_enum_certificates_impl(PyModuleDef *module, const char *store_name)
4175/*[clinic end generated code: output=cc4ebc10b8adacfc input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004176{
Christian Heimes46bebee2013-06-09 19:03:31 +02004177 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004178 PCCERT_CONTEXT pCertCtx = NULL;
4179 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004180 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004181
Christian Heimes44109d72013-11-22 01:51:30 +01004182 result = PyList_New(0);
4183 if (result == NULL) {
4184 return NULL;
4185 }
4186 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4187 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004188 Py_DECREF(result);
4189 return PyErr_SetFromWindowsErr(GetLastError());
4190 }
4191
Christian Heimes44109d72013-11-22 01:51:30 +01004192 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4193 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4194 pCertCtx->cbCertEncoded);
4195 if (!cert) {
4196 Py_CLEAR(result);
4197 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004198 }
Christian Heimes44109d72013-11-22 01:51:30 +01004199 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4200 Py_CLEAR(result);
4201 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004202 }
Christian Heimes44109d72013-11-22 01:51:30 +01004203 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4204 if (keyusage == Py_True) {
4205 Py_DECREF(keyusage);
4206 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004207 }
Christian Heimes44109d72013-11-22 01:51:30 +01004208 if (keyusage == NULL) {
4209 Py_CLEAR(result);
4210 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004211 }
Christian Heimes44109d72013-11-22 01:51:30 +01004212 if ((tup = PyTuple_New(3)) == NULL) {
4213 Py_CLEAR(result);
4214 break;
4215 }
4216 PyTuple_SET_ITEM(tup, 0, cert);
4217 cert = NULL;
4218 PyTuple_SET_ITEM(tup, 1, enc);
4219 enc = NULL;
4220 PyTuple_SET_ITEM(tup, 2, keyusage);
4221 keyusage = NULL;
4222 if (PyList_Append(result, tup) < 0) {
4223 Py_CLEAR(result);
4224 break;
4225 }
4226 Py_CLEAR(tup);
4227 }
4228 if (pCertCtx) {
4229 /* loop ended with an error, need to clean up context manually */
4230 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004231 }
4232
4233 /* In error cases cert, enc and tup may not be NULL */
4234 Py_XDECREF(cert);
4235 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004236 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004237 Py_XDECREF(tup);
4238
4239 if (!CertCloseStore(hStore, 0)) {
4240 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004241 Py_XDECREF(result);
4242 return PyErr_SetFromWindowsErr(GetLastError());
4243 }
4244 return result;
4245}
4246
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004247/*[clinic input]
4248_ssl.enum_crls
4249 store_name: str
4250
4251Retrieve CRLs from Windows' cert store.
4252
4253store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4254more cert storages, too. The function returns a list of (bytes,
4255encoding_type) tuples. The encoding_type flag can be interpreted with
4256X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4257[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004258
4259static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004260_ssl_enum_crls_impl(PyModuleDef *module, const char *store_name)
4261/*[clinic end generated code: output=763490a2aa1c50d5 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004262{
Christian Heimes44109d72013-11-22 01:51:30 +01004263 HCERTSTORE hStore = NULL;
4264 PCCRL_CONTEXT pCrlCtx = NULL;
4265 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4266 PyObject *result = NULL;
4267
Christian Heimes44109d72013-11-22 01:51:30 +01004268 result = PyList_New(0);
4269 if (result == NULL) {
4270 return NULL;
4271 }
4272 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4273 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004274 Py_DECREF(result);
4275 return PyErr_SetFromWindowsErr(GetLastError());
4276 }
Christian Heimes44109d72013-11-22 01:51:30 +01004277
4278 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4279 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4280 pCrlCtx->cbCrlEncoded);
4281 if (!crl) {
4282 Py_CLEAR(result);
4283 break;
4284 }
4285 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4286 Py_CLEAR(result);
4287 break;
4288 }
4289 if ((tup = PyTuple_New(2)) == NULL) {
4290 Py_CLEAR(result);
4291 break;
4292 }
4293 PyTuple_SET_ITEM(tup, 0, crl);
4294 crl = NULL;
4295 PyTuple_SET_ITEM(tup, 1, enc);
4296 enc = NULL;
4297
4298 if (PyList_Append(result, tup) < 0) {
4299 Py_CLEAR(result);
4300 break;
4301 }
4302 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004303 }
Christian Heimes44109d72013-11-22 01:51:30 +01004304 if (pCrlCtx) {
4305 /* loop ended with an error, need to clean up context manually */
4306 CertFreeCRLContext(pCrlCtx);
4307 }
4308
4309 /* In error cases cert, enc and tup may not be NULL */
4310 Py_XDECREF(crl);
4311 Py_XDECREF(enc);
4312 Py_XDECREF(tup);
4313
4314 if (!CertCloseStore(hStore, 0)) {
4315 /* This error case might shadow another exception.*/
4316 Py_XDECREF(result);
4317 return PyErr_SetFromWindowsErr(GetLastError());
4318 }
4319 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004320}
Christian Heimes44109d72013-11-22 01:51:30 +01004321
4322#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004323
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004324/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004325static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004326 _SSL__TEST_DECODE_CERT_METHODDEF
4327 _SSL_RAND_ADD_METHODDEF
4328 _SSL_RAND_BYTES_METHODDEF
4329 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4330 _SSL_RAND_EGD_METHODDEF
4331 _SSL_RAND_STATUS_METHODDEF
4332 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4333 _SSL_ENUM_CERTIFICATES_METHODDEF
4334 _SSL_ENUM_CRLS_METHODDEF
4335 _SSL_TXT2OBJ_METHODDEF
4336 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004337 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004338};
4339
4340
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341#ifdef WITH_THREAD
4342
4343/* an implementation of OpenSSL threading operations in terms
4344 of the Python C thread library */
4345
4346static PyThread_type_lock *_ssl_locks = NULL;
4347
Christian Heimes4d98ca92013-08-19 17:36:29 +02004348#if OPENSSL_VERSION_NUMBER >= 0x10000000
4349/* use new CRYPTO_THREADID API. */
4350static void
4351_ssl_threadid_callback(CRYPTO_THREADID *id)
4352{
4353 CRYPTO_THREADID_set_numeric(id,
4354 (unsigned long)PyThread_get_thread_ident());
4355}
4356#else
4357/* deprecated CRYPTO_set_id_callback() API. */
4358static unsigned long
4359_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004360 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004362#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004363
Bill Janssen6e027db2007-11-15 22:23:56 +00004364static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004365 (int mode, int n, const char *file, int line) {
4366 /* this function is needed to perform locking on shared data
4367 structures. (Note that OpenSSL uses a number of global data
4368 structures that will be implicitly shared whenever multiple
4369 threads use OpenSSL.) Multi-threaded applications will
4370 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004372 locking_function() must be able to handle up to
4373 CRYPTO_num_locks() different mutex locks. It sets the n-th
4374 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004376 file and line are the file number of the function setting the
4377 lock. They can be useful for debugging.
4378 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004380 if ((_ssl_locks == NULL) ||
4381 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4382 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004384 if (mode & CRYPTO_LOCK) {
4385 PyThread_acquire_lock(_ssl_locks[n], 1);
4386 } else {
4387 PyThread_release_lock(_ssl_locks[n]);
4388 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389}
4390
4391static int _setup_ssl_threads(void) {
4392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004393 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004395 if (_ssl_locks == NULL) {
4396 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004397 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4398 if (_ssl_locks == NULL) {
4399 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004400 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004401 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004402 memset(_ssl_locks, 0,
4403 sizeof(PyThread_type_lock) * _ssl_locks_count);
4404 for (i = 0; i < _ssl_locks_count; i++) {
4405 _ssl_locks[i] = PyThread_allocate_lock();
4406 if (_ssl_locks[i] == NULL) {
4407 unsigned int j;
4408 for (j = 0; j < i; j++) {
4409 PyThread_free_lock(_ssl_locks[j]);
4410 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004411 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004412 return 0;
4413 }
4414 }
4415 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004416#if OPENSSL_VERSION_NUMBER >= 0x10000000
4417 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4418#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004419 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004420#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004421 }
4422 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423}
4424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004425#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004427PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004428"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004429for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004430
Martin v. Löwis1a214512008-06-11 05:26:20 +00004431
4432static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004433 PyModuleDef_HEAD_INIT,
4434 "_ssl",
4435 module_doc,
4436 -1,
4437 PySSL_methods,
4438 NULL,
4439 NULL,
4440 NULL,
4441 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004442};
4443
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004444
4445static void
4446parse_openssl_version(unsigned long libver,
4447 unsigned int *major, unsigned int *minor,
4448 unsigned int *fix, unsigned int *patch,
4449 unsigned int *status)
4450{
4451 *status = libver & 0xF;
4452 libver >>= 4;
4453 *patch = libver & 0xFF;
4454 libver >>= 8;
4455 *fix = libver & 0xFF;
4456 libver >>= 8;
4457 *minor = libver & 0xFF;
4458 libver >>= 8;
4459 *major = libver & 0xFF;
4460}
4461
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004462PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004463PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004464{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004465 PyObject *m, *d, *r;
4466 unsigned long libver;
4467 unsigned int major, minor, fix, patch, status;
4468 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004469 struct py_ssl_error_code *errcode;
4470 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004471
Antoine Pitrou152efa22010-05-16 18:19:27 +00004472 if (PyType_Ready(&PySSLContext_Type) < 0)
4473 return NULL;
4474 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004475 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004476 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4477 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004479 m = PyModule_Create(&_sslmodule);
4480 if (m == NULL)
4481 return NULL;
4482 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004484 /* Load _socket module and its C API */
4485 socket_api = PySocketModule_ImportModuleAndAPI();
4486 if (!socket_api)
4487 return NULL;
4488 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004490 /* Init OpenSSL */
4491 SSL_load_error_strings();
4492 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004493#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004494 /* note that this will start threading if not already started */
4495 if (!_setup_ssl_threads()) {
4496 return NULL;
4497 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004499 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004501 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004502 sslerror_type_slots[0].pfunc = PyExc_OSError;
4503 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004504 if (PySSLErrorObject == NULL)
4505 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004506
Antoine Pitrou41032a62011-10-27 23:56:55 +02004507 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4508 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4509 PySSLErrorObject, NULL);
4510 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4511 "ssl.SSLWantReadError", SSLWantReadError_doc,
4512 PySSLErrorObject, NULL);
4513 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4514 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4515 PySSLErrorObject, NULL);
4516 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4517 "ssl.SSLSyscallError", SSLSyscallError_doc,
4518 PySSLErrorObject, NULL);
4519 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4520 "ssl.SSLEOFError", SSLEOFError_doc,
4521 PySSLErrorObject, NULL);
4522 if (PySSLZeroReturnErrorObject == NULL
4523 || PySSLWantReadErrorObject == NULL
4524 || PySSLWantWriteErrorObject == NULL
4525 || PySSLSyscallErrorObject == NULL
4526 || PySSLEOFErrorObject == NULL)
4527 return NULL;
4528 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4529 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4530 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4531 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4532 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4533 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004534 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004535 if (PyDict_SetItemString(d, "_SSLContext",
4536 (PyObject *)&PySSLContext_Type) != 0)
4537 return NULL;
4538 if (PyDict_SetItemString(d, "_SSLSocket",
4539 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004540 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004541 if (PyDict_SetItemString(d, "MemoryBIO",
4542 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4543 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004544 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4545 PY_SSL_ERROR_ZERO_RETURN);
4546 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4547 PY_SSL_ERROR_WANT_READ);
4548 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4549 PY_SSL_ERROR_WANT_WRITE);
4550 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4551 PY_SSL_ERROR_WANT_X509_LOOKUP);
4552 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4553 PY_SSL_ERROR_SYSCALL);
4554 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4555 PY_SSL_ERROR_SSL);
4556 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4557 PY_SSL_ERROR_WANT_CONNECT);
4558 /* non ssl.h errorcodes */
4559 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4560 PY_SSL_ERROR_EOF);
4561 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4562 PY_SSL_ERROR_INVALID_ERROR_CODE);
4563 /* cert requirements */
4564 PyModule_AddIntConstant(m, "CERT_NONE",
4565 PY_SSL_CERT_NONE);
4566 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4567 PY_SSL_CERT_OPTIONAL);
4568 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4569 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004570 /* CRL verification for verification_flags */
4571 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4572 0);
4573 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4574 X509_V_FLAG_CRL_CHECK);
4575 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4576 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4577 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4578 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004579#ifdef X509_V_FLAG_TRUSTED_FIRST
4580 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4581 X509_V_FLAG_TRUSTED_FIRST);
4582#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004583
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004584 /* Alert Descriptions from ssl.h */
4585 /* note RESERVED constants no longer intended for use have been removed */
4586 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4587
4588#define ADD_AD_CONSTANT(s) \
4589 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4590 SSL_AD_##s)
4591
4592 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4593 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4594 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4595 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4596 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4597 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4598 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4599 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4600 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4601 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4602 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4603 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4604 ADD_AD_CONSTANT(UNKNOWN_CA);
4605 ADD_AD_CONSTANT(ACCESS_DENIED);
4606 ADD_AD_CONSTANT(DECODE_ERROR);
4607 ADD_AD_CONSTANT(DECRYPT_ERROR);
4608 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4609 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4610 ADD_AD_CONSTANT(INTERNAL_ERROR);
4611 ADD_AD_CONSTANT(USER_CANCELLED);
4612 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004613 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004614#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4615 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4616#endif
4617#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4618 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4619#endif
4620#ifdef SSL_AD_UNRECOGNIZED_NAME
4621 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4622#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004623#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4624 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4625#endif
4626#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4627 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4628#endif
4629#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4630 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4631#endif
4632
4633#undef ADD_AD_CONSTANT
4634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004635 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004636#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004637 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4638 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004639#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004640#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004641 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4642 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004643#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004644 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4645 PY_SSL_VERSION_SSL23);
4646 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4647 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004648#if HAVE_TLSv1_2
4649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4650 PY_SSL_VERSION_TLS1_1);
4651 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4652 PY_SSL_VERSION_TLS1_2);
4653#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004654
Antoine Pitroub5218772010-05-21 09:56:06 +00004655 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004656 PyModule_AddIntConstant(m, "OP_ALL",
4657 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004658 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4659 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4660 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004661#if HAVE_TLSv1_2
4662 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4663 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4664#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004665 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4666 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004667 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004668#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004669 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004670#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004671#ifdef SSL_OP_NO_COMPRESSION
4672 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4673 SSL_OP_NO_COMPRESSION);
4674#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004675
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004676#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004677 r = Py_True;
4678#else
4679 r = Py_False;
4680#endif
4681 Py_INCREF(r);
4682 PyModule_AddObject(m, "HAS_SNI", r);
4683
Antoine Pitroud6494802011-07-21 01:11:30 +02004684 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004685 Py_INCREF(r);
4686 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4687
Antoine Pitrou501da612011-12-21 09:27:41 +01004688#ifdef OPENSSL_NO_ECDH
4689 r = Py_False;
4690#else
4691 r = Py_True;
4692#endif
4693 Py_INCREF(r);
4694 PyModule_AddObject(m, "HAS_ECDH", r);
4695
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004696#ifdef OPENSSL_NPN_NEGOTIATED
4697 r = Py_True;
4698#else
4699 r = Py_False;
4700#endif
4701 Py_INCREF(r);
4702 PyModule_AddObject(m, "HAS_NPN", r);
4703
Benjamin Petersoncca27322015-01-23 16:35:37 -05004704#ifdef HAVE_ALPN
4705 r = Py_True;
4706#else
4707 r = Py_False;
4708#endif
4709 Py_INCREF(r);
4710 PyModule_AddObject(m, "HAS_ALPN", r);
4711
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004712 /* Mappings for error codes */
4713 err_codes_to_names = PyDict_New();
4714 err_names_to_codes = PyDict_New();
4715 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4716 return NULL;
4717 errcode = error_codes;
4718 while (errcode->mnemonic != NULL) {
4719 PyObject *mnemo, *key;
4720 mnemo = PyUnicode_FromString(errcode->mnemonic);
4721 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4722 if (mnemo == NULL || key == NULL)
4723 return NULL;
4724 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4725 return NULL;
4726 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4727 return NULL;
4728 Py_DECREF(key);
4729 Py_DECREF(mnemo);
4730 errcode++;
4731 }
4732 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4733 return NULL;
4734 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4735 return NULL;
4736
4737 lib_codes_to_names = PyDict_New();
4738 if (lib_codes_to_names == NULL)
4739 return NULL;
4740 libcode = library_codes;
4741 while (libcode->library != NULL) {
4742 PyObject *mnemo, *key;
4743 key = PyLong_FromLong(libcode->code);
4744 mnemo = PyUnicode_FromString(libcode->library);
4745 if (key == NULL || mnemo == NULL)
4746 return NULL;
4747 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4748 return NULL;
4749 Py_DECREF(key);
4750 Py_DECREF(mnemo);
4751 libcode++;
4752 }
4753 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4754 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004756 /* OpenSSL version */
4757 /* SSLeay() gives us the version of the library linked against,
4758 which could be different from the headers version.
4759 */
4760 libver = SSLeay();
4761 r = PyLong_FromUnsignedLong(libver);
4762 if (r == NULL)
4763 return NULL;
4764 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4765 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004766 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004767 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4768 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4769 return NULL;
4770 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4771 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4772 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004773
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004774 libver = OPENSSL_VERSION_NUMBER;
4775 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4776 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4777 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4778 return NULL;
4779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004780 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004781}