blob: 29e7469b625f816d2139aa15b7bd7fcbb41b3458 [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
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000112enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000113 /* these mirror ssl.h */
114 PY_SSL_ERROR_NONE,
115 PY_SSL_ERROR_SSL,
116 PY_SSL_ERROR_WANT_READ,
117 PY_SSL_ERROR_WANT_WRITE,
118 PY_SSL_ERROR_WANT_X509_LOOKUP,
119 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
120 PY_SSL_ERROR_ZERO_RETURN,
121 PY_SSL_ERROR_WANT_CONNECT,
122 /* start of non ssl.h errorcodes */
123 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
124 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
125 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000126};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127
Thomas Woutersed03b412007-08-28 21:37:11 +0000128enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000129 PY_SSL_CLIENT,
130 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000131};
132
133enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000134 PY_SSL_CERT_NONE,
135 PY_SSL_CERT_OPTIONAL,
136 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000137};
138
139enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000140 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200141 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000142 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100143#if HAVE_TLSv1_2
144 PY_SSL_VERSION_TLS1,
145 PY_SSL_VERSION_TLS1_1,
146 PY_SSL_VERSION_TLS1_2
147#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000148 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000149#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100150};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200151
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000152#ifdef WITH_THREAD
153
154/* serves as a flag to see whether we've initialized the SSL thread support. */
155/* 0 means no, greater than 0 means yes */
156
157static unsigned int _ssl_locks_count = 0;
158
159#endif /* def WITH_THREAD */
160
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161/* SSL socket object */
162
163#define X509_NAME_MAXLEN 256
164
165/* RAND_* APIs got added to OpenSSL in 0.9.5 */
166#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
167# define HAVE_OPENSSL_RAND 1
168#else
169# undef HAVE_OPENSSL_RAND
170#endif
171
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000172/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
173 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
174 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
175#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000176# define HAVE_SSL_CTX_CLEAR_OPTIONS
177#else
178# undef HAVE_SSL_CTX_CLEAR_OPTIONS
179#endif
180
Antoine Pitroud6494802011-07-21 01:11:30 +0200181/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
182 * older SSL, but let's be safe */
183#define PySSL_CB_MAXLEN 128
184
185/* SSL_get_finished got added to OpenSSL in 0.9.5 */
186#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
187# define HAVE_OPENSSL_FINISHED 1
188#else
189# define HAVE_OPENSSL_FINISHED 0
190#endif
191
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100192/* ECDH support got added to OpenSSL in 0.9.8 */
193#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
194# define OPENSSL_NO_ECDH
195#endif
196
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100197/* compression support got added to OpenSSL in 0.9.8 */
198#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
199# define OPENSSL_NO_COMP
200#endif
201
Christian Heimes2427b502013-11-23 11:24:32 +0100202/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
203#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
204# define HAVE_OPENSSL_VERIFY_PARAM
205#endif
206
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100207
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000208typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100211#ifdef OPENSSL_NPN_NEGOTIATED
212 char *npn_protocols;
213 int npn_protocols_len;
214#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100215#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200216 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100217#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100218 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000220
Antoine Pitrou152efa22010-05-16 18:19:27 +0000221typedef struct {
222 PyObject_HEAD
223 PyObject *Socket; /* weakref to socket on which we're layered */
224 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100225 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000226 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200227 char shutdown_seen_zero;
228 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200229 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200230 PyObject *owner; /* Python level "owner" passed to servername callback */
231 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000233
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200234typedef struct {
235 PyObject_HEAD
236 BIO *bio;
237 int eof_written;
238} PySSLMemoryBIO;
239
Antoine Pitrou152efa22010-05-16 18:19:27 +0000240static PyTypeObject PySSLContext_Type;
241static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200242static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000243
244static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
245static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000246static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000247 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000248static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
249static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000250
Antoine Pitrou152efa22010-05-16 18:19:27 +0000251#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
252#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200253#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000254
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000255typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000256 SOCKET_IS_NONBLOCKING,
257 SOCKET_IS_BLOCKING,
258 SOCKET_HAS_TIMED_OUT,
259 SOCKET_HAS_BEEN_CLOSED,
260 SOCKET_TOO_LARGE_FOR_SELECT,
261 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000262} timeout_state;
263
Thomas Woutersed03b412007-08-28 21:37:11 +0000264/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000265#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200266#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000267
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200268/* Get the socket from a PySSLSocket, if it has one */
269#define GET_SOCKET(obj) ((obj)->Socket ? \
270 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200271
272/*
273 * SSL errors.
274 */
275
276PyDoc_STRVAR(SSLError_doc,
277"An error occurred in the SSL implementation.");
278
279PyDoc_STRVAR(SSLZeroReturnError_doc,
280"SSL/TLS session closed cleanly.");
281
282PyDoc_STRVAR(SSLWantReadError_doc,
283"Non-blocking SSL socket needs to read more data\n"
284"before the requested operation can be completed.");
285
286PyDoc_STRVAR(SSLWantWriteError_doc,
287"Non-blocking SSL socket needs to write more data\n"
288"before the requested operation can be completed.");
289
290PyDoc_STRVAR(SSLSyscallError_doc,
291"System error when attempting SSL operation.");
292
293PyDoc_STRVAR(SSLEOFError_doc,
294"SSL/TLS connection terminated abruptly.");
295
296static PyObject *
297SSLError_str(PyOSErrorObject *self)
298{
299 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
300 Py_INCREF(self->strerror);
301 return self->strerror;
302 }
303 else
304 return PyObject_Str(self->args);
305}
306
307static PyType_Slot sslerror_type_slots[] = {
308 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
309 {Py_tp_doc, SSLError_doc},
310 {Py_tp_str, SSLError_str},
311 {0, 0},
312};
313
314static PyType_Spec sslerror_type_spec = {
315 "ssl.SSLError",
316 sizeof(PyOSErrorObject),
317 0,
318 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
319 sslerror_type_slots
320};
321
322static void
323fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
324 int lineno, unsigned long errcode)
325{
326 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
327 PyObject *init_value, *msg, *key;
328 _Py_IDENTIFIER(reason);
329 _Py_IDENTIFIER(library);
330
331 if (errcode != 0) {
332 int lib, reason;
333
334 lib = ERR_GET_LIB(errcode);
335 reason = ERR_GET_REASON(errcode);
336 key = Py_BuildValue("ii", lib, reason);
337 if (key == NULL)
338 goto fail;
339 reason_obj = PyDict_GetItem(err_codes_to_names, key);
340 Py_DECREF(key);
341 if (reason_obj == NULL) {
342 /* XXX if reason < 100, it might reflect a library number (!!) */
343 PyErr_Clear();
344 }
345 key = PyLong_FromLong(lib);
346 if (key == NULL)
347 goto fail;
348 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
349 Py_DECREF(key);
350 if (lib_obj == NULL) {
351 PyErr_Clear();
352 }
353 if (errstr == NULL)
354 errstr = ERR_reason_error_string(errcode);
355 }
356 if (errstr == NULL)
357 errstr = "unknown error";
358
359 if (reason_obj && lib_obj)
360 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
361 lib_obj, reason_obj, errstr, lineno);
362 else if (lib_obj)
363 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
364 lib_obj, errstr, lineno);
365 else
366 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 if (msg == NULL)
368 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100369
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200370 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100371 if (init_value == NULL)
372 goto fail;
373
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200374 err_value = PyObject_CallObject(type, init_value);
375 Py_DECREF(init_value);
376 if (err_value == NULL)
377 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100378
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200379 if (reason_obj == NULL)
380 reason_obj = Py_None;
381 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
382 goto fail;
383 if (lib_obj == NULL)
384 lib_obj = Py_None;
385 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
386 goto fail;
387 PyErr_SetObject(type, err_value);
388fail:
389 Py_XDECREF(err_value);
390}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000391
392static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000393PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000394{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200396 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 int err;
398 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200399 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200402 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 if (obj->ssl != NULL) {
405 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000406
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 switch (err) {
408 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200409 errstr = "TLS/SSL connection has been closed (EOF)";
410 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 p = PY_SSL_ERROR_ZERO_RETURN;
412 break;
413 case SSL_ERROR_WANT_READ:
414 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200415 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 p = PY_SSL_ERROR_WANT_READ;
417 break;
418 case SSL_ERROR_WANT_WRITE:
419 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200420 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 errstr = "The operation did not complete (write)";
422 break;
423 case SSL_ERROR_WANT_X509_LOOKUP:
424 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 break;
427 case SSL_ERROR_WANT_CONNECT:
428 p = PY_SSL_ERROR_WANT_CONNECT;
429 errstr = "The operation did not complete (connect)";
430 break;
431 case SSL_ERROR_SYSCALL:
432 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200434 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200437 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000438 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200439 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000440 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000441 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000442 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200443 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000444 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200445 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000447 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200448 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000449 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 }
451 } else {
452 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000453 }
454 break;
455 }
456 case SSL_ERROR_SSL:
457 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 if (e == 0)
460 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000461 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000462 break;
463 }
464 default:
465 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
466 errstr = "Invalid error code";
467 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000470 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000472}
473
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000474static PyObject *
475_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
476
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200477 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200479 else
480 errcode = 0;
481 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000482 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484}
485
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200486/*
487 * SSL objects
488 */
489
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100491newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000492 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200493 char *server_hostname,
494 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000496 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200498 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200499 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000500
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 if (self == NULL)
503 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 self->peer_cert = NULL;
506 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000507 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100508 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200509 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200510 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200511 self->owner = NULL;
512 if (server_hostname != NULL) {
513 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
514 "idna", "strict");
515 if (hostname == NULL) {
516 Py_DECREF(self);
517 return NULL;
518 }
519 self->server_hostname = hostname;
520 } else
521 self->server_hostname = NULL;
522
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100523 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 /* Make sure the SSL error state is initialized */
526 (void) ERR_get_state();
527 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000530 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200532 SSL_set_app_data(self->ssl, self);
533 if (sock) {
534 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
535 } else {
536 /* BIOs are reference counted and SSL_set_bio borrows our reference.
537 * To prevent a double free in memory_bio_dealloc() we need to take an
538 * extra reference here. */
539 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
540 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
541 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
542 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200543 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000544#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200545 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000546#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200547 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000548
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100549#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000550 if (server_hostname != NULL)
551 SSL_set_tlsext_host_name(self->ssl, server_hostname);
552#endif
553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 /* If the socket is in non-blocking mode or timeout mode, set the BIO
555 * to non-blocking mode (blocking is the default)
556 */
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200557 if (sock && sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
559 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
560 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 PySSL_BEGIN_ALLOW_THREADS
563 if (socket_type == PY_SSL_CLIENT)
564 SSL_set_connect_state(self->ssl);
565 else
566 SSL_set_accept_state(self->ssl);
567 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000568
Antoine Pitroud6494802011-07-21 01:11:30 +0200569 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200570 if (sock != NULL) {
571 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
572 if (self->Socket == NULL) {
573 Py_DECREF(self);
574 Py_XDECREF(self->server_hostname);
575 return NULL;
576 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000579}
580
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000581/* SSL object methods */
582
Antoine Pitrou152efa22010-05-16 18:19:27 +0000583static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000584{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 int ret;
586 int err;
587 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200588 PySocketSockObject *sock = GET_SOCKET(self);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000589
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200590 if (sock) {
591 if (((PyObject*)sock) == Py_None) {
592 _setSSLError("Underlying socket connection gone",
593 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
594 return NULL;
595 }
596 Py_INCREF(sock);
597
598 /* just in case the blocking state of the socket has been changed */
599 nonblocking = (sock->sock_timeout >= 0.0);
600 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
601 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 /* Actually negotiate SSL connection */
605 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000607 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 ret = SSL_do_handshake(self->ssl);
609 err = SSL_get_error(self->ssl, ret);
610 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000611 if (PyErr_CheckSignals())
612 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 if (err == SSL_ERROR_WANT_READ) {
614 sockstate = check_socket_and_wait_for_timeout(sock, 0);
615 } else if (err == SSL_ERROR_WANT_WRITE) {
616 sockstate = check_socket_and_wait_for_timeout(sock, 1);
617 } else {
618 sockstate = SOCKET_OPERATION_OK;
619 }
620 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000621 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000623 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
625 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000626 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000627 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
629 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000630 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000631 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
633 break;
634 }
635 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200636 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 if (ret < 1)
638 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 if (self->peer_cert)
641 X509_free (self->peer_cert);
642 PySSL_BEGIN_ALLOW_THREADS
643 self->peer_cert = SSL_get_peer_certificate(self->ssl);
644 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200645 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646
647 Py_INCREF(Py_None);
648 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000649
650error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200651 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000652 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000653}
654
Thomas Woutersed03b412007-08-28 21:37:11 +0000655static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 char namebuf[X509_NAME_MAXLEN];
659 int buflen;
660 PyObject *name_obj;
661 PyObject *value_obj;
662 PyObject *attr;
663 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
666 if (buflen < 0) {
667 _setSSLError(NULL, 0, __FILE__, __LINE__);
668 goto fail;
669 }
670 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
671 if (name_obj == NULL)
672 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
675 if (buflen < 0) {
676 _setSSLError(NULL, 0, __FILE__, __LINE__);
677 Py_DECREF(name_obj);
678 goto fail;
679 }
680 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000681 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 OPENSSL_free(valuebuf);
683 if (value_obj == NULL) {
684 Py_DECREF(name_obj);
685 goto fail;
686 }
687 attr = PyTuple_New(2);
688 if (attr == NULL) {
689 Py_DECREF(name_obj);
690 Py_DECREF(value_obj);
691 goto fail;
692 }
693 PyTuple_SET_ITEM(attr, 0, name_obj);
694 PyTuple_SET_ITEM(attr, 1, value_obj);
695 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000696
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000699}
700
701static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000703{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
705 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
706 PyObject *rdnt;
707 PyObject *attr = NULL; /* tuple to hold an attribute */
708 int entry_count = X509_NAME_entry_count(xname);
709 X509_NAME_ENTRY *entry;
710 ASN1_OBJECT *name;
711 ASN1_STRING *value;
712 int index_counter;
713 int rdn_level = -1;
714 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 dn = PyList_New(0);
717 if (dn == NULL)
718 return NULL;
719 /* now create another tuple to hold the top-level RDN */
720 rdn = PyList_New(0);
721 if (rdn == NULL)
722 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 for (index_counter = 0;
725 index_counter < entry_count;
726 index_counter++)
727 {
728 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 /* check to see if we've gotten to a new RDN */
731 if (rdn_level >= 0) {
732 if (rdn_level != entry->set) {
733 /* yes, new RDN */
734 /* add old RDN to DN */
735 rdnt = PyList_AsTuple(rdn);
736 Py_DECREF(rdn);
737 if (rdnt == NULL)
738 goto fail0;
739 retcode = PyList_Append(dn, rdnt);
740 Py_DECREF(rdnt);
741 if (retcode < 0)
742 goto fail0;
743 /* create new RDN */
744 rdn = PyList_New(0);
745 if (rdn == NULL)
746 goto fail0;
747 }
748 }
749 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 /* now add this attribute to the current RDN */
752 name = X509_NAME_ENTRY_get_object(entry);
753 value = X509_NAME_ENTRY_get_data(entry);
754 attr = _create_tuple_for_attribute(name, value);
755 /*
756 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
757 entry->set,
758 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
759 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
760 */
761 if (attr == NULL)
762 goto fail1;
763 retcode = PyList_Append(rdn, attr);
764 Py_DECREF(attr);
765 if (retcode < 0)
766 goto fail1;
767 }
768 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100769 if (rdn != NULL) {
770 if (PyList_GET_SIZE(rdn) > 0) {
771 rdnt = PyList_AsTuple(rdn);
772 Py_DECREF(rdn);
773 if (rdnt == NULL)
774 goto fail0;
775 retcode = PyList_Append(dn, rdnt);
776 Py_DECREF(rdnt);
777 if (retcode < 0)
778 goto fail0;
779 }
780 else {
781 Py_DECREF(rdn);
782 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* convert list to tuple */
786 rdnt = PyList_AsTuple(dn);
787 Py_DECREF(dn);
788 if (rdnt == NULL)
789 return NULL;
790 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000791
792 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
795 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 Py_XDECREF(dn);
797 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798}
799
800static PyObject *
801_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* this code follows the procedure outlined in
804 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
805 function to extract the STACK_OF(GENERAL_NAME),
806 then iterates through the stack to add the
807 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 int i, j;
810 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200811 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 X509_EXTENSION *ext = NULL;
813 GENERAL_NAMES *names = NULL;
814 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000815 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 BIO *biobuf = NULL;
817 char buf[2048];
818 char *vptr;
819 int len;
820 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000821#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000823#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000825#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 if (certificate == NULL)
828 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 /* get a memory buffer */
831 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200833 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 while ((i = X509_get_ext_by_NID(
835 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 if (peer_alt_names == Py_None) {
838 peer_alt_names = PyList_New(0);
839 if (peer_alt_names == NULL)
840 goto fail;
841 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 /* now decode the altName */
844 ext = X509_get_ext(certificate, i);
845 if(!(method = X509V3_EXT_get(ext))) {
846 PyErr_SetString
847 (PySSLErrorObject,
848 ERRSTR("No method for internalizing subjectAltName!"));
849 goto fail;
850 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 p = ext->value->data;
853 if (method->it)
854 names = (GENERAL_NAMES*)
855 (ASN1_item_d2i(NULL,
856 &p,
857 ext->value->length,
858 ASN1_ITEM_ptr(method->it)));
859 else
860 names = (GENERAL_NAMES*)
861 (method->d2i(NULL,
862 &p,
863 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200867 int gntype;
868 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200871 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200872 switch (gntype) {
873 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000874 /* we special-case DirName as a tuple of
875 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 t = PyTuple_New(2);
878 if (t == NULL) {
879 goto fail;
880 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 v = PyUnicode_FromString("DirName");
883 if (v == NULL) {
884 Py_DECREF(t);
885 goto fail;
886 }
887 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 v = _create_tuple_for_X509_NAME (name->d.dirn);
890 if (v == NULL) {
891 Py_DECREF(t);
892 goto fail;
893 }
894 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000896
Christian Heimes824f7f32013-08-17 00:54:47 +0200897 case GEN_EMAIL:
898 case GEN_DNS:
899 case GEN_URI:
900 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
901 correctly, CVE-2013-4238 */
902 t = PyTuple_New(2);
903 if (t == NULL)
904 goto fail;
905 switch (gntype) {
906 case GEN_EMAIL:
907 v = PyUnicode_FromString("email");
908 as = name->d.rfc822Name;
909 break;
910 case GEN_DNS:
911 v = PyUnicode_FromString("DNS");
912 as = name->d.dNSName;
913 break;
914 case GEN_URI:
915 v = PyUnicode_FromString("URI");
916 as = name->d.uniformResourceIdentifier;
917 break;
918 }
919 if (v == NULL) {
920 Py_DECREF(t);
921 goto fail;
922 }
923 PyTuple_SET_ITEM(t, 0, v);
924 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
925 ASN1_STRING_length(as));
926 if (v == NULL) {
927 Py_DECREF(t);
928 goto fail;
929 }
930 PyTuple_SET_ITEM(t, 1, v);
931 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Christian Heimes824f7f32013-08-17 00:54:47 +0200933 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200935 switch (gntype) {
936 /* check for new general name type */
937 case GEN_OTHERNAME:
938 case GEN_X400:
939 case GEN_EDIPARTY:
940 case GEN_IPADD:
941 case GEN_RID:
942 break;
943 default:
944 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
945 "Unknown general name type %d",
946 gntype) == -1) {
947 goto fail;
948 }
949 break;
950 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 (void) BIO_reset(biobuf);
952 GENERAL_NAME_print(biobuf, name);
953 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
954 if (len < 0) {
955 _setSSLError(NULL, 0, __FILE__, __LINE__);
956 goto fail;
957 }
958 vptr = strchr(buf, ':');
959 if (vptr == NULL)
960 goto fail;
961 t = PyTuple_New(2);
962 if (t == NULL)
963 goto fail;
964 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
965 if (v == NULL) {
966 Py_DECREF(t);
967 goto fail;
968 }
969 PyTuple_SET_ITEM(t, 0, v);
970 v = PyUnicode_FromStringAndSize((vptr + 1),
971 (len - (vptr - buf + 1)));
972 if (v == NULL) {
973 Py_DECREF(t);
974 goto fail;
975 }
976 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200977 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 if (PyList_Append(peer_alt_names, t) < 0) {
983 Py_DECREF(t);
984 goto fail;
985 }
986 Py_DECREF(t);
987 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100988 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 }
990 BIO_free(biobuf);
991 if (peer_alt_names != Py_None) {
992 v = PyList_AsTuple(peer_alt_names);
993 Py_DECREF(peer_alt_names);
994 return v;
995 } else {
996 return peer_alt_names;
997 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000998
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999
1000 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 if (biobuf != NULL)
1002 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 if (peer_alt_names != Py_None) {
1005 Py_XDECREF(peer_alt_names);
1006 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009}
1010
1011static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001012_get_aia_uri(X509 *certificate, int nid) {
1013 PyObject *lst = NULL, *ostr = NULL;
1014 int i, result;
1015 AUTHORITY_INFO_ACCESS *info;
1016
1017 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1018 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
1019 return Py_None;
1020 }
1021
1022 if ((lst = PyList_New(0)) == NULL) {
1023 goto fail;
1024 }
1025
1026 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1027 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1028 ASN1_IA5STRING *uri;
1029
1030 if ((OBJ_obj2nid(ad->method) != nid) ||
1031 (ad->location->type != GEN_URI)) {
1032 continue;
1033 }
1034 uri = ad->location->d.uniformResourceIdentifier;
1035 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1036 uri->length);
1037 if (ostr == NULL) {
1038 goto fail;
1039 }
1040 result = PyList_Append(lst, ostr);
1041 Py_DECREF(ostr);
1042 if (result < 0) {
1043 goto fail;
1044 }
1045 }
1046 AUTHORITY_INFO_ACCESS_free(info);
1047
1048 /* convert to tuple or None */
1049 if (PyList_Size(lst) == 0) {
1050 Py_DECREF(lst);
1051 return Py_None;
1052 } else {
1053 PyObject *tup;
1054 tup = PyList_AsTuple(lst);
1055 Py_DECREF(lst);
1056 return tup;
1057 }
1058
1059 fail:
1060 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001061 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001062 return NULL;
1063}
1064
1065static PyObject *
1066_get_crl_dp(X509 *certificate) {
1067 STACK_OF(DIST_POINT) *dps;
1068 int i, j, result;
1069 PyObject *lst;
1070
Christian Heimes949ec142013-11-21 16:26:51 +01001071#if OPENSSL_VERSION_NUMBER < 0x10001000L
1072 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1073 NULL, NULL);
1074#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001075 /* Calls x509v3_cache_extensions and sets up crldp */
1076 X509_check_ca(certificate);
1077 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001078#endif
1079
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001080 if (dps == NULL) {
1081 return Py_None;
1082 }
1083
1084 if ((lst = PyList_New(0)) == NULL) {
1085 return NULL;
1086 }
1087
1088 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1089 DIST_POINT *dp;
1090 STACK_OF(GENERAL_NAME) *gns;
1091
1092 dp = sk_DIST_POINT_value(dps, i);
1093 gns = dp->distpoint->name.fullname;
1094
1095 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1096 GENERAL_NAME *gn;
1097 ASN1_IA5STRING *uri;
1098 PyObject *ouri;
1099
1100 gn = sk_GENERAL_NAME_value(gns, j);
1101 if (gn->type != GEN_URI) {
1102 continue;
1103 }
1104 uri = gn->d.uniformResourceIdentifier;
1105 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1106 uri->length);
1107 if (ouri == NULL) {
1108 Py_DECREF(lst);
1109 return NULL;
1110 }
1111 result = PyList_Append(lst, ouri);
1112 Py_DECREF(ouri);
1113 if (result < 0) {
1114 Py_DECREF(lst);
1115 return NULL;
1116 }
1117 }
1118 }
1119 /* convert to tuple or None */
1120 if (PyList_Size(lst) == 0) {
1121 Py_DECREF(lst);
1122 return Py_None;
1123 } else {
1124 PyObject *tup;
1125 tup = PyList_AsTuple(lst);
1126 Py_DECREF(lst);
1127 return tup;
1128 }
1129}
1130
1131static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001132_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 PyObject *retval = NULL;
1135 BIO *biobuf = NULL;
1136 PyObject *peer;
1137 PyObject *peer_alt_names = NULL;
1138 PyObject *issuer;
1139 PyObject *version;
1140 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001141 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 ASN1_INTEGER *serialNumber;
1143 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001144 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 ASN1_TIME *notBefore, *notAfter;
1146 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 retval = PyDict_New();
1149 if (retval == NULL)
1150 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001151
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 peer = _create_tuple_for_X509_NAME(
1153 X509_get_subject_name(certificate));
1154 if (peer == NULL)
1155 goto fail0;
1156 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1157 Py_DECREF(peer);
1158 goto fail0;
1159 }
1160 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001161
Antoine Pitroufb046912010-11-09 20:21:19 +00001162 issuer = _create_tuple_for_X509_NAME(
1163 X509_get_issuer_name(certificate));
1164 if (issuer == NULL)
1165 goto fail0;
1166 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001168 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001170 Py_DECREF(issuer);
1171
1172 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001173 if (version == NULL)
1174 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001175 if (PyDict_SetItemString(retval, "version", version) < 0) {
1176 Py_DECREF(version);
1177 goto fail0;
1178 }
1179 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 /* get a memory buffer */
1182 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001183
Antoine Pitroufb046912010-11-09 20:21:19 +00001184 (void) BIO_reset(biobuf);
1185 serialNumber = X509_get_serialNumber(certificate);
1186 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1187 i2a_ASN1_INTEGER(biobuf, serialNumber);
1188 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1189 if (len < 0) {
1190 _setSSLError(NULL, 0, __FILE__, __LINE__);
1191 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001193 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1194 if (sn_obj == NULL)
1195 goto fail1;
1196 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1197 Py_DECREF(sn_obj);
1198 goto fail1;
1199 }
1200 Py_DECREF(sn_obj);
1201
1202 (void) BIO_reset(biobuf);
1203 notBefore = X509_get_notBefore(certificate);
1204 ASN1_TIME_print(biobuf, notBefore);
1205 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1206 if (len < 0) {
1207 _setSSLError(NULL, 0, __FILE__, __LINE__);
1208 goto fail1;
1209 }
1210 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1211 if (pnotBefore == NULL)
1212 goto fail1;
1213 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1214 Py_DECREF(pnotBefore);
1215 goto fail1;
1216 }
1217 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 (void) BIO_reset(biobuf);
1220 notAfter = X509_get_notAfter(certificate);
1221 ASN1_TIME_print(biobuf, notAfter);
1222 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1223 if (len < 0) {
1224 _setSSLError(NULL, 0, __FILE__, __LINE__);
1225 goto fail1;
1226 }
1227 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1228 if (pnotAfter == NULL)
1229 goto fail1;
1230 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1231 Py_DECREF(pnotAfter);
1232 goto fail1;
1233 }
1234 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 peer_alt_names = _get_peer_alt_names(certificate);
1239 if (peer_alt_names == NULL)
1240 goto fail1;
1241 else if (peer_alt_names != Py_None) {
1242 if (PyDict_SetItemString(retval, "subjectAltName",
1243 peer_alt_names) < 0) {
1244 Py_DECREF(peer_alt_names);
1245 goto fail1;
1246 }
1247 Py_DECREF(peer_alt_names);
1248 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001249
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001250 /* Authority Information Access: OCSP URIs */
1251 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1252 if (obj == NULL) {
1253 goto fail1;
1254 } else if (obj != Py_None) {
1255 result = PyDict_SetItemString(retval, "OCSP", obj);
1256 Py_DECREF(obj);
1257 if (result < 0) {
1258 goto fail1;
1259 }
1260 }
1261
1262 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1263 if (obj == NULL) {
1264 goto fail1;
1265 } else if (obj != Py_None) {
1266 result = PyDict_SetItemString(retval, "caIssuers", obj);
1267 Py_DECREF(obj);
1268 if (result < 0) {
1269 goto fail1;
1270 }
1271 }
1272
1273 /* CDP (CRL distribution points) */
1274 obj = _get_crl_dp(certificate);
1275 if (obj == NULL) {
1276 goto fail1;
1277 } else if (obj != Py_None) {
1278 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1279 Py_DECREF(obj);
1280 if (result < 0) {
1281 goto fail1;
1282 }
1283 }
1284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 BIO_free(biobuf);
1286 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001287
1288 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 if (biobuf != NULL)
1290 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001291 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 Py_XDECREF(retval);
1293 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001294}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001295
Christian Heimes9a5395a2013-06-17 15:44:12 +02001296static PyObject *
1297_certificate_to_der(X509 *certificate)
1298{
1299 unsigned char *bytes_buf = NULL;
1300 int len;
1301 PyObject *retval;
1302
1303 bytes_buf = NULL;
1304 len = i2d_X509(certificate, &bytes_buf);
1305 if (len < 0) {
1306 _setSSLError(NULL, 0, __FILE__, __LINE__);
1307 return NULL;
1308 }
1309 /* this is actually an immutable bytes sequence */
1310 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1311 OPENSSL_free(bytes_buf);
1312 return retval;
1313}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
1315static PyObject *
1316PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001319 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 X509 *x=NULL;
1321 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Antoine Pitroufb046912010-11-09 20:21:19 +00001323 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1324 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1328 PyErr_SetString(PySSLErrorObject,
1329 "Can't malloc memory to read file");
1330 goto fail0;
1331 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Victor Stinner3800e1e2010-05-16 21:23:48 +00001333 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 PyErr_SetString(PySSLErrorObject,
1335 "Can't open file");
1336 goto fail0;
1337 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1340 if (x == NULL) {
1341 PyErr_SetString(PySSLErrorObject,
1342 "Error decoding PEM-encoded file");
1343 goto fail0;
1344 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345
Antoine Pitroufb046912010-11-09 20:21:19 +00001346 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001347 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348
1349 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001350 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 if (cert != NULL) BIO_free(cert);
1352 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353}
1354
1355
1356static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001357PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001360 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361
Antoine Pitrou721738f2012-08-15 23:20:39 +02001362 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitrou20b85552013-09-29 19:50:53 +02001365 if (!self->handshake_done) {
1366 PyErr_SetString(PyExc_ValueError,
1367 "handshake not done yet");
1368 return NULL;
1369 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 if (!self->peer_cert)
1371 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372
Antoine Pitrou721738f2012-08-15 23:20:39 +02001373 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001375 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001377 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 if ((verification & SSL_VERIFY_PEER) == 0)
1379 return PyDict_New();
1380 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001381 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383}
1384
1385PyDoc_STRVAR(PySSL_peercert_doc,
1386"peer_certificate([der=False]) -> certificate\n\
1387\n\
1388Returns the certificate for the peer. If no certificate was provided,\n\
1389returns None. If a certificate was provided, but not validated, returns\n\
1390an empty dictionary. Otherwise returns a dict containing information\n\
1391about the peer certificate.\n\
1392\n\
1393If the optional argument is True, returns a DER-encoded copy of the\n\
1394peer certificate, or None if no certificate was provided. This will\n\
1395return the certificate even if it wasn't validated.");
1396
Antoine Pitrou152efa22010-05-16 18:19:27 +00001397static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001400 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 char *cipher_name;
1402 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001405 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 current = SSL_get_current_cipher(self->ssl);
1407 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001408 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 retval = PyTuple_New(3);
1411 if (retval == NULL)
1412 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 cipher_name = (char *) SSL_CIPHER_get_name(current);
1415 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001416 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 PyTuple_SET_ITEM(retval, 0, Py_None);
1418 } else {
1419 v = PyUnicode_FromString(cipher_name);
1420 if (v == NULL)
1421 goto fail0;
1422 PyTuple_SET_ITEM(retval, 0, v);
1423 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001424 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001426 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 PyTuple_SET_ITEM(retval, 1, Py_None);
1428 } else {
1429 v = PyUnicode_FromString(cipher_protocol);
1430 if (v == NULL)
1431 goto fail0;
1432 PyTuple_SET_ITEM(retval, 1, v);
1433 }
1434 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1435 if (v == NULL)
1436 goto fail0;
1437 PyTuple_SET_ITEM(retval, 2, v);
1438 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001439
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 Py_DECREF(retval);
1442 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443}
1444
Antoine Pitrou47e40422014-09-04 21:00:10 +02001445static PyObject *PySSL_version(PySSLSocket *self)
1446{
1447 const char *version;
1448
1449 if (self->ssl == NULL)
1450 Py_RETURN_NONE;
1451 version = SSL_get_version(self->ssl);
1452 if (!strcmp(version, "unknown"))
1453 Py_RETURN_NONE;
1454 return PyUnicode_FromString(version);
1455}
1456
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001457#ifdef OPENSSL_NPN_NEGOTIATED
1458static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1459 const unsigned char *out;
1460 unsigned int outlen;
1461
Victor Stinner4569cd52013-06-23 14:58:43 +02001462 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001463 &out, &outlen);
1464
1465 if (out == NULL)
1466 Py_RETURN_NONE;
1467 return PyUnicode_FromStringAndSize((char *) out, outlen);
1468}
1469#endif
1470
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001471static PyObject *PySSL_compression(PySSLSocket *self) {
1472#ifdef OPENSSL_NO_COMP
1473 Py_RETURN_NONE;
1474#else
1475 const COMP_METHOD *comp_method;
1476 const char *short_name;
1477
1478 if (self->ssl == NULL)
1479 Py_RETURN_NONE;
1480 comp_method = SSL_get_current_compression(self->ssl);
1481 if (comp_method == NULL || comp_method->type == NID_undef)
1482 Py_RETURN_NONE;
1483 short_name = OBJ_nid2sn(comp_method->type);
1484 if (short_name == NULL)
1485 Py_RETURN_NONE;
1486 return PyUnicode_DecodeFSDefault(short_name);
1487#endif
1488}
1489
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001490static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1491 Py_INCREF(self->ctx);
1492 return self->ctx;
1493}
1494
1495static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1496 void *closure) {
1497
1498 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001499#if !HAVE_SNI
1500 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1501 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001502 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001503#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001504 Py_INCREF(value);
1505 Py_DECREF(self->ctx);
1506 self->ctx = (PySSLContext *) value;
1507 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001508#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001509 } else {
1510 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1511 return -1;
1512 }
1513
1514 return 0;
1515}
1516
1517PyDoc_STRVAR(PySSL_set_context_doc,
1518"_setter_context(ctx)\n\
1519\
1520This changes the context associated with the SSLSocket. This is typically\n\
1521used from within a callback function set by the set_servername_callback\n\
1522on the SSLContext to change the certificate information associated with the\n\
1523SSLSocket before the cryptographic exchange handshake messages\n");
1524
1525
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001526static PyObject *
1527PySSL_get_server_side(PySSLSocket *self, void *c)
1528{
1529 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1530}
1531
1532PyDoc_STRVAR(PySSL_get_server_side_doc,
1533"Whether this is a server-side socket.");
1534
1535static PyObject *
1536PySSL_get_server_hostname(PySSLSocket *self, void *c)
1537{
1538 if (self->server_hostname == NULL)
1539 Py_RETURN_NONE;
1540 Py_INCREF(self->server_hostname);
1541 return self->server_hostname;
1542}
1543
1544PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1545"The currently set server hostname (for SNI).");
1546
1547static PyObject *
1548PySSL_get_owner(PySSLSocket *self, void *c)
1549{
1550 PyObject *owner;
1551
1552 if (self->owner == NULL)
1553 Py_RETURN_NONE;
1554
1555 owner = PyWeakref_GetObject(self->owner);
1556 Py_INCREF(owner);
1557 return owner;
1558}
1559
1560static int
1561PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1562{
1563 Py_XDECREF(self->owner);
1564 self->owner = PyWeakref_NewRef(value, NULL);
1565 if (self->owner == NULL)
1566 return -1;
1567 return 0;
1568}
1569
1570PyDoc_STRVAR(PySSL_get_owner_doc,
1571"The Python-level owner of this object.\
1572Passed as \"self\" in servername callback.");
1573
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001574
Antoine Pitrou152efa22010-05-16 18:19:27 +00001575static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001576{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 if (self->peer_cert) /* Possible not to have one? */
1578 X509_free (self->peer_cert);
1579 if (self->ssl)
1580 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001582 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001583 Py_XDECREF(self->server_hostname);
1584 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001586}
1587
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001588/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001589 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001590 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001591 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001592
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001593static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001594check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001595{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001596 fd_set fds;
1597 struct timeval tv;
1598 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001601 if ((s == NULL) || (s->sock_timeout == 0.0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 return SOCKET_IS_NONBLOCKING;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001603 else if (s->sock_timeout < 0.0)
1604 return SOCKET_IS_BLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 /* Guard against closed socket */
1607 if (s->sock_fd < 0)
1608 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 /* Prefer poll, if available, since you can poll() any fd
1611 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001612#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 {
1614 struct pollfd pollfd;
1615 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 pollfd.fd = s->sock_fd;
1618 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 /* s->sock_timeout is in seconds, timeout in ms */
1621 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1622 PySSL_BEGIN_ALLOW_THREADS
1623 rc = poll(&pollfd, 1, timeout);
1624 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 goto normal_return;
1627 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001628#endif
1629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001631 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634 /* Construct the arguments to select */
1635 tv.tv_sec = (int)s->sock_timeout;
1636 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1637 FD_ZERO(&fds);
1638 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 /* See if the socket is ready */
1641 PySSL_BEGIN_ALLOW_THREADS
1642 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001643 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1644 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001646 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1647 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001649
Bill Janssen6e027db2007-11-15 22:23:56 +00001650#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001651normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001652#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001653 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1654 (when we are able to write or when there's something to read) */
1655 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001656}
1657
Antoine Pitrou152efa22010-05-16 18:19:27 +00001658static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001659{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001660 Py_buffer buf;
1661 int len;
1662 int sockstate;
1663 int err;
1664 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001665 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001666
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001667 if (sock != NULL) {
1668 if (((PyObject*)sock) == Py_None) {
1669 _setSSLError("Underlying socket connection gone",
1670 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1671 return NULL;
1672 }
1673 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 }
1675
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001676 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001677 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001679 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680
Victor Stinner6efa9652013-06-25 00:42:31 +02001681 if (buf.len > INT_MAX) {
1682 PyErr_Format(PyExc_OverflowError,
1683 "string longer than %d bytes", INT_MAX);
1684 goto error;
1685 }
1686
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001687 if (sock != NULL) {
1688 /* just in case the blocking state of the socket has been changed */
1689 nonblocking = (sock->sock_timeout >= 0.0);
1690 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1691 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1692 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693
1694 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1695 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001696 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 "The write operation timed out");
1698 goto error;
1699 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1700 PyErr_SetString(PySSLErrorObject,
1701 "Underlying socket has been closed.");
1702 goto error;
1703 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1704 PyErr_SetString(PySSLErrorObject,
1705 "Underlying socket too large for select().");
1706 goto error;
1707 }
1708 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001710 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 err = SSL_get_error(self->ssl, len);
1712 PySSL_END_ALLOW_THREADS
1713 if (PyErr_CheckSignals()) {
1714 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001715 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001717 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001718 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001719 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 } else {
1721 sockstate = SOCKET_OPERATION_OK;
1722 }
1723 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001724 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 "The write operation timed out");
1726 goto error;
1727 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1728 PyErr_SetString(PySSLErrorObject,
1729 "Underlying socket has been closed.");
1730 goto error;
1731 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1732 break;
1733 }
1734 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001735
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001736 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PyBuffer_Release(&buf);
1738 if (len > 0)
1739 return PyLong_FromLong(len);
1740 else
1741 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001742
1743error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001744 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 PyBuffer_Release(&buf);
1746 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747}
1748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750"write(s) -> len\n\
1751\n\
1752Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754
Antoine Pitrou152efa22010-05-16 18:19:27 +00001755static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001756{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 PySSL_BEGIN_ALLOW_THREADS
1760 count = SSL_pending(self->ssl);
1761 PySSL_END_ALLOW_THREADS
1762 if (count < 0)
1763 return PySSL_SetError(self, count, __FILE__, __LINE__);
1764 else
1765 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001766}
1767
1768PyDoc_STRVAR(PySSL_SSLpending_doc,
1769"pending() -> count\n\
1770\n\
1771Returns the number of already decrypted bytes available for read,\n\
1772pending on the connection.\n");
1773
Antoine Pitrou152efa22010-05-16 18:19:27 +00001774static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001775{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 PyObject *dest = NULL;
1777 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001779 int len, count;
1780 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 int sockstate;
1782 int err;
1783 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001784 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001785
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001786 if (sock != NULL) {
1787 if (((PyObject*)sock) == Py_None) {
1788 _setSSLError("Underlying socket connection gone",
1789 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1790 return NULL;
1791 }
1792 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 }
1794
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001795 buf.obj = NULL;
1796 buf.buf = NULL;
1797 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001798 goto error;
1799
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001800 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1801 dest = PyBytes_FromStringAndSize(NULL, len);
1802 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001803 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001804 mem = PyBytes_AS_STRING(dest);
1805 }
1806 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001808 mem = buf.buf;
1809 if (len <= 0 || len > buf.len) {
1810 len = (int) buf.len;
1811 if (buf.len != len) {
1812 PyErr_SetString(PyExc_OverflowError,
1813 "maximum length can't fit in a C 'int'");
1814 goto error;
1815 }
1816 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 }
1818
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001819 if (sock != NULL) {
1820 /* just in case the blocking state of the socket has been changed */
1821 nonblocking = (sock->sock_timeout >= 0.0);
1822 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1823 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1824 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825
1826 /* first check if there are bytes ready to be read */
1827 PySSL_BEGIN_ALLOW_THREADS
1828 count = SSL_pending(self->ssl);
1829 PySSL_END_ALLOW_THREADS
1830
1831 if (!count) {
1832 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1833 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001834 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 "The read operation timed out");
1836 goto error;
1837 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1838 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001839 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 goto error;
1841 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1842 count = 0;
1843 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001844 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 }
1846 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 PySSL_BEGIN_ALLOW_THREADS
1848 count = SSL_read(self->ssl, mem, len);
1849 err = SSL_get_error(self->ssl, count);
1850 PySSL_END_ALLOW_THREADS
1851 if (PyErr_CheckSignals())
1852 goto error;
1853 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001854 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001856 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1858 (SSL_get_shutdown(self->ssl) ==
1859 SSL_RECEIVED_SHUTDOWN))
1860 {
1861 count = 0;
1862 goto done;
1863 } else {
1864 sockstate = SOCKET_OPERATION_OK;
1865 }
1866 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001867 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 "The read operation timed out");
1869 goto error;
1870 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1871 break;
1872 }
1873 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1874 if (count <= 0) {
1875 PySSL_SetError(self, count, __FILE__, __LINE__);
1876 goto error;
1877 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001878
1879done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001880 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001882 _PyBytes_Resize(&dest, count);
1883 return dest;
1884 }
1885 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 PyBuffer_Release(&buf);
1887 return PyLong_FromLong(count);
1888 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001889
1890error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001891 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001892 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001893 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001894 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001897}
1898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001899PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001900"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001901\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001902Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001903
Antoine Pitrou152efa22010-05-16 18:19:27 +00001904static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001905{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 int err, ssl_err, sockstate, nonblocking;
1907 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001908 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001909
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001910 if (sock != NULL) {
1911 /* Guard against closed socket */
1912 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1913 _setSSLError("Underlying socket connection gone",
1914 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1915 return NULL;
1916 }
1917 Py_INCREF(sock);
1918
1919 /* Just in case the blocking state of the socket has been changed */
1920 nonblocking = (sock->sock_timeout >= 0.0);
1921 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1922 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924
1925 while (1) {
1926 PySSL_BEGIN_ALLOW_THREADS
1927 /* Disable read-ahead so that unwrap can work correctly.
1928 * Otherwise OpenSSL might read in too much data,
1929 * eating clear text data that happens to be
1930 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001931 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 * function is used and the shutdown_seen_zero != 0
1933 * condition is met.
1934 */
1935 if (self->shutdown_seen_zero)
1936 SSL_set_read_ahead(self->ssl, 0);
1937 err = SSL_shutdown(self->ssl);
1938 PySSL_END_ALLOW_THREADS
1939 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1940 if (err > 0)
1941 break;
1942 if (err == 0) {
1943 /* Don't loop endlessly; instead preserve legacy
1944 behaviour of trying SSL_shutdown() only twice.
1945 This looks necessary for OpenSSL < 0.9.8m */
1946 if (++zeros > 1)
1947 break;
1948 /* Shutdown was sent, now try receiving */
1949 self->shutdown_seen_zero = 1;
1950 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001951 }
1952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 /* Possibly retry shutdown until timeout or failure */
1954 ssl_err = SSL_get_error(self->ssl, err);
1955 if (ssl_err == SSL_ERROR_WANT_READ)
1956 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1957 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1958 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1959 else
1960 break;
1961 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1962 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001963 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 "The read operation timed out");
1965 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001966 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001968 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 }
1970 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1971 PyErr_SetString(PySSLErrorObject,
1972 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001973 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 }
1975 else if (sockstate != SOCKET_OPERATION_OK)
1976 /* Retain the SSL error code */
1977 break;
1978 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001979
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001980 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001981 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001984 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001985 /* It's already INCREF'ed */
1986 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001987 else
1988 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001989
1990error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001991 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001992 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001993}
1994
1995PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1996"shutdown(s) -> socket\n\
1997\n\
1998Does the SSL shutdown handshake with the remote end, and returns\n\
1999the underlying socket object.");
2000
Antoine Pitroud6494802011-07-21 01:11:30 +02002001#if HAVE_OPENSSL_FINISHED
2002static PyObject *
2003PySSL_tls_unique_cb(PySSLSocket *self)
2004{
2005 PyObject *retval = NULL;
2006 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002007 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002008
2009 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2010 /* if session is resumed XOR we are the client */
2011 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2012 }
2013 else {
2014 /* if a new session XOR we are the server */
2015 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2016 }
2017
2018 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002019 if (len == 0)
2020 Py_RETURN_NONE;
2021
2022 retval = PyBytes_FromStringAndSize(buf, len);
2023
2024 return retval;
2025}
2026
2027PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2028"tls_unique_cb() -> bytes\n\
2029\n\
2030Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2031\n\
2032If the TLS handshake is not yet complete, None is returned");
2033
2034#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00002035
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002036static PyGetSetDef ssl_getsetlist[] = {
2037 {"context", (getter) PySSL_get_context,
2038 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002039 {"server_side", (getter) PySSL_get_server_side, NULL,
2040 PySSL_get_server_side_doc},
2041 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2042 PySSL_get_server_hostname_doc},
2043 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2044 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002045 {NULL}, /* sentinel */
2046};
2047
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002048static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2050 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2051 PySSL_SSLwrite_doc},
2052 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2053 PySSL_SSLread_doc},
2054 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2055 PySSL_SSLpending_doc},
2056 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2057 PySSL_peercert_doc},
2058 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002059 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002060#ifdef OPENSSL_NPN_NEGOTIATED
2061 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2062#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002063 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2065 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002066#if HAVE_OPENSSL_FINISHED
2067 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2068 PySSL_tls_unique_cb_doc},
2069#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002070 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002071};
2072
Antoine Pitrou152efa22010-05-16 18:19:27 +00002073static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002074 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002075 "_ssl._SSLSocket", /*tp_name*/
2076 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 0, /*tp_itemsize*/
2078 /* methods */
2079 (destructor)PySSL_dealloc, /*tp_dealloc*/
2080 0, /*tp_print*/
2081 0, /*tp_getattr*/
2082 0, /*tp_setattr*/
2083 0, /*tp_reserved*/
2084 0, /*tp_repr*/
2085 0, /*tp_as_number*/
2086 0, /*tp_as_sequence*/
2087 0, /*tp_as_mapping*/
2088 0, /*tp_hash*/
2089 0, /*tp_call*/
2090 0, /*tp_str*/
2091 0, /*tp_getattro*/
2092 0, /*tp_setattro*/
2093 0, /*tp_as_buffer*/
2094 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2095 0, /*tp_doc*/
2096 0, /*tp_traverse*/
2097 0, /*tp_clear*/
2098 0, /*tp_richcompare*/
2099 0, /*tp_weaklistoffset*/
2100 0, /*tp_iter*/
2101 0, /*tp_iternext*/
2102 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002103 0, /*tp_members*/
2104 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002105};
2106
Antoine Pitrou152efa22010-05-16 18:19:27 +00002107
2108/*
2109 * _SSLContext objects
2110 */
2111
2112static PyObject *
2113context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2114{
2115 char *kwlist[] = {"protocol", NULL};
2116 PySSLContext *self;
2117 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002118 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002119 SSL_CTX *ctx = NULL;
2120
2121 if (!PyArg_ParseTupleAndKeywords(
2122 args, kwds, "i:_SSLContext", kwlist,
2123 &proto_version))
2124 return NULL;
2125
2126 PySSL_BEGIN_ALLOW_THREADS
2127 if (proto_version == PY_SSL_VERSION_TLS1)
2128 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002129#if HAVE_TLSv1_2
2130 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2131 ctx = SSL_CTX_new(TLSv1_1_method());
2132 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2133 ctx = SSL_CTX_new(TLSv1_2_method());
2134#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002135 else if (proto_version == PY_SSL_VERSION_SSL3)
2136 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002137#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138 else if (proto_version == PY_SSL_VERSION_SSL2)
2139 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002140#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002141 else if (proto_version == PY_SSL_VERSION_SSL23)
2142 ctx = SSL_CTX_new(SSLv23_method());
2143 else
2144 proto_version = -1;
2145 PySSL_END_ALLOW_THREADS
2146
2147 if (proto_version == -1) {
2148 PyErr_SetString(PyExc_ValueError,
2149 "invalid protocol version");
2150 return NULL;
2151 }
2152 if (ctx == NULL) {
2153 PyErr_SetString(PySSLErrorObject,
2154 "failed to allocate SSL context");
2155 return NULL;
2156 }
2157
2158 assert(type != NULL && type->tp_alloc != NULL);
2159 self = (PySSLContext *) type->tp_alloc(type, 0);
2160 if (self == NULL) {
2161 SSL_CTX_free(ctx);
2162 return NULL;
2163 }
2164 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002165#ifdef OPENSSL_NPN_NEGOTIATED
2166 self->npn_protocols = NULL;
2167#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002168#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002169 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002170#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002171 /* Don't check host name by default */
2172 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173 /* Defaults */
2174 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002175 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2176 if (proto_version != PY_SSL_VERSION_SSL2)
2177 options |= SSL_OP_NO_SSLv2;
2178 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002179
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002180#ifndef OPENSSL_NO_ECDH
2181 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2182 prime256v1 by default. This is Apache mod_ssl's initialization
2183 policy, so we should be safe. */
2184#if defined(SSL_CTX_set_ecdh_auto)
2185 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2186#else
2187 {
2188 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2189 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2190 EC_KEY_free(key);
2191 }
2192#endif
2193#endif
2194
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002195#define SID_CTX "Python"
2196 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2197 sizeof(SID_CTX));
2198#undef SID_CTX
2199
Antoine Pitrou152efa22010-05-16 18:19:27 +00002200 return (PyObject *)self;
2201}
2202
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203static int
2204context_traverse(PySSLContext *self, visitproc visit, void *arg)
2205{
2206#ifndef OPENSSL_NO_TLSEXT
2207 Py_VISIT(self->set_hostname);
2208#endif
2209 return 0;
2210}
2211
2212static int
2213context_clear(PySSLContext *self)
2214{
2215#ifndef OPENSSL_NO_TLSEXT
2216 Py_CLEAR(self->set_hostname);
2217#endif
2218 return 0;
2219}
2220
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221static void
2222context_dealloc(PySSLContext *self)
2223{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002224 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002225 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002226#ifdef OPENSSL_NPN_NEGOTIATED
2227 PyMem_Free(self->npn_protocols);
2228#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002229 Py_TYPE(self)->tp_free(self);
2230}
2231
2232static PyObject *
2233set_ciphers(PySSLContext *self, PyObject *args)
2234{
2235 int ret;
2236 const char *cipherlist;
2237
2238 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2239 return NULL;
2240 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2241 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002242 /* Clearing the error queue is necessary on some OpenSSL versions,
2243 otherwise the error will be reported again when another SSL call
2244 is done. */
2245 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002246 PyErr_SetString(PySSLErrorObject,
2247 "No cipher can be selected.");
2248 return NULL;
2249 }
2250 Py_RETURN_NONE;
2251}
2252
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002253#ifdef OPENSSL_NPN_NEGOTIATED
2254/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2255static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002256_advertiseNPN_cb(SSL *s,
2257 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002258 void *args)
2259{
2260 PySSLContext *ssl_ctx = (PySSLContext *) args;
2261
2262 if (ssl_ctx->npn_protocols == NULL) {
2263 *data = (unsigned char *) "";
2264 *len = 0;
2265 } else {
2266 *data = (unsigned char *) ssl_ctx->npn_protocols;
2267 *len = ssl_ctx->npn_protocols_len;
2268 }
2269
2270 return SSL_TLSEXT_ERR_OK;
2271}
2272/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2273static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002274_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002275 unsigned char **out, unsigned char *outlen,
2276 const unsigned char *server, unsigned int server_len,
2277 void *args)
2278{
2279 PySSLContext *ssl_ctx = (PySSLContext *) args;
2280
2281 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2282 int client_len;
2283
2284 if (client == NULL) {
2285 client = (unsigned char *) "";
2286 client_len = 0;
2287 } else {
2288 client_len = ssl_ctx->npn_protocols_len;
2289 }
2290
2291 SSL_select_next_proto(out, outlen,
2292 server, server_len,
2293 client, client_len);
2294
2295 return SSL_TLSEXT_ERR_OK;
2296}
2297#endif
2298
2299static PyObject *
2300_set_npn_protocols(PySSLContext *self, PyObject *args)
2301{
2302#ifdef OPENSSL_NPN_NEGOTIATED
2303 Py_buffer protos;
2304
2305 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2306 return NULL;
2307
Christian Heimes5cb31c92012-09-20 12:42:54 +02002308 if (self->npn_protocols != NULL) {
2309 PyMem_Free(self->npn_protocols);
2310 }
2311
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002312 self->npn_protocols = PyMem_Malloc(protos.len);
2313 if (self->npn_protocols == NULL) {
2314 PyBuffer_Release(&protos);
2315 return PyErr_NoMemory();
2316 }
2317 memcpy(self->npn_protocols, protos.buf, protos.len);
2318 self->npn_protocols_len = (int) protos.len;
2319
2320 /* set both server and client callbacks, because the context can
2321 * be used to create both types of sockets */
2322 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2323 _advertiseNPN_cb,
2324 self);
2325 SSL_CTX_set_next_proto_select_cb(self->ctx,
2326 _selectNPN_cb,
2327 self);
2328
2329 PyBuffer_Release(&protos);
2330 Py_RETURN_NONE;
2331#else
2332 PyErr_SetString(PyExc_NotImplementedError,
2333 "The NPN extension requires OpenSSL 1.0.1 or later.");
2334 return NULL;
2335#endif
2336}
2337
Antoine Pitrou152efa22010-05-16 18:19:27 +00002338static PyObject *
2339get_verify_mode(PySSLContext *self, void *c)
2340{
2341 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2342 case SSL_VERIFY_NONE:
2343 return PyLong_FromLong(PY_SSL_CERT_NONE);
2344 case SSL_VERIFY_PEER:
2345 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2346 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2347 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2348 }
2349 PyErr_SetString(PySSLErrorObject,
2350 "invalid return value from SSL_CTX_get_verify_mode");
2351 return NULL;
2352}
2353
2354static int
2355set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2356{
2357 int n, mode;
2358 if (!PyArg_Parse(arg, "i", &n))
2359 return -1;
2360 if (n == PY_SSL_CERT_NONE)
2361 mode = SSL_VERIFY_NONE;
2362 else if (n == PY_SSL_CERT_OPTIONAL)
2363 mode = SSL_VERIFY_PEER;
2364 else if (n == PY_SSL_CERT_REQUIRED)
2365 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2366 else {
2367 PyErr_SetString(PyExc_ValueError,
2368 "invalid value for verify_mode");
2369 return -1;
2370 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002371 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2372 PyErr_SetString(PyExc_ValueError,
2373 "Cannot set verify_mode to CERT_NONE when "
2374 "check_hostname is enabled.");
2375 return -1;
2376 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002377 SSL_CTX_set_verify(self->ctx, mode, NULL);
2378 return 0;
2379}
2380
Christian Heimes2427b502013-11-23 11:24:32 +01002381#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002382static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002383get_verify_flags(PySSLContext *self, void *c)
2384{
2385 X509_STORE *store;
2386 unsigned long flags;
2387
2388 store = SSL_CTX_get_cert_store(self->ctx);
2389 flags = X509_VERIFY_PARAM_get_flags(store->param);
2390 return PyLong_FromUnsignedLong(flags);
2391}
2392
2393static int
2394set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2395{
2396 X509_STORE *store;
2397 unsigned long new_flags, flags, set, clear;
2398
2399 if (!PyArg_Parse(arg, "k", &new_flags))
2400 return -1;
2401 store = SSL_CTX_get_cert_store(self->ctx);
2402 flags = X509_VERIFY_PARAM_get_flags(store->param);
2403 clear = flags & ~new_flags;
2404 set = ~flags & new_flags;
2405 if (clear) {
2406 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2407 _setSSLError(NULL, 0, __FILE__, __LINE__);
2408 return -1;
2409 }
2410 }
2411 if (set) {
2412 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2413 _setSSLError(NULL, 0, __FILE__, __LINE__);
2414 return -1;
2415 }
2416 }
2417 return 0;
2418}
Christian Heimes2427b502013-11-23 11:24:32 +01002419#endif
Christian Heimes22587792013-11-21 23:56:13 +01002420
2421static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002422get_options(PySSLContext *self, void *c)
2423{
2424 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2425}
2426
2427static int
2428set_options(PySSLContext *self, PyObject *arg, void *c)
2429{
2430 long new_opts, opts, set, clear;
2431 if (!PyArg_Parse(arg, "l", &new_opts))
2432 return -1;
2433 opts = SSL_CTX_get_options(self->ctx);
2434 clear = opts & ~new_opts;
2435 set = ~opts & new_opts;
2436 if (clear) {
2437#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2438 SSL_CTX_clear_options(self->ctx, clear);
2439#else
2440 PyErr_SetString(PyExc_ValueError,
2441 "can't clear options before OpenSSL 0.9.8m");
2442 return -1;
2443#endif
2444 }
2445 if (set)
2446 SSL_CTX_set_options(self->ctx, set);
2447 return 0;
2448}
2449
Christian Heimes1aa9a752013-12-02 02:41:19 +01002450static PyObject *
2451get_check_hostname(PySSLContext *self, void *c)
2452{
2453 return PyBool_FromLong(self->check_hostname);
2454}
2455
2456static int
2457set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2458{
2459 int check_hostname;
2460 if (!PyArg_Parse(arg, "p", &check_hostname))
2461 return -1;
2462 if (check_hostname &&
2463 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2464 PyErr_SetString(PyExc_ValueError,
2465 "check_hostname needs a SSL context with either "
2466 "CERT_OPTIONAL or CERT_REQUIRED");
2467 return -1;
2468 }
2469 self->check_hostname = check_hostname;
2470 return 0;
2471}
2472
2473
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002474typedef struct {
2475 PyThreadState *thread_state;
2476 PyObject *callable;
2477 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002478 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002479 int error;
2480} _PySSLPasswordInfo;
2481
2482static int
2483_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2484 const char *bad_type_error)
2485{
2486 /* Set the password and size fields of a _PySSLPasswordInfo struct
2487 from a unicode, bytes, or byte array object.
2488 The password field will be dynamically allocated and must be freed
2489 by the caller */
2490 PyObject *password_bytes = NULL;
2491 const char *data = NULL;
2492 Py_ssize_t size;
2493
2494 if (PyUnicode_Check(password)) {
2495 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2496 if (!password_bytes) {
2497 goto error;
2498 }
2499 data = PyBytes_AS_STRING(password_bytes);
2500 size = PyBytes_GET_SIZE(password_bytes);
2501 } else if (PyBytes_Check(password)) {
2502 data = PyBytes_AS_STRING(password);
2503 size = PyBytes_GET_SIZE(password);
2504 } else if (PyByteArray_Check(password)) {
2505 data = PyByteArray_AS_STRING(password);
2506 size = PyByteArray_GET_SIZE(password);
2507 } else {
2508 PyErr_SetString(PyExc_TypeError, bad_type_error);
2509 goto error;
2510 }
2511
Victor Stinner9ee02032013-06-23 15:08:23 +02002512 if (size > (Py_ssize_t)INT_MAX) {
2513 PyErr_Format(PyExc_ValueError,
2514 "password cannot be longer than %d bytes", INT_MAX);
2515 goto error;
2516 }
2517
Victor Stinner11ebff22013-07-07 17:07:52 +02002518 PyMem_Free(pw_info->password);
2519 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002520 if (!pw_info->password) {
2521 PyErr_SetString(PyExc_MemoryError,
2522 "unable to allocate password buffer");
2523 goto error;
2524 }
2525 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002526 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002527
2528 Py_XDECREF(password_bytes);
2529 return 1;
2530
2531error:
2532 Py_XDECREF(password_bytes);
2533 return 0;
2534}
2535
2536static int
2537_password_callback(char *buf, int size, int rwflag, void *userdata)
2538{
2539 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2540 PyObject *fn_ret = NULL;
2541
2542 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2543
2544 if (pw_info->callable) {
2545 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2546 if (!fn_ret) {
2547 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2548 core python API, so we could use it to add a frame here */
2549 goto error;
2550 }
2551
2552 if (!_pwinfo_set(pw_info, fn_ret,
2553 "password callback must return a string")) {
2554 goto error;
2555 }
2556 Py_CLEAR(fn_ret);
2557 }
2558
2559 if (pw_info->size > size) {
2560 PyErr_Format(PyExc_ValueError,
2561 "password cannot be longer than %d bytes", size);
2562 goto error;
2563 }
2564
2565 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2566 memcpy(buf, pw_info->password, pw_info->size);
2567 return pw_info->size;
2568
2569error:
2570 Py_XDECREF(fn_ret);
2571 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2572 pw_info->error = 1;
2573 return -1;
2574}
2575
Antoine Pitroub5218772010-05-21 09:56:06 +00002576static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002577load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2578{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002579 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2580 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002581 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002582 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2583 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2584 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002585 int r;
2586
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002587 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002588 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002589 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002590 "O|OO:load_cert_chain", kwlist,
2591 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002592 return NULL;
2593 if (keyfile == Py_None)
2594 keyfile = NULL;
2595 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2596 PyErr_SetString(PyExc_TypeError,
2597 "certfile should be a valid filesystem path");
2598 return NULL;
2599 }
2600 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2601 PyErr_SetString(PyExc_TypeError,
2602 "keyfile should be a valid filesystem path");
2603 goto error;
2604 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002605 if (password && password != Py_None) {
2606 if (PyCallable_Check(password)) {
2607 pw_info.callable = password;
2608 } else if (!_pwinfo_set(&pw_info, password,
2609 "password should be a string or callable")) {
2610 goto error;
2611 }
2612 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2613 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2614 }
2615 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002616 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2617 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002618 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002620 if (pw_info.error) {
2621 ERR_clear_error();
2622 /* the password callback has already set the error information */
2623 }
2624 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002625 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002626 PyErr_SetFromErrno(PyExc_IOError);
2627 }
2628 else {
2629 _setSSLError(NULL, 0, __FILE__, __LINE__);
2630 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002631 goto error;
2632 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002633 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002634 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002635 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2636 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002637 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2638 Py_CLEAR(keyfile_bytes);
2639 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002641 if (pw_info.error) {
2642 ERR_clear_error();
2643 /* the password callback has already set the error information */
2644 }
2645 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002646 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002647 PyErr_SetFromErrno(PyExc_IOError);
2648 }
2649 else {
2650 _setSSLError(NULL, 0, __FILE__, __LINE__);
2651 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002652 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002653 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002654 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002656 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657 if (r != 1) {
2658 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002659 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002660 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002661 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2662 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002663 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002664 Py_RETURN_NONE;
2665
2666error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002667 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2668 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002669 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002670 Py_XDECREF(keyfile_bytes);
2671 Py_XDECREF(certfile_bytes);
2672 return NULL;
2673}
2674
Christian Heimesefff7062013-11-21 03:35:02 +01002675/* internal helper function, returns -1 on error
2676 */
2677static int
2678_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2679 int filetype)
2680{
2681 BIO *biobuf = NULL;
2682 X509_STORE *store;
2683 int retval = 0, err, loaded = 0;
2684
2685 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2686
2687 if (len <= 0) {
2688 PyErr_SetString(PyExc_ValueError,
2689 "Empty certificate data");
2690 return -1;
2691 } else if (len > INT_MAX) {
2692 PyErr_SetString(PyExc_OverflowError,
2693 "Certificate data is too long.");
2694 return -1;
2695 }
2696
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002697 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002698 if (biobuf == NULL) {
2699 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2700 return -1;
2701 }
2702
2703 store = SSL_CTX_get_cert_store(self->ctx);
2704 assert(store != NULL);
2705
2706 while (1) {
2707 X509 *cert = NULL;
2708 int r;
2709
2710 if (filetype == SSL_FILETYPE_ASN1) {
2711 cert = d2i_X509_bio(biobuf, NULL);
2712 } else {
2713 cert = PEM_read_bio_X509(biobuf, NULL,
2714 self->ctx->default_passwd_callback,
2715 self->ctx->default_passwd_callback_userdata);
2716 }
2717 if (cert == NULL) {
2718 break;
2719 }
2720 r = X509_STORE_add_cert(store, cert);
2721 X509_free(cert);
2722 if (!r) {
2723 err = ERR_peek_last_error();
2724 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2725 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2726 /* cert already in hash table, not an error */
2727 ERR_clear_error();
2728 } else {
2729 break;
2730 }
2731 }
2732 loaded++;
2733 }
2734
2735 err = ERR_peek_last_error();
2736 if ((filetype == SSL_FILETYPE_ASN1) &&
2737 (loaded > 0) &&
2738 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2739 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2740 /* EOF ASN1 file, not an error */
2741 ERR_clear_error();
2742 retval = 0;
2743 } else if ((filetype == SSL_FILETYPE_PEM) &&
2744 (loaded > 0) &&
2745 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2746 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2747 /* EOF PEM file, not an error */
2748 ERR_clear_error();
2749 retval = 0;
2750 } else {
2751 _setSSLError(NULL, 0, __FILE__, __LINE__);
2752 retval = -1;
2753 }
2754
2755 BIO_free(biobuf);
2756 return retval;
2757}
2758
2759
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760static PyObject *
2761load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2762{
Christian Heimesefff7062013-11-21 03:35:02 +01002763 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2764 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2766 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002767 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002768
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002769 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002770 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002771 "|OOO:load_verify_locations", kwlist,
2772 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002773 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002774
Antoine Pitrou152efa22010-05-16 18:19:27 +00002775 if (cafile == Py_None)
2776 cafile = NULL;
2777 if (capath == Py_None)
2778 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002779 if (cadata == Py_None)
2780 cadata = NULL;
2781
2782 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002783 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002784 "cafile, capath and cadata cannot be all omitted");
2785 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002786 }
2787 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2788 PyErr_SetString(PyExc_TypeError,
2789 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002790 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002791 }
2792 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 PyErr_SetString(PyExc_TypeError,
2794 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002795 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002796 }
Christian Heimesefff7062013-11-21 03:35:02 +01002797
2798 /* validata cadata type and load cadata */
2799 if (cadata) {
2800 Py_buffer buf;
2801 PyObject *cadata_ascii = NULL;
2802
2803 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2804 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2805 PyBuffer_Release(&buf);
2806 PyErr_SetString(PyExc_TypeError,
2807 "cadata should be a contiguous buffer with "
2808 "a single dimension");
2809 goto error;
2810 }
2811 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2812 PyBuffer_Release(&buf);
2813 if (r == -1) {
2814 goto error;
2815 }
2816 } else {
2817 PyErr_Clear();
2818 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2819 if (cadata_ascii == NULL) {
2820 PyErr_SetString(PyExc_TypeError,
2821 "cadata should be a ASCII string or a "
2822 "bytes-like object");
2823 goto error;
2824 }
2825 r = _add_ca_certs(self,
2826 PyBytes_AS_STRING(cadata_ascii),
2827 PyBytes_GET_SIZE(cadata_ascii),
2828 SSL_FILETYPE_PEM);
2829 Py_DECREF(cadata_ascii);
2830 if (r == -1) {
2831 goto error;
2832 }
2833 }
2834 }
2835
2836 /* load cafile or capath */
2837 if (cafile || capath) {
2838 if (cafile)
2839 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2840 if (capath)
2841 capath_buf = PyBytes_AS_STRING(capath_bytes);
2842 PySSL_BEGIN_ALLOW_THREADS
2843 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2844 PySSL_END_ALLOW_THREADS
2845 if (r != 1) {
2846 ok = 0;
2847 if (errno != 0) {
2848 ERR_clear_error();
2849 PyErr_SetFromErrno(PyExc_IOError);
2850 }
2851 else {
2852 _setSSLError(NULL, 0, __FILE__, __LINE__);
2853 }
2854 goto error;
2855 }
2856 }
2857 goto end;
2858
2859 error:
2860 ok = 0;
2861 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002862 Py_XDECREF(cafile_bytes);
2863 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002864 if (ok) {
2865 Py_RETURN_NONE;
2866 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867 return NULL;
2868 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869}
2870
2871static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002872load_dh_params(PySSLContext *self, PyObject *filepath)
2873{
2874 FILE *f;
2875 DH *dh;
2876
Victor Stinnerdaf45552013-08-28 00:53:59 +02002877 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002878 if (f == NULL) {
2879 if (!PyErr_Occurred())
2880 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2881 return NULL;
2882 }
2883 errno = 0;
2884 PySSL_BEGIN_ALLOW_THREADS
2885 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002886 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002887 PySSL_END_ALLOW_THREADS
2888 if (dh == NULL) {
2889 if (errno != 0) {
2890 ERR_clear_error();
2891 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2892 }
2893 else {
2894 _setSSLError(NULL, 0, __FILE__, __LINE__);
2895 }
2896 return NULL;
2897 }
2898 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2899 _setSSLError(NULL, 0, __FILE__, __LINE__);
2900 DH_free(dh);
2901 Py_RETURN_NONE;
2902}
2903
2904static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2906{
Antoine Pitroud5323212010-10-22 18:19:07 +00002907 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002908 PySocketSockObject *sock;
2909 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002910 char *hostname = NULL;
2911 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002912
Antoine Pitroud5323212010-10-22 18:19:07 +00002913 /* server_hostname is either None (or absent), or to be encoded
2914 using the idna encoding. */
2915 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002917 &sock, &server_side,
2918 Py_TYPE(Py_None), &hostname_obj)) {
2919 PyErr_Clear();
2920 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2921 PySocketModule.Sock_Type,
2922 &sock, &server_side,
2923 "idna", &hostname))
2924 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002925 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002926
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002927 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2928 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002929 if (hostname != NULL)
2930 PyMem_Free(hostname);
2931 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002932}
2933
Antoine Pitroub0182c82010-10-12 20:09:02 +00002934static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002935context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
2936{
2937 char *kwlist[] = {"incoming", "outgoing", "server_side",
2938 "server_hostname", NULL};
2939 int server_side;
2940 char *hostname = NULL;
2941 PyObject *hostname_obj = Py_None, *res;
2942 PySSLMemoryBIO *incoming, *outgoing;
2943
2944 /* server_hostname is either None (or absent), or to be encoded
2945 using the idna encoding. */
2946 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
2947 &PySSLMemoryBIO_Type, &incoming,
2948 &PySSLMemoryBIO_Type, &outgoing,
2949 &server_side, &hostname_obj))
2950 return NULL;
2951 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002952 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
2953 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002954 }
2955
2956 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
2957 incoming, outgoing);
2958
2959 PyMem_Free(hostname);
2960 return res;
2961}
2962
2963static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00002964session_stats(PySSLContext *self, PyObject *unused)
2965{
2966 int r;
2967 PyObject *value, *stats = PyDict_New();
2968 if (!stats)
2969 return NULL;
2970
2971#define ADD_STATS(SSL_NAME, KEY_NAME) \
2972 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2973 if (value == NULL) \
2974 goto error; \
2975 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2976 Py_DECREF(value); \
2977 if (r < 0) \
2978 goto error;
2979
2980 ADD_STATS(number, "number");
2981 ADD_STATS(connect, "connect");
2982 ADD_STATS(connect_good, "connect_good");
2983 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2984 ADD_STATS(accept, "accept");
2985 ADD_STATS(accept_good, "accept_good");
2986 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2987 ADD_STATS(accept, "accept");
2988 ADD_STATS(hits, "hits");
2989 ADD_STATS(misses, "misses");
2990 ADD_STATS(timeouts, "timeouts");
2991 ADD_STATS(cache_full, "cache_full");
2992
2993#undef ADD_STATS
2994
2995 return stats;
2996
2997error:
2998 Py_DECREF(stats);
2999 return NULL;
3000}
3001
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003002static PyObject *
3003set_default_verify_paths(PySSLContext *self, PyObject *unused)
3004{
3005 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3006 _setSSLError(NULL, 0, __FILE__, __LINE__);
3007 return NULL;
3008 }
3009 Py_RETURN_NONE;
3010}
3011
Antoine Pitrou501da612011-12-21 09:27:41 +01003012#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003013static PyObject *
3014set_ecdh_curve(PySSLContext *self, PyObject *name)
3015{
3016 PyObject *name_bytes;
3017 int nid;
3018 EC_KEY *key;
3019
3020 if (!PyUnicode_FSConverter(name, &name_bytes))
3021 return NULL;
3022 assert(PyBytes_Check(name_bytes));
3023 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3024 Py_DECREF(name_bytes);
3025 if (nid == 0) {
3026 PyErr_Format(PyExc_ValueError,
3027 "unknown elliptic curve name %R", name);
3028 return NULL;
3029 }
3030 key = EC_KEY_new_by_curve_name(nid);
3031 if (key == NULL) {
3032 _setSSLError(NULL, 0, __FILE__, __LINE__);
3033 return NULL;
3034 }
3035 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3036 EC_KEY_free(key);
3037 Py_RETURN_NONE;
3038}
Antoine Pitrou501da612011-12-21 09:27:41 +01003039#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003040
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003041#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003042static int
3043_servername_callback(SSL *s, int *al, void *args)
3044{
3045 int ret;
3046 PySSLContext *ssl_ctx = (PySSLContext *) args;
3047 PySSLSocket *ssl;
3048 PyObject *servername_o;
3049 PyObject *servername_idna;
3050 PyObject *result;
3051 /* The high-level ssl.SSLSocket object */
3052 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003053 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003054#ifdef WITH_THREAD
3055 PyGILState_STATE gstate = PyGILState_Ensure();
3056#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003057
3058 if (ssl_ctx->set_hostname == NULL) {
3059 /* remove race condition in this the call back while if removing the
3060 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003061#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003062 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003063#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003064 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003065 }
3066
3067 ssl = SSL_get_app_data(s);
3068 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003069
3070 /* The servername callback expects a argument that represents the current
3071 * SSL connection and that has a .context attribute that can be changed to
3072 * identify the requested hostname. Since the official API is the Python
3073 * level API we want to pass the callback a Python level object rather than
3074 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3075 * SSLObject) that will be passed. Otherwise if there's a socket then that
3076 * will be passed. If both do not exist only then the C-level object is
3077 * passed. */
3078 if (ssl->owner)
3079 ssl_socket = PyWeakref_GetObject(ssl->owner);
3080 else if (ssl->Socket)
3081 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3082 else
3083 ssl_socket = (PyObject *) ssl;
3084
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003085 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003086 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003087 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003088
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003089 if (servername == NULL) {
3090 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3091 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003092 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003093 else {
3094 servername_o = PyBytes_FromString(servername);
3095 if (servername_o == NULL) {
3096 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3097 goto error;
3098 }
3099 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3100 if (servername_idna == NULL) {
3101 PyErr_WriteUnraisable(servername_o);
3102 Py_DECREF(servername_o);
3103 goto error;
3104 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003105 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003106 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3107 servername_idna, ssl_ctx, NULL);
3108 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003109 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003110 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003111
3112 if (result == NULL) {
3113 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3114 *al = SSL_AD_HANDSHAKE_FAILURE;
3115 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3116 }
3117 else {
3118 if (result != Py_None) {
3119 *al = (int) PyLong_AsLong(result);
3120 if (PyErr_Occurred()) {
3121 PyErr_WriteUnraisable(result);
3122 *al = SSL_AD_INTERNAL_ERROR;
3123 }
3124 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3125 }
3126 else {
3127 ret = SSL_TLSEXT_ERR_OK;
3128 }
3129 Py_DECREF(result);
3130 }
3131
Stefan Krah20d60802013-01-17 17:07:17 +01003132#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003133 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003134#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003135 return ret;
3136
3137error:
3138 Py_DECREF(ssl_socket);
3139 *al = SSL_AD_INTERNAL_ERROR;
3140 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003141#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003142 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003143#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144 return ret;
3145}
Antoine Pitroua5963382013-03-30 16:39:00 +01003146#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003147
3148PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3149"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003150\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003151This sets a callback that will be called when a server name is provided by\n\
3152the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003153\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003154If the argument is None then the callback is disabled. The method is called\n\
3155with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003156See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003157
3158static PyObject *
3159set_servername_callback(PySSLContext *self, PyObject *args)
3160{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003161#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003162 PyObject *cb;
3163
3164 if (!PyArg_ParseTuple(args, "O", &cb))
3165 return NULL;
3166
3167 Py_CLEAR(self->set_hostname);
3168 if (cb == Py_None) {
3169 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3170 }
3171 else {
3172 if (!PyCallable_Check(cb)) {
3173 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3174 PyErr_SetString(PyExc_TypeError,
3175 "not a callable object");
3176 return NULL;
3177 }
3178 Py_INCREF(cb);
3179 self->set_hostname = cb;
3180 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3181 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3182 }
3183 Py_RETURN_NONE;
3184#else
3185 PyErr_SetString(PyExc_NotImplementedError,
3186 "The TLS extension servername callback, "
3187 "SSL_CTX_set_tlsext_servername_callback, "
3188 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003189 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003190#endif
3191}
3192
Christian Heimes9a5395a2013-06-17 15:44:12 +02003193PyDoc_STRVAR(PySSL_get_stats_doc,
3194"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3195\n\
3196Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3197CA extension and certificate revocation lists inside the context's cert\n\
3198store.\n\
3199NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3200been used at least once.");
3201
3202static PyObject *
3203cert_store_stats(PySSLContext *self)
3204{
3205 X509_STORE *store;
3206 X509_OBJECT *obj;
3207 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3208
3209 store = SSL_CTX_get_cert_store(self->ctx);
3210 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3211 obj = sk_X509_OBJECT_value(store->objs, i);
3212 switch (obj->type) {
3213 case X509_LU_X509:
3214 x509++;
3215 if (X509_check_ca(obj->data.x509)) {
3216 ca++;
3217 }
3218 break;
3219 case X509_LU_CRL:
3220 crl++;
3221 break;
3222 case X509_LU_PKEY:
3223 pkey++;
3224 break;
3225 default:
3226 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3227 * As far as I can tell they are internal states and never
3228 * stored in a cert store */
3229 break;
3230 }
3231 }
3232 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3233 "x509_ca", ca);
3234}
3235
3236PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003237"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003238\n\
3239Returns a list of dicts with information of loaded CA certs. If the\n\
3240optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3241NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3242been used at least once.");
3243
3244static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003245get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003246{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003247 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003248 X509_STORE *store;
3249 PyObject *ci = NULL, *rlist = NULL;
3250 int i;
3251 int binary_mode = 0;
3252
Christian Heimesf22e8e52013-11-22 02:22:51 +01003253 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3254 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003255 return NULL;
3256 }
3257
3258 if ((rlist = PyList_New(0)) == NULL) {
3259 return NULL;
3260 }
3261
3262 store = SSL_CTX_get_cert_store(self->ctx);
3263 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3264 X509_OBJECT *obj;
3265 X509 *cert;
3266
3267 obj = sk_X509_OBJECT_value(store->objs, i);
3268 if (obj->type != X509_LU_X509) {
3269 /* not a x509 cert */
3270 continue;
3271 }
3272 /* CA for any purpose */
3273 cert = obj->data.x509;
3274 if (!X509_check_ca(cert)) {
3275 continue;
3276 }
3277 if (binary_mode) {
3278 ci = _certificate_to_der(cert);
3279 } else {
3280 ci = _decode_certificate(cert);
3281 }
3282 if (ci == NULL) {
3283 goto error;
3284 }
3285 if (PyList_Append(rlist, ci) == -1) {
3286 goto error;
3287 }
3288 Py_CLEAR(ci);
3289 }
3290 return rlist;
3291
3292 error:
3293 Py_XDECREF(ci);
3294 Py_XDECREF(rlist);
3295 return NULL;
3296}
3297
3298
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003300 {"check_hostname", (getter) get_check_hostname,
3301 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003302 {"options", (getter) get_options,
3303 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003304#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003305 {"verify_flags", (getter) get_verify_flags,
3306 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003307#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308 {"verify_mode", (getter) get_verify_mode,
3309 (setter) set_verify_mode, NULL},
3310 {NULL}, /* sentinel */
3311};
3312
3313static struct PyMethodDef context_methods[] = {
3314 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3315 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003316 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3317 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003318 {"set_ciphers", (PyCFunction) set_ciphers,
3319 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003320 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3321 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 {"load_cert_chain", (PyCFunction) load_cert_chain,
3323 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003324 {"load_dh_params", (PyCFunction) load_dh_params,
3325 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003326 {"load_verify_locations", (PyCFunction) load_verify_locations,
3327 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003328 {"session_stats", (PyCFunction) session_stats,
3329 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003330 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3331 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003332#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003333 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3334 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003335#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003336 {"set_servername_callback", (PyCFunction) set_servername_callback,
3337 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003338 {"cert_store_stats", (PyCFunction) cert_store_stats,
3339 METH_NOARGS, PySSL_get_stats_doc},
3340 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003341 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003342 {NULL, NULL} /* sentinel */
3343};
3344
3345static PyTypeObject PySSLContext_Type = {
3346 PyVarObject_HEAD_INIT(NULL, 0)
3347 "_ssl._SSLContext", /*tp_name*/
3348 sizeof(PySSLContext), /*tp_basicsize*/
3349 0, /*tp_itemsize*/
3350 (destructor)context_dealloc, /*tp_dealloc*/
3351 0, /*tp_print*/
3352 0, /*tp_getattr*/
3353 0, /*tp_setattr*/
3354 0, /*tp_reserved*/
3355 0, /*tp_repr*/
3356 0, /*tp_as_number*/
3357 0, /*tp_as_sequence*/
3358 0, /*tp_as_mapping*/
3359 0, /*tp_hash*/
3360 0, /*tp_call*/
3361 0, /*tp_str*/
3362 0, /*tp_getattro*/
3363 0, /*tp_setattro*/
3364 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003365 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003366 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003367 (traverseproc) context_traverse, /*tp_traverse*/
3368 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003369 0, /*tp_richcompare*/
3370 0, /*tp_weaklistoffset*/
3371 0, /*tp_iter*/
3372 0, /*tp_iternext*/
3373 context_methods, /*tp_methods*/
3374 0, /*tp_members*/
3375 context_getsetlist, /*tp_getset*/
3376 0, /*tp_base*/
3377 0, /*tp_dict*/
3378 0, /*tp_descr_get*/
3379 0, /*tp_descr_set*/
3380 0, /*tp_dictoffset*/
3381 0, /*tp_init*/
3382 0, /*tp_alloc*/
3383 context_new, /*tp_new*/
3384};
3385
3386
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003387/*
3388 * MemoryBIO objects
3389 */
3390
3391static PyObject *
3392memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3393{
3394 char *kwlist[] = {NULL};
3395 BIO *bio;
3396 PySSLMemoryBIO *self;
3397
3398 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3399 return NULL;
3400
3401 bio = BIO_new(BIO_s_mem());
3402 if (bio == NULL) {
3403 PyErr_SetString(PySSLErrorObject,
3404 "failed to allocate BIO");
3405 return NULL;
3406 }
3407 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3408 * just that no data is currently available. The SSL routines should retry
3409 * the read, which we can achieve by calling BIO_set_retry_read(). */
3410 BIO_set_retry_read(bio);
3411 BIO_set_mem_eof_return(bio, -1);
3412
3413 assert(type != NULL && type->tp_alloc != NULL);
3414 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3415 if (self == NULL) {
3416 BIO_free(bio);
3417 return NULL;
3418 }
3419 self->bio = bio;
3420 self->eof_written = 0;
3421
3422 return (PyObject *) self;
3423}
3424
3425static void
3426memory_bio_dealloc(PySSLMemoryBIO *self)
3427{
3428 BIO_free(self->bio);
3429 Py_TYPE(self)->tp_free(self);
3430}
3431
3432static PyObject *
3433memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3434{
3435 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3436}
3437
3438PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3439"The number of bytes pending in the memory BIO.");
3440
3441static PyObject *
3442memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3443{
3444 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3445 && self->eof_written);
3446}
3447
3448PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3449"Whether the memory BIO is at EOF.");
3450
3451static PyObject *
3452memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3453{
3454 int len = -1, avail, nbytes;
3455 PyObject *result;
3456
3457 if (!PyArg_ParseTuple(args, "|i:read", &len))
3458 return NULL;
3459
3460 avail = BIO_ctrl_pending(self->bio);
3461 if ((len < 0) || (len > avail))
3462 len = avail;
3463
3464 result = PyBytes_FromStringAndSize(NULL, len);
3465 if ((result == NULL) || (len == 0))
3466 return result;
3467
3468 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3469 /* There should never be any short reads but check anyway. */
3470 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3471 Py_DECREF(result);
3472 return NULL;
3473 }
3474
3475 return result;
3476}
3477
3478PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3479"read([len]) -> bytes\n\
3480\n\
3481Read up to len bytes from the memory BIO.\n\
3482\n\
3483If len is not specified, read the entire buffer.\n\
3484If the return value is an empty bytes instance, this means either\n\
3485EOF or that no data is available. Use the \"eof\" property to\n\
3486distinguish between the two.");
3487
3488static PyObject *
3489memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3490{
3491 Py_buffer buf;
3492 int nbytes;
3493
3494 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3495 return NULL;
3496
3497 if (buf.len > INT_MAX) {
3498 PyErr_Format(PyExc_OverflowError,
3499 "string longer than %d bytes", INT_MAX);
3500 goto error;
3501 }
3502
3503 if (self->eof_written) {
3504 PyErr_SetString(PySSLErrorObject,
3505 "cannot write() after write_eof()");
3506 goto error;
3507 }
3508
3509 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3510 if (nbytes < 0) {
3511 _setSSLError(NULL, 0, __FILE__, __LINE__);
3512 goto error;
3513 }
3514
3515 PyBuffer_Release(&buf);
3516 return PyLong_FromLong(nbytes);
3517
3518error:
3519 PyBuffer_Release(&buf);
3520 return NULL;
3521}
3522
3523PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3524"write(b) -> len\n\
3525\n\
3526Writes the bytes b into the memory BIO. Returns the number\n\
3527of bytes written.");
3528
3529static PyObject *
3530memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3531{
3532 self->eof_written = 1;
3533 /* After an EOF is written, a zero return from read() should be a real EOF
3534 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3535 BIO_clear_retry_flags(self->bio);
3536 BIO_set_mem_eof_return(self->bio, 0);
3537
3538 Py_RETURN_NONE;
3539}
3540
3541PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3542"write_eof()\n\
3543\n\
3544Write an EOF marker to the memory BIO.\n\
3545When all data has been read, the \"eof\" property will be True.");
3546
3547static PyGetSetDef memory_bio_getsetlist[] = {
3548 {"pending", (getter) memory_bio_get_pending, NULL,
3549 PySSL_memory_bio_pending_doc},
3550 {"eof", (getter) memory_bio_get_eof, NULL,
3551 PySSL_memory_bio_eof_doc},
3552 {NULL}, /* sentinel */
3553};
3554
3555static struct PyMethodDef memory_bio_methods[] = {
3556 {"read", (PyCFunction) memory_bio_read,
3557 METH_VARARGS, PySSL_memory_bio_read_doc},
3558 {"write", (PyCFunction) memory_bio_write,
3559 METH_VARARGS, PySSL_memory_bio_write_doc},
3560 {"write_eof", (PyCFunction) memory_bio_write_eof,
3561 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3562 {NULL, NULL} /* sentinel */
3563};
3564
3565static PyTypeObject PySSLMemoryBIO_Type = {
3566 PyVarObject_HEAD_INIT(NULL, 0)
3567 "_ssl.MemoryBIO", /*tp_name*/
3568 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3569 0, /*tp_itemsize*/
3570 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3571 0, /*tp_print*/
3572 0, /*tp_getattr*/
3573 0, /*tp_setattr*/
3574 0, /*tp_reserved*/
3575 0, /*tp_repr*/
3576 0, /*tp_as_number*/
3577 0, /*tp_as_sequence*/
3578 0, /*tp_as_mapping*/
3579 0, /*tp_hash*/
3580 0, /*tp_call*/
3581 0, /*tp_str*/
3582 0, /*tp_getattro*/
3583 0, /*tp_setattro*/
3584 0, /*tp_as_buffer*/
3585 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3586 0, /*tp_doc*/
3587 0, /*tp_traverse*/
3588 0, /*tp_clear*/
3589 0, /*tp_richcompare*/
3590 0, /*tp_weaklistoffset*/
3591 0, /*tp_iter*/
3592 0, /*tp_iternext*/
3593 memory_bio_methods, /*tp_methods*/
3594 0, /*tp_members*/
3595 memory_bio_getsetlist, /*tp_getset*/
3596 0, /*tp_base*/
3597 0, /*tp_dict*/
3598 0, /*tp_descr_get*/
3599 0, /*tp_descr_set*/
3600 0, /*tp_dictoffset*/
3601 0, /*tp_init*/
3602 0, /*tp_alloc*/
3603 memory_bio_new, /*tp_new*/
3604};
3605
Antoine Pitrou152efa22010-05-16 18:19:27 +00003606
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003607#ifdef HAVE_OPENSSL_RAND
3608
3609/* helper routines for seeding the SSL PRNG */
3610static PyObject *
3611PySSL_RAND_add(PyObject *self, PyObject *args)
3612{
3613 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003614 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003615 double entropy;
3616
3617 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003618 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003619 do {
3620 written = Py_MIN(len, INT_MAX);
3621 RAND_add(buf, (int)written, entropy);
3622 buf += written;
3623 len -= written;
3624 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003625 Py_INCREF(Py_None);
3626 return Py_None;
3627}
3628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003629PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003630"RAND_add(string, entropy)\n\
3631\n\
3632Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003633bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003634
3635static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003636PySSL_RAND(int len, int pseudo)
3637{
3638 int ok;
3639 PyObject *bytes;
3640 unsigned long err;
3641 const char *errstr;
3642 PyObject *v;
3643
Victor Stinner1e81a392013-12-19 16:47:04 +01003644 if (len < 0) {
3645 PyErr_SetString(PyExc_ValueError, "num must be positive");
3646 return NULL;
3647 }
3648
Victor Stinner99c8b162011-05-24 12:05:19 +02003649 bytes = PyBytes_FromStringAndSize(NULL, len);
3650 if (bytes == NULL)
3651 return NULL;
3652 if (pseudo) {
3653 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3654 if (ok == 0 || ok == 1)
3655 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3656 }
3657 else {
3658 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3659 if (ok == 1)
3660 return bytes;
3661 }
3662 Py_DECREF(bytes);
3663
3664 err = ERR_get_error();
3665 errstr = ERR_reason_error_string(err);
3666 v = Py_BuildValue("(ks)", err, errstr);
3667 if (v != NULL) {
3668 PyErr_SetObject(PySSLErrorObject, v);
3669 Py_DECREF(v);
3670 }
3671 return NULL;
3672}
3673
3674static PyObject *
3675PySSL_RAND_bytes(PyObject *self, PyObject *args)
3676{
3677 int len;
3678 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3679 return NULL;
3680 return PySSL_RAND(len, 0);
3681}
3682
3683PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3684"RAND_bytes(n) -> bytes\n\
3685\n\
3686Generate n cryptographically strong pseudo-random bytes.");
3687
3688static PyObject *
3689PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3690{
3691 int len;
3692 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3693 return NULL;
3694 return PySSL_RAND(len, 1);
3695}
3696
3697PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3698"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3699\n\
3700Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3701generated are cryptographically strong.");
3702
3703static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003704PySSL_RAND_status(PyObject *self)
3705{
Christian Heimes217cfd12007-12-02 14:31:20 +00003706 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003707}
3708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003709PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003710"RAND_status() -> 0 or 1\n\
3711\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003712Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3713It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3714using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003715
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003716#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003717static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003718PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003719{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003720 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003721 int bytes;
3722
Jesus Ceac8754a12012-09-11 02:00:58 +02003723 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003724 PyUnicode_FSConverter, &path))
3725 return NULL;
3726
3727 bytes = RAND_egd(PyBytes_AsString(path));
3728 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003729 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003730 PyErr_SetString(PySSLErrorObject,
3731 "EGD connection failed or EGD did not return "
3732 "enough data to seed the PRNG");
3733 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003734 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003735 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003736}
3737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003738PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003739"RAND_egd(path) -> bytes\n\
3740\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003741Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3742Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003743fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003744#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003745
Christian Heimesf77b4b22013-08-21 13:26:05 +02003746#endif /* HAVE_OPENSSL_RAND */
3747
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003748
Christian Heimes6d7ad132013-06-09 18:02:55 +02003749PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3750"get_default_verify_paths() -> tuple\n\
3751\n\
3752Return search paths and environment vars that are used by SSLContext's\n\
3753set_default_verify_paths() to load default CAs. The values are\n\
3754'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3755
3756static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003757PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003758{
3759 PyObject *ofile_env = NULL;
3760 PyObject *ofile = NULL;
3761 PyObject *odir_env = NULL;
3762 PyObject *odir = NULL;
3763
3764#define convert(info, target) { \
3765 const char *tmp = (info); \
3766 target = NULL; \
3767 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3768 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3769 target = PyBytes_FromString(tmp); } \
3770 if (!target) goto error; \
3771 } while(0)
3772
3773 convert(X509_get_default_cert_file_env(), ofile_env);
3774 convert(X509_get_default_cert_file(), ofile);
3775 convert(X509_get_default_cert_dir_env(), odir_env);
3776 convert(X509_get_default_cert_dir(), odir);
3777#undef convert
3778
Christian Heimes200bb1b2013-06-14 15:14:29 +02003779 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003780
3781 error:
3782 Py_XDECREF(ofile_env);
3783 Py_XDECREF(ofile);
3784 Py_XDECREF(odir_env);
3785 Py_XDECREF(odir);
3786 return NULL;
3787}
3788
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003789static PyObject*
3790asn1obj2py(ASN1_OBJECT *obj)
3791{
3792 int nid;
3793 const char *ln, *sn;
3794 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003795 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003796
3797 nid = OBJ_obj2nid(obj);
3798 if (nid == NID_undef) {
3799 PyErr_Format(PyExc_ValueError, "Unknown object");
3800 return NULL;
3801 }
3802 sn = OBJ_nid2sn(nid);
3803 ln = OBJ_nid2ln(nid);
3804 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3805 if (buflen < 0) {
3806 _setSSLError(NULL, 0, __FILE__, __LINE__);
3807 return NULL;
3808 }
3809 if (buflen) {
3810 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3811 } else {
3812 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3813 }
3814}
3815
3816PyDoc_STRVAR(PySSL_txt2obj_doc,
3817"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3818\n\
3819Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3820objects are looked up by OID. With name=True short and long name are also\n\
3821matched.");
3822
3823static PyObject*
3824PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3825{
3826 char *kwlist[] = {"txt", "name", NULL};
3827 PyObject *result = NULL;
3828 char *txt;
3829 int name = 0;
3830 ASN1_OBJECT *obj;
3831
3832 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3833 kwlist, &txt, &name)) {
3834 return NULL;
3835 }
3836 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3837 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003838 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003839 return NULL;
3840 }
3841 result = asn1obj2py(obj);
3842 ASN1_OBJECT_free(obj);
3843 return result;
3844}
3845
3846PyDoc_STRVAR(PySSL_nid2obj_doc,
3847"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3848\n\
3849Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3850
3851static PyObject*
3852PySSL_nid2obj(PyObject *self, PyObject *args)
3853{
3854 PyObject *result = NULL;
3855 int nid;
3856 ASN1_OBJECT *obj;
3857
3858 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3859 return NULL;
3860 }
3861 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003862 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003863 return NULL;
3864 }
3865 obj = OBJ_nid2obj(nid);
3866 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003867 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003868 return NULL;
3869 }
3870 result = asn1obj2py(obj);
3871 ASN1_OBJECT_free(obj);
3872 return result;
3873}
3874
Christian Heimes46bebee2013-06-09 19:03:31 +02003875#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003876
3877static PyObject*
3878certEncodingType(DWORD encodingType)
3879{
3880 static PyObject *x509_asn = NULL;
3881 static PyObject *pkcs_7_asn = NULL;
3882
3883 if (x509_asn == NULL) {
3884 x509_asn = PyUnicode_InternFromString("x509_asn");
3885 if (x509_asn == NULL)
3886 return NULL;
3887 }
3888 if (pkcs_7_asn == NULL) {
3889 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3890 if (pkcs_7_asn == NULL)
3891 return NULL;
3892 }
3893 switch(encodingType) {
3894 case X509_ASN_ENCODING:
3895 Py_INCREF(x509_asn);
3896 return x509_asn;
3897 case PKCS_7_ASN_ENCODING:
3898 Py_INCREF(pkcs_7_asn);
3899 return pkcs_7_asn;
3900 default:
3901 return PyLong_FromLong(encodingType);
3902 }
3903}
3904
3905static PyObject*
3906parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3907{
3908 CERT_ENHKEY_USAGE *usage;
3909 DWORD size, error, i;
3910 PyObject *retval;
3911
3912 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3913 error = GetLastError();
3914 if (error == CRYPT_E_NOT_FOUND) {
3915 Py_RETURN_TRUE;
3916 }
3917 return PyErr_SetFromWindowsErr(error);
3918 }
3919
3920 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3921 if (usage == NULL) {
3922 return PyErr_NoMemory();
3923 }
3924
3925 /* Now get the actual enhanced usage property */
3926 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3927 PyMem_Free(usage);
3928 error = GetLastError();
3929 if (error == CRYPT_E_NOT_FOUND) {
3930 Py_RETURN_TRUE;
3931 }
3932 return PyErr_SetFromWindowsErr(error);
3933 }
3934 retval = PySet_New(NULL);
3935 if (retval == NULL) {
3936 goto error;
3937 }
3938 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3939 if (usage->rgpszUsageIdentifier[i]) {
3940 PyObject *oid;
3941 int err;
3942 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3943 if (oid == NULL) {
3944 Py_CLEAR(retval);
3945 goto error;
3946 }
3947 err = PySet_Add(retval, oid);
3948 Py_DECREF(oid);
3949 if (err == -1) {
3950 Py_CLEAR(retval);
3951 goto error;
3952 }
3953 }
3954 }
3955 error:
3956 PyMem_Free(usage);
3957 return retval;
3958}
3959
3960PyDoc_STRVAR(PySSL_enum_certificates_doc,
3961"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003962\n\
3963Retrieve certificates from Windows' cert store. store_name may be one of\n\
3964'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003965The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003966encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003967PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3968boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003969
Christian Heimes46bebee2013-06-09 19:03:31 +02003970static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003971PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003972{
Christian Heimes44109d72013-11-22 01:51:30 +01003973 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003974 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003975 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003976 PCCERT_CONTEXT pCertCtx = NULL;
3977 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003978 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003979
Christian Heimes44109d72013-11-22 01:51:30 +01003980 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3981 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003982 return NULL;
3983 }
Christian Heimes44109d72013-11-22 01:51:30 +01003984 result = PyList_New(0);
3985 if (result == NULL) {
3986 return NULL;
3987 }
3988 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3989 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003990 Py_DECREF(result);
3991 return PyErr_SetFromWindowsErr(GetLastError());
3992 }
3993
Christian Heimes44109d72013-11-22 01:51:30 +01003994 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3995 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3996 pCertCtx->cbCertEncoded);
3997 if (!cert) {
3998 Py_CLEAR(result);
3999 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004000 }
Christian Heimes44109d72013-11-22 01:51:30 +01004001 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4002 Py_CLEAR(result);
4003 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004004 }
Christian Heimes44109d72013-11-22 01:51:30 +01004005 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4006 if (keyusage == Py_True) {
4007 Py_DECREF(keyusage);
4008 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004009 }
Christian Heimes44109d72013-11-22 01:51:30 +01004010 if (keyusage == NULL) {
4011 Py_CLEAR(result);
4012 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004013 }
Christian Heimes44109d72013-11-22 01:51:30 +01004014 if ((tup = PyTuple_New(3)) == NULL) {
4015 Py_CLEAR(result);
4016 break;
4017 }
4018 PyTuple_SET_ITEM(tup, 0, cert);
4019 cert = NULL;
4020 PyTuple_SET_ITEM(tup, 1, enc);
4021 enc = NULL;
4022 PyTuple_SET_ITEM(tup, 2, keyusage);
4023 keyusage = NULL;
4024 if (PyList_Append(result, tup) < 0) {
4025 Py_CLEAR(result);
4026 break;
4027 }
4028 Py_CLEAR(tup);
4029 }
4030 if (pCertCtx) {
4031 /* loop ended with an error, need to clean up context manually */
4032 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004033 }
4034
4035 /* In error cases cert, enc and tup may not be NULL */
4036 Py_XDECREF(cert);
4037 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004038 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004039 Py_XDECREF(tup);
4040
4041 if (!CertCloseStore(hStore, 0)) {
4042 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004043 Py_XDECREF(result);
4044 return PyErr_SetFromWindowsErr(GetLastError());
4045 }
4046 return result;
4047}
4048
4049PyDoc_STRVAR(PySSL_enum_crls_doc,
4050"enum_crls(store_name) -> []\n\
4051\n\
4052Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4053'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4054The function returns a list of (bytes, encoding_type) tuples. The\n\
4055encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4056PKCS_7_ASN_ENCODING.");
4057
4058static PyObject *
4059PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4060{
4061 char *kwlist[] = {"store_name", NULL};
4062 char *store_name;
4063 HCERTSTORE hStore = NULL;
4064 PCCRL_CONTEXT pCrlCtx = NULL;
4065 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4066 PyObject *result = NULL;
4067
4068 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4069 kwlist, &store_name)) {
4070 return NULL;
4071 }
4072 result = PyList_New(0);
4073 if (result == NULL) {
4074 return NULL;
4075 }
4076 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4077 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004078 Py_DECREF(result);
4079 return PyErr_SetFromWindowsErr(GetLastError());
4080 }
Christian Heimes44109d72013-11-22 01:51:30 +01004081
4082 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4083 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4084 pCrlCtx->cbCrlEncoded);
4085 if (!crl) {
4086 Py_CLEAR(result);
4087 break;
4088 }
4089 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4090 Py_CLEAR(result);
4091 break;
4092 }
4093 if ((tup = PyTuple_New(2)) == NULL) {
4094 Py_CLEAR(result);
4095 break;
4096 }
4097 PyTuple_SET_ITEM(tup, 0, crl);
4098 crl = NULL;
4099 PyTuple_SET_ITEM(tup, 1, enc);
4100 enc = NULL;
4101
4102 if (PyList_Append(result, tup) < 0) {
4103 Py_CLEAR(result);
4104 break;
4105 }
4106 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004107 }
Christian Heimes44109d72013-11-22 01:51:30 +01004108 if (pCrlCtx) {
4109 /* loop ended with an error, need to clean up context manually */
4110 CertFreeCRLContext(pCrlCtx);
4111 }
4112
4113 /* In error cases cert, enc and tup may not be NULL */
4114 Py_XDECREF(crl);
4115 Py_XDECREF(enc);
4116 Py_XDECREF(tup);
4117
4118 if (!CertCloseStore(hStore, 0)) {
4119 /* This error case might shadow another exception.*/
4120 Py_XDECREF(result);
4121 return PyErr_SetFromWindowsErr(GetLastError());
4122 }
4123 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004124}
Christian Heimes44109d72013-11-22 01:51:30 +01004125
4126#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004127
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004128/* List of functions exported by this module. */
4129
4130static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004131 {"_test_decode_cert", PySSL_test_decode_certificate,
4132 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004133#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004134 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4135 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004136 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4137 PySSL_RAND_bytes_doc},
4138 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4139 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004140#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004141 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004142 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004143#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004144 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4145 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02004146#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02004147 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004148 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004149#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004150 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4151 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4152 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4153 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004154#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004155 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4156 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4157 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4158 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004159 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004160};
4161
4162
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004163#ifdef WITH_THREAD
4164
4165/* an implementation of OpenSSL threading operations in terms
4166 of the Python C thread library */
4167
4168static PyThread_type_lock *_ssl_locks = NULL;
4169
Christian Heimes4d98ca92013-08-19 17:36:29 +02004170#if OPENSSL_VERSION_NUMBER >= 0x10000000
4171/* use new CRYPTO_THREADID API. */
4172static void
4173_ssl_threadid_callback(CRYPTO_THREADID *id)
4174{
4175 CRYPTO_THREADID_set_numeric(id,
4176 (unsigned long)PyThread_get_thread_ident());
4177}
4178#else
4179/* deprecated CRYPTO_set_id_callback() API. */
4180static unsigned long
4181_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004182 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004183}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004184#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004185
Bill Janssen6e027db2007-11-15 22:23:56 +00004186static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004187 (int mode, int n, const char *file, int line) {
4188 /* this function is needed to perform locking on shared data
4189 structures. (Note that OpenSSL uses a number of global data
4190 structures that will be implicitly shared whenever multiple
4191 threads use OpenSSL.) Multi-threaded applications will
4192 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004194 locking_function() must be able to handle up to
4195 CRYPTO_num_locks() different mutex locks. It sets the n-th
4196 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004198 file and line are the file number of the function setting the
4199 lock. They can be useful for debugging.
4200 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004202 if ((_ssl_locks == NULL) ||
4203 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4204 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004206 if (mode & CRYPTO_LOCK) {
4207 PyThread_acquire_lock(_ssl_locks[n], 1);
4208 } else {
4209 PyThread_release_lock(_ssl_locks[n]);
4210 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004211}
4212
4213static int _setup_ssl_threads(void) {
4214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004215 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004217 if (_ssl_locks == NULL) {
4218 _ssl_locks_count = CRYPTO_num_locks();
4219 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02004220 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004221 if (_ssl_locks == NULL)
4222 return 0;
4223 memset(_ssl_locks, 0,
4224 sizeof(PyThread_type_lock) * _ssl_locks_count);
4225 for (i = 0; i < _ssl_locks_count; i++) {
4226 _ssl_locks[i] = PyThread_allocate_lock();
4227 if (_ssl_locks[i] == NULL) {
4228 unsigned int j;
4229 for (j = 0; j < i; j++) {
4230 PyThread_free_lock(_ssl_locks[j]);
4231 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004232 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004233 return 0;
4234 }
4235 }
4236 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004237#if OPENSSL_VERSION_NUMBER >= 0x10000000
4238 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4239#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004240 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004241#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004242 }
4243 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004244}
4245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004246#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004248PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004249"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004250for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004251
Martin v. Löwis1a214512008-06-11 05:26:20 +00004252
4253static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004254 PyModuleDef_HEAD_INIT,
4255 "_ssl",
4256 module_doc,
4257 -1,
4258 PySSL_methods,
4259 NULL,
4260 NULL,
4261 NULL,
4262 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004263};
4264
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004265
4266static void
4267parse_openssl_version(unsigned long libver,
4268 unsigned int *major, unsigned int *minor,
4269 unsigned int *fix, unsigned int *patch,
4270 unsigned int *status)
4271{
4272 *status = libver & 0xF;
4273 libver >>= 4;
4274 *patch = libver & 0xFF;
4275 libver >>= 8;
4276 *fix = libver & 0xFF;
4277 libver >>= 8;
4278 *minor = libver & 0xFF;
4279 libver >>= 8;
4280 *major = libver & 0xFF;
4281}
4282
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004283PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004284PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004285{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004286 PyObject *m, *d, *r;
4287 unsigned long libver;
4288 unsigned int major, minor, fix, patch, status;
4289 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004290 struct py_ssl_error_code *errcode;
4291 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004292
Antoine Pitrou152efa22010-05-16 18:19:27 +00004293 if (PyType_Ready(&PySSLContext_Type) < 0)
4294 return NULL;
4295 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004296 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004297 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4298 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004300 m = PyModule_Create(&_sslmodule);
4301 if (m == NULL)
4302 return NULL;
4303 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004305 /* Load _socket module and its C API */
4306 socket_api = PySocketModule_ImportModuleAndAPI();
4307 if (!socket_api)
4308 return NULL;
4309 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004311 /* Init OpenSSL */
4312 SSL_load_error_strings();
4313 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004314#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004315 /* note that this will start threading if not already started */
4316 if (!_setup_ssl_threads()) {
4317 return NULL;
4318 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004319#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004320 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004322 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004323 sslerror_type_slots[0].pfunc = PyExc_OSError;
4324 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004325 if (PySSLErrorObject == NULL)
4326 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004327
Antoine Pitrou41032a62011-10-27 23:56:55 +02004328 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4329 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4330 PySSLErrorObject, NULL);
4331 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4332 "ssl.SSLWantReadError", SSLWantReadError_doc,
4333 PySSLErrorObject, NULL);
4334 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4335 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4336 PySSLErrorObject, NULL);
4337 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4338 "ssl.SSLSyscallError", SSLSyscallError_doc,
4339 PySSLErrorObject, NULL);
4340 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4341 "ssl.SSLEOFError", SSLEOFError_doc,
4342 PySSLErrorObject, NULL);
4343 if (PySSLZeroReturnErrorObject == NULL
4344 || PySSLWantReadErrorObject == NULL
4345 || PySSLWantWriteErrorObject == NULL
4346 || PySSLSyscallErrorObject == NULL
4347 || PySSLEOFErrorObject == NULL)
4348 return NULL;
4349 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4350 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4351 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4352 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4353 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4354 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004355 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004356 if (PyDict_SetItemString(d, "_SSLContext",
4357 (PyObject *)&PySSLContext_Type) != 0)
4358 return NULL;
4359 if (PyDict_SetItemString(d, "_SSLSocket",
4360 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004361 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004362 if (PyDict_SetItemString(d, "MemoryBIO",
4363 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4364 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004365 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4366 PY_SSL_ERROR_ZERO_RETURN);
4367 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4368 PY_SSL_ERROR_WANT_READ);
4369 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4370 PY_SSL_ERROR_WANT_WRITE);
4371 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4372 PY_SSL_ERROR_WANT_X509_LOOKUP);
4373 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4374 PY_SSL_ERROR_SYSCALL);
4375 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4376 PY_SSL_ERROR_SSL);
4377 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4378 PY_SSL_ERROR_WANT_CONNECT);
4379 /* non ssl.h errorcodes */
4380 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4381 PY_SSL_ERROR_EOF);
4382 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4383 PY_SSL_ERROR_INVALID_ERROR_CODE);
4384 /* cert requirements */
4385 PyModule_AddIntConstant(m, "CERT_NONE",
4386 PY_SSL_CERT_NONE);
4387 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4388 PY_SSL_CERT_OPTIONAL);
4389 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4390 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004391 /* CRL verification for verification_flags */
4392 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4393 0);
4394 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4395 X509_V_FLAG_CRL_CHECK);
4396 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4397 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4398 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4399 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004400
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004401 /* Alert Descriptions from ssl.h */
4402 /* note RESERVED constants no longer intended for use have been removed */
4403 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4404
4405#define ADD_AD_CONSTANT(s) \
4406 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4407 SSL_AD_##s)
4408
4409 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4410 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4411 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4412 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4413 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4414 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4415 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4416 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4417 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4418 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4419 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4420 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4421 ADD_AD_CONSTANT(UNKNOWN_CA);
4422 ADD_AD_CONSTANT(ACCESS_DENIED);
4423 ADD_AD_CONSTANT(DECODE_ERROR);
4424 ADD_AD_CONSTANT(DECRYPT_ERROR);
4425 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4426 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4427 ADD_AD_CONSTANT(INTERNAL_ERROR);
4428 ADD_AD_CONSTANT(USER_CANCELLED);
4429 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004430 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004431#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4432 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4433#endif
4434#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4435 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4436#endif
4437#ifdef SSL_AD_UNRECOGNIZED_NAME
4438 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4439#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004440#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4441 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4442#endif
4443#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4444 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4445#endif
4446#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4447 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4448#endif
4449
4450#undef ADD_AD_CONSTANT
4451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004452 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004453#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004454 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4455 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004456#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004457 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4458 PY_SSL_VERSION_SSL3);
4459 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4460 PY_SSL_VERSION_SSL23);
4461 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4462 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004463#if HAVE_TLSv1_2
4464 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4465 PY_SSL_VERSION_TLS1_1);
4466 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4467 PY_SSL_VERSION_TLS1_2);
4468#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004469
Antoine Pitroub5218772010-05-21 09:56:06 +00004470 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004471 PyModule_AddIntConstant(m, "OP_ALL",
4472 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004473 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4474 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4475 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004476#if HAVE_TLSv1_2
4477 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4478 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4479#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004480 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4481 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004482 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004483#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004484 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004485#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004486#ifdef SSL_OP_NO_COMPRESSION
4487 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4488 SSL_OP_NO_COMPRESSION);
4489#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004490
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004491#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004492 r = Py_True;
4493#else
4494 r = Py_False;
4495#endif
4496 Py_INCREF(r);
4497 PyModule_AddObject(m, "HAS_SNI", r);
4498
Antoine Pitroud6494802011-07-21 01:11:30 +02004499#if HAVE_OPENSSL_FINISHED
4500 r = Py_True;
4501#else
4502 r = Py_False;
4503#endif
4504 Py_INCREF(r);
4505 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4506
Antoine Pitrou501da612011-12-21 09:27:41 +01004507#ifdef OPENSSL_NO_ECDH
4508 r = Py_False;
4509#else
4510 r = Py_True;
4511#endif
4512 Py_INCREF(r);
4513 PyModule_AddObject(m, "HAS_ECDH", r);
4514
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004515#ifdef OPENSSL_NPN_NEGOTIATED
4516 r = Py_True;
4517#else
4518 r = Py_False;
4519#endif
4520 Py_INCREF(r);
4521 PyModule_AddObject(m, "HAS_NPN", r);
4522
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004523 /* Mappings for error codes */
4524 err_codes_to_names = PyDict_New();
4525 err_names_to_codes = PyDict_New();
4526 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4527 return NULL;
4528 errcode = error_codes;
4529 while (errcode->mnemonic != NULL) {
4530 PyObject *mnemo, *key;
4531 mnemo = PyUnicode_FromString(errcode->mnemonic);
4532 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4533 if (mnemo == NULL || key == NULL)
4534 return NULL;
4535 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4536 return NULL;
4537 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4538 return NULL;
4539 Py_DECREF(key);
4540 Py_DECREF(mnemo);
4541 errcode++;
4542 }
4543 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4544 return NULL;
4545 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4546 return NULL;
4547
4548 lib_codes_to_names = PyDict_New();
4549 if (lib_codes_to_names == NULL)
4550 return NULL;
4551 libcode = library_codes;
4552 while (libcode->library != NULL) {
4553 PyObject *mnemo, *key;
4554 key = PyLong_FromLong(libcode->code);
4555 mnemo = PyUnicode_FromString(libcode->library);
4556 if (key == NULL || mnemo == NULL)
4557 return NULL;
4558 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4559 return NULL;
4560 Py_DECREF(key);
4561 Py_DECREF(mnemo);
4562 libcode++;
4563 }
4564 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4565 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004567 /* OpenSSL version */
4568 /* SSLeay() gives us the version of the library linked against,
4569 which could be different from the headers version.
4570 */
4571 libver = SSLeay();
4572 r = PyLong_FromUnsignedLong(libver);
4573 if (r == NULL)
4574 return NULL;
4575 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4576 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004577 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004578 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4579 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4580 return NULL;
4581 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4582 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4583 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004584
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004585 libver = OPENSSL_VERSION_NUMBER;
4586 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4587 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4588 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4589 return NULL;
4590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004591 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004592}