blob: 36e77395fce73d2b65ec12539c566e63adf0531d [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
Benjamin Petersone32467c2014-12-05 21:59:35 -05002135#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 else if (proto_version == PY_SSL_VERSION_SSL3)
2137 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002138#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002139#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140 else if (proto_version == PY_SSL_VERSION_SSL2)
2141 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002142#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002143 else if (proto_version == PY_SSL_VERSION_SSL23)
2144 ctx = SSL_CTX_new(SSLv23_method());
2145 else
2146 proto_version = -1;
2147 PySSL_END_ALLOW_THREADS
2148
2149 if (proto_version == -1) {
2150 PyErr_SetString(PyExc_ValueError,
2151 "invalid protocol version");
2152 return NULL;
2153 }
2154 if (ctx == NULL) {
2155 PyErr_SetString(PySSLErrorObject,
2156 "failed to allocate SSL context");
2157 return NULL;
2158 }
2159
2160 assert(type != NULL && type->tp_alloc != NULL);
2161 self = (PySSLContext *) type->tp_alloc(type, 0);
2162 if (self == NULL) {
2163 SSL_CTX_free(ctx);
2164 return NULL;
2165 }
2166 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002167#ifdef OPENSSL_NPN_NEGOTIATED
2168 self->npn_protocols = NULL;
2169#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002170#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002171 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002172#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002173 /* Don't check host name by default */
2174 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002175 /* Defaults */
2176 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002177 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2178 if (proto_version != PY_SSL_VERSION_SSL2)
2179 options |= SSL_OP_NO_SSLv2;
2180 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002181
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002182#ifndef OPENSSL_NO_ECDH
2183 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2184 prime256v1 by default. This is Apache mod_ssl's initialization
2185 policy, so we should be safe. */
2186#if defined(SSL_CTX_set_ecdh_auto)
2187 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2188#else
2189 {
2190 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2191 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2192 EC_KEY_free(key);
2193 }
2194#endif
2195#endif
2196
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002197#define SID_CTX "Python"
2198 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2199 sizeof(SID_CTX));
2200#undef SID_CTX
2201
Antoine Pitrou152efa22010-05-16 18:19:27 +00002202 return (PyObject *)self;
2203}
2204
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002205static int
2206context_traverse(PySSLContext *self, visitproc visit, void *arg)
2207{
2208#ifndef OPENSSL_NO_TLSEXT
2209 Py_VISIT(self->set_hostname);
2210#endif
2211 return 0;
2212}
2213
2214static int
2215context_clear(PySSLContext *self)
2216{
2217#ifndef OPENSSL_NO_TLSEXT
2218 Py_CLEAR(self->set_hostname);
2219#endif
2220 return 0;
2221}
2222
Antoine Pitrou152efa22010-05-16 18:19:27 +00002223static void
2224context_dealloc(PySSLContext *self)
2225{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002226 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002227 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002228#ifdef OPENSSL_NPN_NEGOTIATED
2229 PyMem_Free(self->npn_protocols);
2230#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002231 Py_TYPE(self)->tp_free(self);
2232}
2233
2234static PyObject *
2235set_ciphers(PySSLContext *self, PyObject *args)
2236{
2237 int ret;
2238 const char *cipherlist;
2239
2240 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2241 return NULL;
2242 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2243 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002244 /* Clearing the error queue is necessary on some OpenSSL versions,
2245 otherwise the error will be reported again when another SSL call
2246 is done. */
2247 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002248 PyErr_SetString(PySSLErrorObject,
2249 "No cipher can be selected.");
2250 return NULL;
2251 }
2252 Py_RETURN_NONE;
2253}
2254
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002255#ifdef OPENSSL_NPN_NEGOTIATED
2256/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2257static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002258_advertiseNPN_cb(SSL *s,
2259 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002260 void *args)
2261{
2262 PySSLContext *ssl_ctx = (PySSLContext *) args;
2263
2264 if (ssl_ctx->npn_protocols == NULL) {
2265 *data = (unsigned char *) "";
2266 *len = 0;
2267 } else {
2268 *data = (unsigned char *) ssl_ctx->npn_protocols;
2269 *len = ssl_ctx->npn_protocols_len;
2270 }
2271
2272 return SSL_TLSEXT_ERR_OK;
2273}
2274/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2275static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002276_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002277 unsigned char **out, unsigned char *outlen,
2278 const unsigned char *server, unsigned int server_len,
2279 void *args)
2280{
2281 PySSLContext *ssl_ctx = (PySSLContext *) args;
2282
2283 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2284 int client_len;
2285
2286 if (client == NULL) {
2287 client = (unsigned char *) "";
2288 client_len = 0;
2289 } else {
2290 client_len = ssl_ctx->npn_protocols_len;
2291 }
2292
2293 SSL_select_next_proto(out, outlen,
2294 server, server_len,
2295 client, client_len);
2296
2297 return SSL_TLSEXT_ERR_OK;
2298}
2299#endif
2300
2301static PyObject *
2302_set_npn_protocols(PySSLContext *self, PyObject *args)
2303{
2304#ifdef OPENSSL_NPN_NEGOTIATED
2305 Py_buffer protos;
2306
2307 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2308 return NULL;
2309
Christian Heimes5cb31c92012-09-20 12:42:54 +02002310 if (self->npn_protocols != NULL) {
2311 PyMem_Free(self->npn_protocols);
2312 }
2313
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002314 self->npn_protocols = PyMem_Malloc(protos.len);
2315 if (self->npn_protocols == NULL) {
2316 PyBuffer_Release(&protos);
2317 return PyErr_NoMemory();
2318 }
2319 memcpy(self->npn_protocols, protos.buf, protos.len);
2320 self->npn_protocols_len = (int) protos.len;
2321
2322 /* set both server and client callbacks, because the context can
2323 * be used to create both types of sockets */
2324 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2325 _advertiseNPN_cb,
2326 self);
2327 SSL_CTX_set_next_proto_select_cb(self->ctx,
2328 _selectNPN_cb,
2329 self);
2330
2331 PyBuffer_Release(&protos);
2332 Py_RETURN_NONE;
2333#else
2334 PyErr_SetString(PyExc_NotImplementedError,
2335 "The NPN extension requires OpenSSL 1.0.1 or later.");
2336 return NULL;
2337#endif
2338}
2339
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340static PyObject *
2341get_verify_mode(PySSLContext *self, void *c)
2342{
2343 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2344 case SSL_VERIFY_NONE:
2345 return PyLong_FromLong(PY_SSL_CERT_NONE);
2346 case SSL_VERIFY_PEER:
2347 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2348 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2349 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2350 }
2351 PyErr_SetString(PySSLErrorObject,
2352 "invalid return value from SSL_CTX_get_verify_mode");
2353 return NULL;
2354}
2355
2356static int
2357set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2358{
2359 int n, mode;
2360 if (!PyArg_Parse(arg, "i", &n))
2361 return -1;
2362 if (n == PY_SSL_CERT_NONE)
2363 mode = SSL_VERIFY_NONE;
2364 else if (n == PY_SSL_CERT_OPTIONAL)
2365 mode = SSL_VERIFY_PEER;
2366 else if (n == PY_SSL_CERT_REQUIRED)
2367 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2368 else {
2369 PyErr_SetString(PyExc_ValueError,
2370 "invalid value for verify_mode");
2371 return -1;
2372 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002373 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2374 PyErr_SetString(PyExc_ValueError,
2375 "Cannot set verify_mode to CERT_NONE when "
2376 "check_hostname is enabled.");
2377 return -1;
2378 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002379 SSL_CTX_set_verify(self->ctx, mode, NULL);
2380 return 0;
2381}
2382
Christian Heimes2427b502013-11-23 11:24:32 +01002383#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002384static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002385get_verify_flags(PySSLContext *self, void *c)
2386{
2387 X509_STORE *store;
2388 unsigned long flags;
2389
2390 store = SSL_CTX_get_cert_store(self->ctx);
2391 flags = X509_VERIFY_PARAM_get_flags(store->param);
2392 return PyLong_FromUnsignedLong(flags);
2393}
2394
2395static int
2396set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2397{
2398 X509_STORE *store;
2399 unsigned long new_flags, flags, set, clear;
2400
2401 if (!PyArg_Parse(arg, "k", &new_flags))
2402 return -1;
2403 store = SSL_CTX_get_cert_store(self->ctx);
2404 flags = X509_VERIFY_PARAM_get_flags(store->param);
2405 clear = flags & ~new_flags;
2406 set = ~flags & new_flags;
2407 if (clear) {
2408 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2409 _setSSLError(NULL, 0, __FILE__, __LINE__);
2410 return -1;
2411 }
2412 }
2413 if (set) {
2414 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2415 _setSSLError(NULL, 0, __FILE__, __LINE__);
2416 return -1;
2417 }
2418 }
2419 return 0;
2420}
Christian Heimes2427b502013-11-23 11:24:32 +01002421#endif
Christian Heimes22587792013-11-21 23:56:13 +01002422
2423static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002424get_options(PySSLContext *self, void *c)
2425{
2426 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2427}
2428
2429static int
2430set_options(PySSLContext *self, PyObject *arg, void *c)
2431{
2432 long new_opts, opts, set, clear;
2433 if (!PyArg_Parse(arg, "l", &new_opts))
2434 return -1;
2435 opts = SSL_CTX_get_options(self->ctx);
2436 clear = opts & ~new_opts;
2437 set = ~opts & new_opts;
2438 if (clear) {
2439#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2440 SSL_CTX_clear_options(self->ctx, clear);
2441#else
2442 PyErr_SetString(PyExc_ValueError,
2443 "can't clear options before OpenSSL 0.9.8m");
2444 return -1;
2445#endif
2446 }
2447 if (set)
2448 SSL_CTX_set_options(self->ctx, set);
2449 return 0;
2450}
2451
Christian Heimes1aa9a752013-12-02 02:41:19 +01002452static PyObject *
2453get_check_hostname(PySSLContext *self, void *c)
2454{
2455 return PyBool_FromLong(self->check_hostname);
2456}
2457
2458static int
2459set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2460{
2461 int check_hostname;
2462 if (!PyArg_Parse(arg, "p", &check_hostname))
2463 return -1;
2464 if (check_hostname &&
2465 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2466 PyErr_SetString(PyExc_ValueError,
2467 "check_hostname needs a SSL context with either "
2468 "CERT_OPTIONAL or CERT_REQUIRED");
2469 return -1;
2470 }
2471 self->check_hostname = check_hostname;
2472 return 0;
2473}
2474
2475
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002476typedef struct {
2477 PyThreadState *thread_state;
2478 PyObject *callable;
2479 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002480 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002481 int error;
2482} _PySSLPasswordInfo;
2483
2484static int
2485_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2486 const char *bad_type_error)
2487{
2488 /* Set the password and size fields of a _PySSLPasswordInfo struct
2489 from a unicode, bytes, or byte array object.
2490 The password field will be dynamically allocated and must be freed
2491 by the caller */
2492 PyObject *password_bytes = NULL;
2493 const char *data = NULL;
2494 Py_ssize_t size;
2495
2496 if (PyUnicode_Check(password)) {
2497 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2498 if (!password_bytes) {
2499 goto error;
2500 }
2501 data = PyBytes_AS_STRING(password_bytes);
2502 size = PyBytes_GET_SIZE(password_bytes);
2503 } else if (PyBytes_Check(password)) {
2504 data = PyBytes_AS_STRING(password);
2505 size = PyBytes_GET_SIZE(password);
2506 } else if (PyByteArray_Check(password)) {
2507 data = PyByteArray_AS_STRING(password);
2508 size = PyByteArray_GET_SIZE(password);
2509 } else {
2510 PyErr_SetString(PyExc_TypeError, bad_type_error);
2511 goto error;
2512 }
2513
Victor Stinner9ee02032013-06-23 15:08:23 +02002514 if (size > (Py_ssize_t)INT_MAX) {
2515 PyErr_Format(PyExc_ValueError,
2516 "password cannot be longer than %d bytes", INT_MAX);
2517 goto error;
2518 }
2519
Victor Stinner11ebff22013-07-07 17:07:52 +02002520 PyMem_Free(pw_info->password);
2521 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002522 if (!pw_info->password) {
2523 PyErr_SetString(PyExc_MemoryError,
2524 "unable to allocate password buffer");
2525 goto error;
2526 }
2527 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002528 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002529
2530 Py_XDECREF(password_bytes);
2531 return 1;
2532
2533error:
2534 Py_XDECREF(password_bytes);
2535 return 0;
2536}
2537
2538static int
2539_password_callback(char *buf, int size, int rwflag, void *userdata)
2540{
2541 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2542 PyObject *fn_ret = NULL;
2543
2544 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2545
2546 if (pw_info->callable) {
2547 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2548 if (!fn_ret) {
2549 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2550 core python API, so we could use it to add a frame here */
2551 goto error;
2552 }
2553
2554 if (!_pwinfo_set(pw_info, fn_ret,
2555 "password callback must return a string")) {
2556 goto error;
2557 }
2558 Py_CLEAR(fn_ret);
2559 }
2560
2561 if (pw_info->size > size) {
2562 PyErr_Format(PyExc_ValueError,
2563 "password cannot be longer than %d bytes", size);
2564 goto error;
2565 }
2566
2567 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2568 memcpy(buf, pw_info->password, pw_info->size);
2569 return pw_info->size;
2570
2571error:
2572 Py_XDECREF(fn_ret);
2573 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2574 pw_info->error = 1;
2575 return -1;
2576}
2577
Antoine Pitroub5218772010-05-21 09:56:06 +00002578static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002579load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2580{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002581 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2582 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002583 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002584 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2585 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2586 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002587 int r;
2588
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002589 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002590 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002591 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002592 "O|OO:load_cert_chain", kwlist,
2593 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002594 return NULL;
2595 if (keyfile == Py_None)
2596 keyfile = NULL;
2597 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2598 PyErr_SetString(PyExc_TypeError,
2599 "certfile should be a valid filesystem path");
2600 return NULL;
2601 }
2602 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2603 PyErr_SetString(PyExc_TypeError,
2604 "keyfile should be a valid filesystem path");
2605 goto error;
2606 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002607 if (password && password != Py_None) {
2608 if (PyCallable_Check(password)) {
2609 pw_info.callable = password;
2610 } else if (!_pwinfo_set(&pw_info, password,
2611 "password should be a string or callable")) {
2612 goto error;
2613 }
2614 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2615 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2616 }
2617 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2619 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002620 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002621 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002622 if (pw_info.error) {
2623 ERR_clear_error();
2624 /* the password callback has already set the error information */
2625 }
2626 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002627 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002628 PyErr_SetFromErrno(PyExc_IOError);
2629 }
2630 else {
2631 _setSSLError(NULL, 0, __FILE__, __LINE__);
2632 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002633 goto error;
2634 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002635 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002636 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002637 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2638 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002639 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2640 Py_CLEAR(keyfile_bytes);
2641 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002642 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002643 if (pw_info.error) {
2644 ERR_clear_error();
2645 /* the password callback has already set the error information */
2646 }
2647 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002648 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002649 PyErr_SetFromErrno(PyExc_IOError);
2650 }
2651 else {
2652 _setSSLError(NULL, 0, __FILE__, __LINE__);
2653 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002654 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002656 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002658 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002659 if (r != 1) {
2660 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002661 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002663 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2664 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002665 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002666 Py_RETURN_NONE;
2667
2668error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002669 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2670 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002671 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002672 Py_XDECREF(keyfile_bytes);
2673 Py_XDECREF(certfile_bytes);
2674 return NULL;
2675}
2676
Christian Heimesefff7062013-11-21 03:35:02 +01002677/* internal helper function, returns -1 on error
2678 */
2679static int
2680_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2681 int filetype)
2682{
2683 BIO *biobuf = NULL;
2684 X509_STORE *store;
2685 int retval = 0, err, loaded = 0;
2686
2687 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2688
2689 if (len <= 0) {
2690 PyErr_SetString(PyExc_ValueError,
2691 "Empty certificate data");
2692 return -1;
2693 } else if (len > INT_MAX) {
2694 PyErr_SetString(PyExc_OverflowError,
2695 "Certificate data is too long.");
2696 return -1;
2697 }
2698
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002699 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002700 if (biobuf == NULL) {
2701 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2702 return -1;
2703 }
2704
2705 store = SSL_CTX_get_cert_store(self->ctx);
2706 assert(store != NULL);
2707
2708 while (1) {
2709 X509 *cert = NULL;
2710 int r;
2711
2712 if (filetype == SSL_FILETYPE_ASN1) {
2713 cert = d2i_X509_bio(biobuf, NULL);
2714 } else {
2715 cert = PEM_read_bio_X509(biobuf, NULL,
2716 self->ctx->default_passwd_callback,
2717 self->ctx->default_passwd_callback_userdata);
2718 }
2719 if (cert == NULL) {
2720 break;
2721 }
2722 r = X509_STORE_add_cert(store, cert);
2723 X509_free(cert);
2724 if (!r) {
2725 err = ERR_peek_last_error();
2726 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2727 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2728 /* cert already in hash table, not an error */
2729 ERR_clear_error();
2730 } else {
2731 break;
2732 }
2733 }
2734 loaded++;
2735 }
2736
2737 err = ERR_peek_last_error();
2738 if ((filetype == SSL_FILETYPE_ASN1) &&
2739 (loaded > 0) &&
2740 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2741 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2742 /* EOF ASN1 file, not an error */
2743 ERR_clear_error();
2744 retval = 0;
2745 } else if ((filetype == SSL_FILETYPE_PEM) &&
2746 (loaded > 0) &&
2747 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2748 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2749 /* EOF PEM file, not an error */
2750 ERR_clear_error();
2751 retval = 0;
2752 } else {
2753 _setSSLError(NULL, 0, __FILE__, __LINE__);
2754 retval = -1;
2755 }
2756
2757 BIO_free(biobuf);
2758 return retval;
2759}
2760
2761
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762static PyObject *
2763load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2764{
Christian Heimesefff7062013-11-21 03:35:02 +01002765 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2766 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002767 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2768 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002769 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002770
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002771 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002772 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002773 "|OOO:load_verify_locations", kwlist,
2774 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002775 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002776
Antoine Pitrou152efa22010-05-16 18:19:27 +00002777 if (cafile == Py_None)
2778 cafile = NULL;
2779 if (capath == Py_None)
2780 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002781 if (cadata == Py_None)
2782 cadata = NULL;
2783
2784 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002786 "cafile, capath and cadata cannot be all omitted");
2787 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788 }
2789 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2790 PyErr_SetString(PyExc_TypeError,
2791 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002792 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 }
2794 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002795 PyErr_SetString(PyExc_TypeError,
2796 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002797 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798 }
Christian Heimesefff7062013-11-21 03:35:02 +01002799
2800 /* validata cadata type and load cadata */
2801 if (cadata) {
2802 Py_buffer buf;
2803 PyObject *cadata_ascii = NULL;
2804
2805 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2806 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2807 PyBuffer_Release(&buf);
2808 PyErr_SetString(PyExc_TypeError,
2809 "cadata should be a contiguous buffer with "
2810 "a single dimension");
2811 goto error;
2812 }
2813 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2814 PyBuffer_Release(&buf);
2815 if (r == -1) {
2816 goto error;
2817 }
2818 } else {
2819 PyErr_Clear();
2820 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2821 if (cadata_ascii == NULL) {
2822 PyErr_SetString(PyExc_TypeError,
2823 "cadata should be a ASCII string or a "
2824 "bytes-like object");
2825 goto error;
2826 }
2827 r = _add_ca_certs(self,
2828 PyBytes_AS_STRING(cadata_ascii),
2829 PyBytes_GET_SIZE(cadata_ascii),
2830 SSL_FILETYPE_PEM);
2831 Py_DECREF(cadata_ascii);
2832 if (r == -1) {
2833 goto error;
2834 }
2835 }
2836 }
2837
2838 /* load cafile or capath */
2839 if (cafile || capath) {
2840 if (cafile)
2841 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2842 if (capath)
2843 capath_buf = PyBytes_AS_STRING(capath_bytes);
2844 PySSL_BEGIN_ALLOW_THREADS
2845 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2846 PySSL_END_ALLOW_THREADS
2847 if (r != 1) {
2848 ok = 0;
2849 if (errno != 0) {
2850 ERR_clear_error();
2851 PyErr_SetFromErrno(PyExc_IOError);
2852 }
2853 else {
2854 _setSSLError(NULL, 0, __FILE__, __LINE__);
2855 }
2856 goto error;
2857 }
2858 }
2859 goto end;
2860
2861 error:
2862 ok = 0;
2863 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002864 Py_XDECREF(cafile_bytes);
2865 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002866 if (ok) {
2867 Py_RETURN_NONE;
2868 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869 return NULL;
2870 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871}
2872
2873static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002874load_dh_params(PySSLContext *self, PyObject *filepath)
2875{
2876 FILE *f;
2877 DH *dh;
2878
Victor Stinnerdaf45552013-08-28 00:53:59 +02002879 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002880 if (f == NULL) {
2881 if (!PyErr_Occurred())
2882 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2883 return NULL;
2884 }
2885 errno = 0;
2886 PySSL_BEGIN_ALLOW_THREADS
2887 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002888 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002889 PySSL_END_ALLOW_THREADS
2890 if (dh == NULL) {
2891 if (errno != 0) {
2892 ERR_clear_error();
2893 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2894 }
2895 else {
2896 _setSSLError(NULL, 0, __FILE__, __LINE__);
2897 }
2898 return NULL;
2899 }
2900 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2901 _setSSLError(NULL, 0, __FILE__, __LINE__);
2902 DH_free(dh);
2903 Py_RETURN_NONE;
2904}
2905
2906static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002907context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2908{
Antoine Pitroud5323212010-10-22 18:19:07 +00002909 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002910 PySocketSockObject *sock;
2911 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002912 char *hostname = NULL;
2913 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002914
Antoine Pitroud5323212010-10-22 18:19:07 +00002915 /* server_hostname is either None (or absent), or to be encoded
2916 using the idna encoding. */
2917 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002919 &sock, &server_side,
2920 Py_TYPE(Py_None), &hostname_obj)) {
2921 PyErr_Clear();
2922 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2923 PySocketModule.Sock_Type,
2924 &sock, &server_side,
2925 "idna", &hostname))
2926 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002927 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002928
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002929 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2930 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002931 if (hostname != NULL)
2932 PyMem_Free(hostname);
2933 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002934}
2935
Antoine Pitroub0182c82010-10-12 20:09:02 +00002936static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002937context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
2938{
2939 char *kwlist[] = {"incoming", "outgoing", "server_side",
2940 "server_hostname", NULL};
2941 int server_side;
2942 char *hostname = NULL;
2943 PyObject *hostname_obj = Py_None, *res;
2944 PySSLMemoryBIO *incoming, *outgoing;
2945
2946 /* server_hostname is either None (or absent), or to be encoded
2947 using the idna encoding. */
2948 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
2949 &PySSLMemoryBIO_Type, &incoming,
2950 &PySSLMemoryBIO_Type, &outgoing,
2951 &server_side, &hostname_obj))
2952 return NULL;
2953 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002954 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
2955 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002956 }
2957
2958 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
2959 incoming, outgoing);
2960
2961 PyMem_Free(hostname);
2962 return res;
2963}
2964
2965static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00002966session_stats(PySSLContext *self, PyObject *unused)
2967{
2968 int r;
2969 PyObject *value, *stats = PyDict_New();
2970 if (!stats)
2971 return NULL;
2972
2973#define ADD_STATS(SSL_NAME, KEY_NAME) \
2974 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2975 if (value == NULL) \
2976 goto error; \
2977 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2978 Py_DECREF(value); \
2979 if (r < 0) \
2980 goto error;
2981
2982 ADD_STATS(number, "number");
2983 ADD_STATS(connect, "connect");
2984 ADD_STATS(connect_good, "connect_good");
2985 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2986 ADD_STATS(accept, "accept");
2987 ADD_STATS(accept_good, "accept_good");
2988 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2989 ADD_STATS(accept, "accept");
2990 ADD_STATS(hits, "hits");
2991 ADD_STATS(misses, "misses");
2992 ADD_STATS(timeouts, "timeouts");
2993 ADD_STATS(cache_full, "cache_full");
2994
2995#undef ADD_STATS
2996
2997 return stats;
2998
2999error:
3000 Py_DECREF(stats);
3001 return NULL;
3002}
3003
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003004static PyObject *
3005set_default_verify_paths(PySSLContext *self, PyObject *unused)
3006{
3007 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3008 _setSSLError(NULL, 0, __FILE__, __LINE__);
3009 return NULL;
3010 }
3011 Py_RETURN_NONE;
3012}
3013
Antoine Pitrou501da612011-12-21 09:27:41 +01003014#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003015static PyObject *
3016set_ecdh_curve(PySSLContext *self, PyObject *name)
3017{
3018 PyObject *name_bytes;
3019 int nid;
3020 EC_KEY *key;
3021
3022 if (!PyUnicode_FSConverter(name, &name_bytes))
3023 return NULL;
3024 assert(PyBytes_Check(name_bytes));
3025 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3026 Py_DECREF(name_bytes);
3027 if (nid == 0) {
3028 PyErr_Format(PyExc_ValueError,
3029 "unknown elliptic curve name %R", name);
3030 return NULL;
3031 }
3032 key = EC_KEY_new_by_curve_name(nid);
3033 if (key == NULL) {
3034 _setSSLError(NULL, 0, __FILE__, __LINE__);
3035 return NULL;
3036 }
3037 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3038 EC_KEY_free(key);
3039 Py_RETURN_NONE;
3040}
Antoine Pitrou501da612011-12-21 09:27:41 +01003041#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003042
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003043#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003044static int
3045_servername_callback(SSL *s, int *al, void *args)
3046{
3047 int ret;
3048 PySSLContext *ssl_ctx = (PySSLContext *) args;
3049 PySSLSocket *ssl;
3050 PyObject *servername_o;
3051 PyObject *servername_idna;
3052 PyObject *result;
3053 /* The high-level ssl.SSLSocket object */
3054 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003055 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003056#ifdef WITH_THREAD
3057 PyGILState_STATE gstate = PyGILState_Ensure();
3058#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003059
3060 if (ssl_ctx->set_hostname == NULL) {
3061 /* remove race condition in this the call back while if removing the
3062 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003063#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003064 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003065#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003066 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003067 }
3068
3069 ssl = SSL_get_app_data(s);
3070 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003071
3072 /* The servername callback expects a argument that represents the current
3073 * SSL connection and that has a .context attribute that can be changed to
3074 * identify the requested hostname. Since the official API is the Python
3075 * level API we want to pass the callback a Python level object rather than
3076 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3077 * SSLObject) that will be passed. Otherwise if there's a socket then that
3078 * will be passed. If both do not exist only then the C-level object is
3079 * passed. */
3080 if (ssl->owner)
3081 ssl_socket = PyWeakref_GetObject(ssl->owner);
3082 else if (ssl->Socket)
3083 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3084 else
3085 ssl_socket = (PyObject *) ssl;
3086
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003087 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003088 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003089 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003090
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003091 if (servername == NULL) {
3092 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3093 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003094 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003095 else {
3096 servername_o = PyBytes_FromString(servername);
3097 if (servername_o == NULL) {
3098 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3099 goto error;
3100 }
3101 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3102 if (servername_idna == NULL) {
3103 PyErr_WriteUnraisable(servername_o);
3104 Py_DECREF(servername_o);
3105 goto error;
3106 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003107 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003108 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3109 servername_idna, ssl_ctx, NULL);
3110 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003111 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003112 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003113
3114 if (result == NULL) {
3115 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3116 *al = SSL_AD_HANDSHAKE_FAILURE;
3117 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3118 }
3119 else {
3120 if (result != Py_None) {
3121 *al = (int) PyLong_AsLong(result);
3122 if (PyErr_Occurred()) {
3123 PyErr_WriteUnraisable(result);
3124 *al = SSL_AD_INTERNAL_ERROR;
3125 }
3126 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3127 }
3128 else {
3129 ret = SSL_TLSEXT_ERR_OK;
3130 }
3131 Py_DECREF(result);
3132 }
3133
Stefan Krah20d60802013-01-17 17:07:17 +01003134#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003135 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003136#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003137 return ret;
3138
3139error:
3140 Py_DECREF(ssl_socket);
3141 *al = SSL_AD_INTERNAL_ERROR;
3142 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003143#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003145#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003146 return ret;
3147}
Antoine Pitroua5963382013-03-30 16:39:00 +01003148#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003149
3150PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3151"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003152\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003153This sets a callback that will be called when a server name is provided by\n\
3154the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003155\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003156If the argument is None then the callback is disabled. The method is called\n\
3157with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003158See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003159
3160static PyObject *
3161set_servername_callback(PySSLContext *self, PyObject *args)
3162{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003163#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003164 PyObject *cb;
3165
3166 if (!PyArg_ParseTuple(args, "O", &cb))
3167 return NULL;
3168
3169 Py_CLEAR(self->set_hostname);
3170 if (cb == Py_None) {
3171 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3172 }
3173 else {
3174 if (!PyCallable_Check(cb)) {
3175 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3176 PyErr_SetString(PyExc_TypeError,
3177 "not a callable object");
3178 return NULL;
3179 }
3180 Py_INCREF(cb);
3181 self->set_hostname = cb;
3182 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3183 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3184 }
3185 Py_RETURN_NONE;
3186#else
3187 PyErr_SetString(PyExc_NotImplementedError,
3188 "The TLS extension servername callback, "
3189 "SSL_CTX_set_tlsext_servername_callback, "
3190 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003191 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003192#endif
3193}
3194
Christian Heimes9a5395a2013-06-17 15:44:12 +02003195PyDoc_STRVAR(PySSL_get_stats_doc,
3196"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3197\n\
3198Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3199CA extension and certificate revocation lists inside the context's cert\n\
3200store.\n\
3201NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3202been used at least once.");
3203
3204static PyObject *
3205cert_store_stats(PySSLContext *self)
3206{
3207 X509_STORE *store;
3208 X509_OBJECT *obj;
3209 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3210
3211 store = SSL_CTX_get_cert_store(self->ctx);
3212 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3213 obj = sk_X509_OBJECT_value(store->objs, i);
3214 switch (obj->type) {
3215 case X509_LU_X509:
3216 x509++;
3217 if (X509_check_ca(obj->data.x509)) {
3218 ca++;
3219 }
3220 break;
3221 case X509_LU_CRL:
3222 crl++;
3223 break;
3224 case X509_LU_PKEY:
3225 pkey++;
3226 break;
3227 default:
3228 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3229 * As far as I can tell they are internal states and never
3230 * stored in a cert store */
3231 break;
3232 }
3233 }
3234 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3235 "x509_ca", ca);
3236}
3237
3238PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003239"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003240\n\
3241Returns a list of dicts with information of loaded CA certs. If the\n\
3242optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3243NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3244been used at least once.");
3245
3246static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003247get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003248{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003249 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003250 X509_STORE *store;
3251 PyObject *ci = NULL, *rlist = NULL;
3252 int i;
3253 int binary_mode = 0;
3254
Christian Heimesf22e8e52013-11-22 02:22:51 +01003255 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3256 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003257 return NULL;
3258 }
3259
3260 if ((rlist = PyList_New(0)) == NULL) {
3261 return NULL;
3262 }
3263
3264 store = SSL_CTX_get_cert_store(self->ctx);
3265 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3266 X509_OBJECT *obj;
3267 X509 *cert;
3268
3269 obj = sk_X509_OBJECT_value(store->objs, i);
3270 if (obj->type != X509_LU_X509) {
3271 /* not a x509 cert */
3272 continue;
3273 }
3274 /* CA for any purpose */
3275 cert = obj->data.x509;
3276 if (!X509_check_ca(cert)) {
3277 continue;
3278 }
3279 if (binary_mode) {
3280 ci = _certificate_to_der(cert);
3281 } else {
3282 ci = _decode_certificate(cert);
3283 }
3284 if (ci == NULL) {
3285 goto error;
3286 }
3287 if (PyList_Append(rlist, ci) == -1) {
3288 goto error;
3289 }
3290 Py_CLEAR(ci);
3291 }
3292 return rlist;
3293
3294 error:
3295 Py_XDECREF(ci);
3296 Py_XDECREF(rlist);
3297 return NULL;
3298}
3299
3300
Antoine Pitrou152efa22010-05-16 18:19:27 +00003301static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003302 {"check_hostname", (getter) get_check_hostname,
3303 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003304 {"options", (getter) get_options,
3305 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003306#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003307 {"verify_flags", (getter) get_verify_flags,
3308 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003309#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310 {"verify_mode", (getter) get_verify_mode,
3311 (setter) set_verify_mode, NULL},
3312 {NULL}, /* sentinel */
3313};
3314
3315static struct PyMethodDef context_methods[] = {
3316 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3317 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003318 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3319 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320 {"set_ciphers", (PyCFunction) set_ciphers,
3321 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003322 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3323 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003324 {"load_cert_chain", (PyCFunction) load_cert_chain,
3325 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003326 {"load_dh_params", (PyCFunction) load_dh_params,
3327 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 {"load_verify_locations", (PyCFunction) load_verify_locations,
3329 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003330 {"session_stats", (PyCFunction) session_stats,
3331 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003332 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3333 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003334#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003335 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3336 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003337#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003338 {"set_servername_callback", (PyCFunction) set_servername_callback,
3339 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003340 {"cert_store_stats", (PyCFunction) cert_store_stats,
3341 METH_NOARGS, PySSL_get_stats_doc},
3342 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003343 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003344 {NULL, NULL} /* sentinel */
3345};
3346
3347static PyTypeObject PySSLContext_Type = {
3348 PyVarObject_HEAD_INIT(NULL, 0)
3349 "_ssl._SSLContext", /*tp_name*/
3350 sizeof(PySSLContext), /*tp_basicsize*/
3351 0, /*tp_itemsize*/
3352 (destructor)context_dealloc, /*tp_dealloc*/
3353 0, /*tp_print*/
3354 0, /*tp_getattr*/
3355 0, /*tp_setattr*/
3356 0, /*tp_reserved*/
3357 0, /*tp_repr*/
3358 0, /*tp_as_number*/
3359 0, /*tp_as_sequence*/
3360 0, /*tp_as_mapping*/
3361 0, /*tp_hash*/
3362 0, /*tp_call*/
3363 0, /*tp_str*/
3364 0, /*tp_getattro*/
3365 0, /*tp_setattro*/
3366 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003367 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003368 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003369 (traverseproc) context_traverse, /*tp_traverse*/
3370 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003371 0, /*tp_richcompare*/
3372 0, /*tp_weaklistoffset*/
3373 0, /*tp_iter*/
3374 0, /*tp_iternext*/
3375 context_methods, /*tp_methods*/
3376 0, /*tp_members*/
3377 context_getsetlist, /*tp_getset*/
3378 0, /*tp_base*/
3379 0, /*tp_dict*/
3380 0, /*tp_descr_get*/
3381 0, /*tp_descr_set*/
3382 0, /*tp_dictoffset*/
3383 0, /*tp_init*/
3384 0, /*tp_alloc*/
3385 context_new, /*tp_new*/
3386};
3387
3388
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003389/*
3390 * MemoryBIO objects
3391 */
3392
3393static PyObject *
3394memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3395{
3396 char *kwlist[] = {NULL};
3397 BIO *bio;
3398 PySSLMemoryBIO *self;
3399
3400 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3401 return NULL;
3402
3403 bio = BIO_new(BIO_s_mem());
3404 if (bio == NULL) {
3405 PyErr_SetString(PySSLErrorObject,
3406 "failed to allocate BIO");
3407 return NULL;
3408 }
3409 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3410 * just that no data is currently available. The SSL routines should retry
3411 * the read, which we can achieve by calling BIO_set_retry_read(). */
3412 BIO_set_retry_read(bio);
3413 BIO_set_mem_eof_return(bio, -1);
3414
3415 assert(type != NULL && type->tp_alloc != NULL);
3416 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3417 if (self == NULL) {
3418 BIO_free(bio);
3419 return NULL;
3420 }
3421 self->bio = bio;
3422 self->eof_written = 0;
3423
3424 return (PyObject *) self;
3425}
3426
3427static void
3428memory_bio_dealloc(PySSLMemoryBIO *self)
3429{
3430 BIO_free(self->bio);
3431 Py_TYPE(self)->tp_free(self);
3432}
3433
3434static PyObject *
3435memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3436{
3437 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3438}
3439
3440PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3441"The number of bytes pending in the memory BIO.");
3442
3443static PyObject *
3444memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3445{
3446 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3447 && self->eof_written);
3448}
3449
3450PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3451"Whether the memory BIO is at EOF.");
3452
3453static PyObject *
3454memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3455{
3456 int len = -1, avail, nbytes;
3457 PyObject *result;
3458
3459 if (!PyArg_ParseTuple(args, "|i:read", &len))
3460 return NULL;
3461
3462 avail = BIO_ctrl_pending(self->bio);
3463 if ((len < 0) || (len > avail))
3464 len = avail;
3465
3466 result = PyBytes_FromStringAndSize(NULL, len);
3467 if ((result == NULL) || (len == 0))
3468 return result;
3469
3470 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3471 /* There should never be any short reads but check anyway. */
3472 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3473 Py_DECREF(result);
3474 return NULL;
3475 }
3476
3477 return result;
3478}
3479
3480PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3481"read([len]) -> bytes\n\
3482\n\
3483Read up to len bytes from the memory BIO.\n\
3484\n\
3485If len is not specified, read the entire buffer.\n\
3486If the return value is an empty bytes instance, this means either\n\
3487EOF or that no data is available. Use the \"eof\" property to\n\
3488distinguish between the two.");
3489
3490static PyObject *
3491memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3492{
3493 Py_buffer buf;
3494 int nbytes;
3495
3496 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3497 return NULL;
3498
3499 if (buf.len > INT_MAX) {
3500 PyErr_Format(PyExc_OverflowError,
3501 "string longer than %d bytes", INT_MAX);
3502 goto error;
3503 }
3504
3505 if (self->eof_written) {
3506 PyErr_SetString(PySSLErrorObject,
3507 "cannot write() after write_eof()");
3508 goto error;
3509 }
3510
3511 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3512 if (nbytes < 0) {
3513 _setSSLError(NULL, 0, __FILE__, __LINE__);
3514 goto error;
3515 }
3516
3517 PyBuffer_Release(&buf);
3518 return PyLong_FromLong(nbytes);
3519
3520error:
3521 PyBuffer_Release(&buf);
3522 return NULL;
3523}
3524
3525PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3526"write(b) -> len\n\
3527\n\
3528Writes the bytes b into the memory BIO. Returns the number\n\
3529of bytes written.");
3530
3531static PyObject *
3532memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3533{
3534 self->eof_written = 1;
3535 /* After an EOF is written, a zero return from read() should be a real EOF
3536 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3537 BIO_clear_retry_flags(self->bio);
3538 BIO_set_mem_eof_return(self->bio, 0);
3539
3540 Py_RETURN_NONE;
3541}
3542
3543PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3544"write_eof()\n\
3545\n\
3546Write an EOF marker to the memory BIO.\n\
3547When all data has been read, the \"eof\" property will be True.");
3548
3549static PyGetSetDef memory_bio_getsetlist[] = {
3550 {"pending", (getter) memory_bio_get_pending, NULL,
3551 PySSL_memory_bio_pending_doc},
3552 {"eof", (getter) memory_bio_get_eof, NULL,
3553 PySSL_memory_bio_eof_doc},
3554 {NULL}, /* sentinel */
3555};
3556
3557static struct PyMethodDef memory_bio_methods[] = {
3558 {"read", (PyCFunction) memory_bio_read,
3559 METH_VARARGS, PySSL_memory_bio_read_doc},
3560 {"write", (PyCFunction) memory_bio_write,
3561 METH_VARARGS, PySSL_memory_bio_write_doc},
3562 {"write_eof", (PyCFunction) memory_bio_write_eof,
3563 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3564 {NULL, NULL} /* sentinel */
3565};
3566
3567static PyTypeObject PySSLMemoryBIO_Type = {
3568 PyVarObject_HEAD_INIT(NULL, 0)
3569 "_ssl.MemoryBIO", /*tp_name*/
3570 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3571 0, /*tp_itemsize*/
3572 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3573 0, /*tp_print*/
3574 0, /*tp_getattr*/
3575 0, /*tp_setattr*/
3576 0, /*tp_reserved*/
3577 0, /*tp_repr*/
3578 0, /*tp_as_number*/
3579 0, /*tp_as_sequence*/
3580 0, /*tp_as_mapping*/
3581 0, /*tp_hash*/
3582 0, /*tp_call*/
3583 0, /*tp_str*/
3584 0, /*tp_getattro*/
3585 0, /*tp_setattro*/
3586 0, /*tp_as_buffer*/
3587 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3588 0, /*tp_doc*/
3589 0, /*tp_traverse*/
3590 0, /*tp_clear*/
3591 0, /*tp_richcompare*/
3592 0, /*tp_weaklistoffset*/
3593 0, /*tp_iter*/
3594 0, /*tp_iternext*/
3595 memory_bio_methods, /*tp_methods*/
3596 0, /*tp_members*/
3597 memory_bio_getsetlist, /*tp_getset*/
3598 0, /*tp_base*/
3599 0, /*tp_dict*/
3600 0, /*tp_descr_get*/
3601 0, /*tp_descr_set*/
3602 0, /*tp_dictoffset*/
3603 0, /*tp_init*/
3604 0, /*tp_alloc*/
3605 memory_bio_new, /*tp_new*/
3606};
3607
Antoine Pitrou152efa22010-05-16 18:19:27 +00003608
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003609#ifdef HAVE_OPENSSL_RAND
3610
3611/* helper routines for seeding the SSL PRNG */
3612static PyObject *
3613PySSL_RAND_add(PyObject *self, PyObject *args)
3614{
3615 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003616 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003617 double entropy;
3618
3619 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003620 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003621 do {
3622 written = Py_MIN(len, INT_MAX);
3623 RAND_add(buf, (int)written, entropy);
3624 buf += written;
3625 len -= written;
3626 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003627 Py_INCREF(Py_None);
3628 return Py_None;
3629}
3630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003631PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003632"RAND_add(string, entropy)\n\
3633\n\
3634Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003635bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003636
3637static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003638PySSL_RAND(int len, int pseudo)
3639{
3640 int ok;
3641 PyObject *bytes;
3642 unsigned long err;
3643 const char *errstr;
3644 PyObject *v;
3645
Victor Stinner1e81a392013-12-19 16:47:04 +01003646 if (len < 0) {
3647 PyErr_SetString(PyExc_ValueError, "num must be positive");
3648 return NULL;
3649 }
3650
Victor Stinner99c8b162011-05-24 12:05:19 +02003651 bytes = PyBytes_FromStringAndSize(NULL, len);
3652 if (bytes == NULL)
3653 return NULL;
3654 if (pseudo) {
3655 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3656 if (ok == 0 || ok == 1)
3657 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3658 }
3659 else {
3660 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3661 if (ok == 1)
3662 return bytes;
3663 }
3664 Py_DECREF(bytes);
3665
3666 err = ERR_get_error();
3667 errstr = ERR_reason_error_string(err);
3668 v = Py_BuildValue("(ks)", err, errstr);
3669 if (v != NULL) {
3670 PyErr_SetObject(PySSLErrorObject, v);
3671 Py_DECREF(v);
3672 }
3673 return NULL;
3674}
3675
3676static PyObject *
3677PySSL_RAND_bytes(PyObject *self, PyObject *args)
3678{
3679 int len;
3680 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3681 return NULL;
3682 return PySSL_RAND(len, 0);
3683}
3684
3685PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3686"RAND_bytes(n) -> bytes\n\
3687\n\
3688Generate n cryptographically strong pseudo-random bytes.");
3689
3690static PyObject *
3691PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3692{
3693 int len;
3694 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3695 return NULL;
3696 return PySSL_RAND(len, 1);
3697}
3698
3699PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3700"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3701\n\
3702Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3703generated are cryptographically strong.");
3704
3705static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003706PySSL_RAND_status(PyObject *self)
3707{
Christian Heimes217cfd12007-12-02 14:31:20 +00003708 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003709}
3710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003711PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003712"RAND_status() -> 0 or 1\n\
3713\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003714Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3715It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3716using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003717
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003718#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003719static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003720PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003721{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003722 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003723 int bytes;
3724
Jesus Ceac8754a12012-09-11 02:00:58 +02003725 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003726 PyUnicode_FSConverter, &path))
3727 return NULL;
3728
3729 bytes = RAND_egd(PyBytes_AsString(path));
3730 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003731 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003732 PyErr_SetString(PySSLErrorObject,
3733 "EGD connection failed or EGD did not return "
3734 "enough data to seed the PRNG");
3735 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003736 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003737 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003738}
3739
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003740PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003741"RAND_egd(path) -> bytes\n\
3742\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003743Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3744Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003745fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003746#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003747
Christian Heimesf77b4b22013-08-21 13:26:05 +02003748#endif /* HAVE_OPENSSL_RAND */
3749
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003750
Christian Heimes6d7ad132013-06-09 18:02:55 +02003751PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3752"get_default_verify_paths() -> tuple\n\
3753\n\
3754Return search paths and environment vars that are used by SSLContext's\n\
3755set_default_verify_paths() to load default CAs. The values are\n\
3756'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3757
3758static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003759PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003760{
3761 PyObject *ofile_env = NULL;
3762 PyObject *ofile = NULL;
3763 PyObject *odir_env = NULL;
3764 PyObject *odir = NULL;
3765
3766#define convert(info, target) { \
3767 const char *tmp = (info); \
3768 target = NULL; \
3769 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3770 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3771 target = PyBytes_FromString(tmp); } \
3772 if (!target) goto error; \
3773 } while(0)
3774
3775 convert(X509_get_default_cert_file_env(), ofile_env);
3776 convert(X509_get_default_cert_file(), ofile);
3777 convert(X509_get_default_cert_dir_env(), odir_env);
3778 convert(X509_get_default_cert_dir(), odir);
3779#undef convert
3780
Christian Heimes200bb1b2013-06-14 15:14:29 +02003781 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003782
3783 error:
3784 Py_XDECREF(ofile_env);
3785 Py_XDECREF(ofile);
3786 Py_XDECREF(odir_env);
3787 Py_XDECREF(odir);
3788 return NULL;
3789}
3790
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003791static PyObject*
3792asn1obj2py(ASN1_OBJECT *obj)
3793{
3794 int nid;
3795 const char *ln, *sn;
3796 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003797 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003798
3799 nid = OBJ_obj2nid(obj);
3800 if (nid == NID_undef) {
3801 PyErr_Format(PyExc_ValueError, "Unknown object");
3802 return NULL;
3803 }
3804 sn = OBJ_nid2sn(nid);
3805 ln = OBJ_nid2ln(nid);
3806 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3807 if (buflen < 0) {
3808 _setSSLError(NULL, 0, __FILE__, __LINE__);
3809 return NULL;
3810 }
3811 if (buflen) {
3812 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3813 } else {
3814 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3815 }
3816}
3817
3818PyDoc_STRVAR(PySSL_txt2obj_doc,
3819"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3820\n\
3821Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3822objects are looked up by OID. With name=True short and long name are also\n\
3823matched.");
3824
3825static PyObject*
3826PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3827{
3828 char *kwlist[] = {"txt", "name", NULL};
3829 PyObject *result = NULL;
3830 char *txt;
3831 int name = 0;
3832 ASN1_OBJECT *obj;
3833
3834 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3835 kwlist, &txt, &name)) {
3836 return NULL;
3837 }
3838 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3839 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003840 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003841 return NULL;
3842 }
3843 result = asn1obj2py(obj);
3844 ASN1_OBJECT_free(obj);
3845 return result;
3846}
3847
3848PyDoc_STRVAR(PySSL_nid2obj_doc,
3849"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3850\n\
3851Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3852
3853static PyObject*
3854PySSL_nid2obj(PyObject *self, PyObject *args)
3855{
3856 PyObject *result = NULL;
3857 int nid;
3858 ASN1_OBJECT *obj;
3859
3860 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3861 return NULL;
3862 }
3863 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003864 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003865 return NULL;
3866 }
3867 obj = OBJ_nid2obj(nid);
3868 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003869 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003870 return NULL;
3871 }
3872 result = asn1obj2py(obj);
3873 ASN1_OBJECT_free(obj);
3874 return result;
3875}
3876
Christian Heimes46bebee2013-06-09 19:03:31 +02003877#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003878
3879static PyObject*
3880certEncodingType(DWORD encodingType)
3881{
3882 static PyObject *x509_asn = NULL;
3883 static PyObject *pkcs_7_asn = NULL;
3884
3885 if (x509_asn == NULL) {
3886 x509_asn = PyUnicode_InternFromString("x509_asn");
3887 if (x509_asn == NULL)
3888 return NULL;
3889 }
3890 if (pkcs_7_asn == NULL) {
3891 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3892 if (pkcs_7_asn == NULL)
3893 return NULL;
3894 }
3895 switch(encodingType) {
3896 case X509_ASN_ENCODING:
3897 Py_INCREF(x509_asn);
3898 return x509_asn;
3899 case PKCS_7_ASN_ENCODING:
3900 Py_INCREF(pkcs_7_asn);
3901 return pkcs_7_asn;
3902 default:
3903 return PyLong_FromLong(encodingType);
3904 }
3905}
3906
3907static PyObject*
3908parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3909{
3910 CERT_ENHKEY_USAGE *usage;
3911 DWORD size, error, i;
3912 PyObject *retval;
3913
3914 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3915 error = GetLastError();
3916 if (error == CRYPT_E_NOT_FOUND) {
3917 Py_RETURN_TRUE;
3918 }
3919 return PyErr_SetFromWindowsErr(error);
3920 }
3921
3922 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3923 if (usage == NULL) {
3924 return PyErr_NoMemory();
3925 }
3926
3927 /* Now get the actual enhanced usage property */
3928 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3929 PyMem_Free(usage);
3930 error = GetLastError();
3931 if (error == CRYPT_E_NOT_FOUND) {
3932 Py_RETURN_TRUE;
3933 }
3934 return PyErr_SetFromWindowsErr(error);
3935 }
3936 retval = PySet_New(NULL);
3937 if (retval == NULL) {
3938 goto error;
3939 }
3940 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3941 if (usage->rgpszUsageIdentifier[i]) {
3942 PyObject *oid;
3943 int err;
3944 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3945 if (oid == NULL) {
3946 Py_CLEAR(retval);
3947 goto error;
3948 }
3949 err = PySet_Add(retval, oid);
3950 Py_DECREF(oid);
3951 if (err == -1) {
3952 Py_CLEAR(retval);
3953 goto error;
3954 }
3955 }
3956 }
3957 error:
3958 PyMem_Free(usage);
3959 return retval;
3960}
3961
3962PyDoc_STRVAR(PySSL_enum_certificates_doc,
3963"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003964\n\
3965Retrieve certificates from Windows' cert store. store_name may be one of\n\
3966'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003967The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003968encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003969PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3970boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003971
Christian Heimes46bebee2013-06-09 19:03:31 +02003972static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003973PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003974{
Christian Heimes44109d72013-11-22 01:51:30 +01003975 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003976 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003977 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003978 PCCERT_CONTEXT pCertCtx = NULL;
3979 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003980 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003981
Christian Heimes44109d72013-11-22 01:51:30 +01003982 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3983 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003984 return NULL;
3985 }
Christian Heimes44109d72013-11-22 01:51:30 +01003986 result = PyList_New(0);
3987 if (result == NULL) {
3988 return NULL;
3989 }
3990 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3991 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003992 Py_DECREF(result);
3993 return PyErr_SetFromWindowsErr(GetLastError());
3994 }
3995
Christian Heimes44109d72013-11-22 01:51:30 +01003996 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3997 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3998 pCertCtx->cbCertEncoded);
3999 if (!cert) {
4000 Py_CLEAR(result);
4001 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004002 }
Christian Heimes44109d72013-11-22 01:51:30 +01004003 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4004 Py_CLEAR(result);
4005 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004006 }
Christian Heimes44109d72013-11-22 01:51:30 +01004007 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4008 if (keyusage == Py_True) {
4009 Py_DECREF(keyusage);
4010 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004011 }
Christian Heimes44109d72013-11-22 01:51:30 +01004012 if (keyusage == NULL) {
4013 Py_CLEAR(result);
4014 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004015 }
Christian Heimes44109d72013-11-22 01:51:30 +01004016 if ((tup = PyTuple_New(3)) == NULL) {
4017 Py_CLEAR(result);
4018 break;
4019 }
4020 PyTuple_SET_ITEM(tup, 0, cert);
4021 cert = NULL;
4022 PyTuple_SET_ITEM(tup, 1, enc);
4023 enc = NULL;
4024 PyTuple_SET_ITEM(tup, 2, keyusage);
4025 keyusage = NULL;
4026 if (PyList_Append(result, tup) < 0) {
4027 Py_CLEAR(result);
4028 break;
4029 }
4030 Py_CLEAR(tup);
4031 }
4032 if (pCertCtx) {
4033 /* loop ended with an error, need to clean up context manually */
4034 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004035 }
4036
4037 /* In error cases cert, enc and tup may not be NULL */
4038 Py_XDECREF(cert);
4039 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004040 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004041 Py_XDECREF(tup);
4042
4043 if (!CertCloseStore(hStore, 0)) {
4044 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004045 Py_XDECREF(result);
4046 return PyErr_SetFromWindowsErr(GetLastError());
4047 }
4048 return result;
4049}
4050
4051PyDoc_STRVAR(PySSL_enum_crls_doc,
4052"enum_crls(store_name) -> []\n\
4053\n\
4054Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4055'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4056The function returns a list of (bytes, encoding_type) tuples. The\n\
4057encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4058PKCS_7_ASN_ENCODING.");
4059
4060static PyObject *
4061PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4062{
4063 char *kwlist[] = {"store_name", NULL};
4064 char *store_name;
4065 HCERTSTORE hStore = NULL;
4066 PCCRL_CONTEXT pCrlCtx = NULL;
4067 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4068 PyObject *result = NULL;
4069
4070 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4071 kwlist, &store_name)) {
4072 return NULL;
4073 }
4074 result = PyList_New(0);
4075 if (result == NULL) {
4076 return NULL;
4077 }
4078 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4079 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004080 Py_DECREF(result);
4081 return PyErr_SetFromWindowsErr(GetLastError());
4082 }
Christian Heimes44109d72013-11-22 01:51:30 +01004083
4084 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4085 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4086 pCrlCtx->cbCrlEncoded);
4087 if (!crl) {
4088 Py_CLEAR(result);
4089 break;
4090 }
4091 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4092 Py_CLEAR(result);
4093 break;
4094 }
4095 if ((tup = PyTuple_New(2)) == NULL) {
4096 Py_CLEAR(result);
4097 break;
4098 }
4099 PyTuple_SET_ITEM(tup, 0, crl);
4100 crl = NULL;
4101 PyTuple_SET_ITEM(tup, 1, enc);
4102 enc = NULL;
4103
4104 if (PyList_Append(result, tup) < 0) {
4105 Py_CLEAR(result);
4106 break;
4107 }
4108 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004109 }
Christian Heimes44109d72013-11-22 01:51:30 +01004110 if (pCrlCtx) {
4111 /* loop ended with an error, need to clean up context manually */
4112 CertFreeCRLContext(pCrlCtx);
4113 }
4114
4115 /* In error cases cert, enc and tup may not be NULL */
4116 Py_XDECREF(crl);
4117 Py_XDECREF(enc);
4118 Py_XDECREF(tup);
4119
4120 if (!CertCloseStore(hStore, 0)) {
4121 /* This error case might shadow another exception.*/
4122 Py_XDECREF(result);
4123 return PyErr_SetFromWindowsErr(GetLastError());
4124 }
4125 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004126}
Christian Heimes44109d72013-11-22 01:51:30 +01004127
4128#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004129
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004130/* List of functions exported by this module. */
4131
4132static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004133 {"_test_decode_cert", PySSL_test_decode_certificate,
4134 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004135#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004136 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4137 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004138 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4139 PySSL_RAND_bytes_doc},
4140 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4141 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004142#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004143 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004144 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004145#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004146 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4147 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02004148#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02004149 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004150 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004151#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004152 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4153 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4154 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4155 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004156#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004157 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4158 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4159 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4160 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004161 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004162};
4163
4164
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004165#ifdef WITH_THREAD
4166
4167/* an implementation of OpenSSL threading operations in terms
4168 of the Python C thread library */
4169
4170static PyThread_type_lock *_ssl_locks = NULL;
4171
Christian Heimes4d98ca92013-08-19 17:36:29 +02004172#if OPENSSL_VERSION_NUMBER >= 0x10000000
4173/* use new CRYPTO_THREADID API. */
4174static void
4175_ssl_threadid_callback(CRYPTO_THREADID *id)
4176{
4177 CRYPTO_THREADID_set_numeric(id,
4178 (unsigned long)PyThread_get_thread_ident());
4179}
4180#else
4181/* deprecated CRYPTO_set_id_callback() API. */
4182static unsigned long
4183_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004184 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004185}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004186#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004187
Bill Janssen6e027db2007-11-15 22:23:56 +00004188static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004189 (int mode, int n, const char *file, int line) {
4190 /* this function is needed to perform locking on shared data
4191 structures. (Note that OpenSSL uses a number of global data
4192 structures that will be implicitly shared whenever multiple
4193 threads use OpenSSL.) Multi-threaded applications will
4194 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004196 locking_function() must be able to handle up to
4197 CRYPTO_num_locks() different mutex locks. It sets the n-th
4198 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004200 file and line are the file number of the function setting the
4201 lock. They can be useful for debugging.
4202 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004204 if ((_ssl_locks == NULL) ||
4205 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4206 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004208 if (mode & CRYPTO_LOCK) {
4209 PyThread_acquire_lock(_ssl_locks[n], 1);
4210 } else {
4211 PyThread_release_lock(_ssl_locks[n]);
4212 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004213}
4214
4215static int _setup_ssl_threads(void) {
4216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004217 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004219 if (_ssl_locks == NULL) {
4220 _ssl_locks_count = CRYPTO_num_locks();
4221 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02004222 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004223 if (_ssl_locks == NULL)
4224 return 0;
4225 memset(_ssl_locks, 0,
4226 sizeof(PyThread_type_lock) * _ssl_locks_count);
4227 for (i = 0; i < _ssl_locks_count; i++) {
4228 _ssl_locks[i] = PyThread_allocate_lock();
4229 if (_ssl_locks[i] == NULL) {
4230 unsigned int j;
4231 for (j = 0; j < i; j++) {
4232 PyThread_free_lock(_ssl_locks[j]);
4233 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004234 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004235 return 0;
4236 }
4237 }
4238 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004239#if OPENSSL_VERSION_NUMBER >= 0x10000000
4240 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4241#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004242 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004243#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004244 }
4245 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246}
4247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004248#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004250PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004251"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004252for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004253
Martin v. Löwis1a214512008-06-11 05:26:20 +00004254
4255static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004256 PyModuleDef_HEAD_INIT,
4257 "_ssl",
4258 module_doc,
4259 -1,
4260 PySSL_methods,
4261 NULL,
4262 NULL,
4263 NULL,
4264 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004265};
4266
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004267
4268static void
4269parse_openssl_version(unsigned long libver,
4270 unsigned int *major, unsigned int *minor,
4271 unsigned int *fix, unsigned int *patch,
4272 unsigned int *status)
4273{
4274 *status = libver & 0xF;
4275 libver >>= 4;
4276 *patch = libver & 0xFF;
4277 libver >>= 8;
4278 *fix = libver & 0xFF;
4279 libver >>= 8;
4280 *minor = libver & 0xFF;
4281 libver >>= 8;
4282 *major = libver & 0xFF;
4283}
4284
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004285PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004286PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004287{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004288 PyObject *m, *d, *r;
4289 unsigned long libver;
4290 unsigned int major, minor, fix, patch, status;
4291 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004292 struct py_ssl_error_code *errcode;
4293 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004294
Antoine Pitrou152efa22010-05-16 18:19:27 +00004295 if (PyType_Ready(&PySSLContext_Type) < 0)
4296 return NULL;
4297 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004298 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004299 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4300 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004302 m = PyModule_Create(&_sslmodule);
4303 if (m == NULL)
4304 return NULL;
4305 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004306
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004307 /* Load _socket module and its C API */
4308 socket_api = PySocketModule_ImportModuleAndAPI();
4309 if (!socket_api)
4310 return NULL;
4311 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004313 /* Init OpenSSL */
4314 SSL_load_error_strings();
4315 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004316#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004317 /* note that this will start threading if not already started */
4318 if (!_setup_ssl_threads()) {
4319 return NULL;
4320 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004321#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004322 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004324 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004325 sslerror_type_slots[0].pfunc = PyExc_OSError;
4326 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004327 if (PySSLErrorObject == NULL)
4328 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004329
Antoine Pitrou41032a62011-10-27 23:56:55 +02004330 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4331 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4332 PySSLErrorObject, NULL);
4333 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4334 "ssl.SSLWantReadError", SSLWantReadError_doc,
4335 PySSLErrorObject, NULL);
4336 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4337 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4338 PySSLErrorObject, NULL);
4339 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4340 "ssl.SSLSyscallError", SSLSyscallError_doc,
4341 PySSLErrorObject, NULL);
4342 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4343 "ssl.SSLEOFError", SSLEOFError_doc,
4344 PySSLErrorObject, NULL);
4345 if (PySSLZeroReturnErrorObject == NULL
4346 || PySSLWantReadErrorObject == NULL
4347 || PySSLWantWriteErrorObject == NULL
4348 || PySSLSyscallErrorObject == NULL
4349 || PySSLEOFErrorObject == NULL)
4350 return NULL;
4351 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4352 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4353 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4354 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4355 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4356 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004357 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004358 if (PyDict_SetItemString(d, "_SSLContext",
4359 (PyObject *)&PySSLContext_Type) != 0)
4360 return NULL;
4361 if (PyDict_SetItemString(d, "_SSLSocket",
4362 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004363 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004364 if (PyDict_SetItemString(d, "MemoryBIO",
4365 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4366 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004367 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4368 PY_SSL_ERROR_ZERO_RETURN);
4369 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4370 PY_SSL_ERROR_WANT_READ);
4371 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4372 PY_SSL_ERROR_WANT_WRITE);
4373 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4374 PY_SSL_ERROR_WANT_X509_LOOKUP);
4375 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4376 PY_SSL_ERROR_SYSCALL);
4377 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4378 PY_SSL_ERROR_SSL);
4379 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4380 PY_SSL_ERROR_WANT_CONNECT);
4381 /* non ssl.h errorcodes */
4382 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4383 PY_SSL_ERROR_EOF);
4384 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4385 PY_SSL_ERROR_INVALID_ERROR_CODE);
4386 /* cert requirements */
4387 PyModule_AddIntConstant(m, "CERT_NONE",
4388 PY_SSL_CERT_NONE);
4389 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4390 PY_SSL_CERT_OPTIONAL);
4391 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4392 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004393 /* CRL verification for verification_flags */
4394 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4395 0);
4396 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4397 X509_V_FLAG_CRL_CHECK);
4398 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4399 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4400 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4401 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004402
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004403 /* Alert Descriptions from ssl.h */
4404 /* note RESERVED constants no longer intended for use have been removed */
4405 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4406
4407#define ADD_AD_CONSTANT(s) \
4408 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4409 SSL_AD_##s)
4410
4411 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4412 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4413 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4414 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4415 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4416 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4417 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4418 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4419 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4420 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4421 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4422 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4423 ADD_AD_CONSTANT(UNKNOWN_CA);
4424 ADD_AD_CONSTANT(ACCESS_DENIED);
4425 ADD_AD_CONSTANT(DECODE_ERROR);
4426 ADD_AD_CONSTANT(DECRYPT_ERROR);
4427 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4428 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4429 ADD_AD_CONSTANT(INTERNAL_ERROR);
4430 ADD_AD_CONSTANT(USER_CANCELLED);
4431 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004432 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004433#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4434 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4435#endif
4436#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4437 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4438#endif
4439#ifdef SSL_AD_UNRECOGNIZED_NAME
4440 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4441#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004442#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4443 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4444#endif
4445#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4446 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4447#endif
4448#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4449 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4450#endif
4451
4452#undef ADD_AD_CONSTANT
4453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004454 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004455#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004456 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4457 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004458#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004459#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004460 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4461 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004462#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004463 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4464 PY_SSL_VERSION_SSL23);
4465 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4466 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004467#if HAVE_TLSv1_2
4468 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4469 PY_SSL_VERSION_TLS1_1);
4470 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4471 PY_SSL_VERSION_TLS1_2);
4472#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004473
Antoine Pitroub5218772010-05-21 09:56:06 +00004474 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004475 PyModule_AddIntConstant(m, "OP_ALL",
4476 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004477 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4478 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4479 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004480#if HAVE_TLSv1_2
4481 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4482 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4483#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004484 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4485 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004486 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004487#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004488 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004489#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004490#ifdef SSL_OP_NO_COMPRESSION
4491 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4492 SSL_OP_NO_COMPRESSION);
4493#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004494
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004495#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004496 r = Py_True;
4497#else
4498 r = Py_False;
4499#endif
4500 Py_INCREF(r);
4501 PyModule_AddObject(m, "HAS_SNI", r);
4502
Antoine Pitroud6494802011-07-21 01:11:30 +02004503#if HAVE_OPENSSL_FINISHED
4504 r = Py_True;
4505#else
4506 r = Py_False;
4507#endif
4508 Py_INCREF(r);
4509 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4510
Antoine Pitrou501da612011-12-21 09:27:41 +01004511#ifdef OPENSSL_NO_ECDH
4512 r = Py_False;
4513#else
4514 r = Py_True;
4515#endif
4516 Py_INCREF(r);
4517 PyModule_AddObject(m, "HAS_ECDH", r);
4518
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004519#ifdef OPENSSL_NPN_NEGOTIATED
4520 r = Py_True;
4521#else
4522 r = Py_False;
4523#endif
4524 Py_INCREF(r);
4525 PyModule_AddObject(m, "HAS_NPN", r);
4526
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004527 /* Mappings for error codes */
4528 err_codes_to_names = PyDict_New();
4529 err_names_to_codes = PyDict_New();
4530 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4531 return NULL;
4532 errcode = error_codes;
4533 while (errcode->mnemonic != NULL) {
4534 PyObject *mnemo, *key;
4535 mnemo = PyUnicode_FromString(errcode->mnemonic);
4536 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4537 if (mnemo == NULL || key == NULL)
4538 return NULL;
4539 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4540 return NULL;
4541 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4542 return NULL;
4543 Py_DECREF(key);
4544 Py_DECREF(mnemo);
4545 errcode++;
4546 }
4547 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4548 return NULL;
4549 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4550 return NULL;
4551
4552 lib_codes_to_names = PyDict_New();
4553 if (lib_codes_to_names == NULL)
4554 return NULL;
4555 libcode = library_codes;
4556 while (libcode->library != NULL) {
4557 PyObject *mnemo, *key;
4558 key = PyLong_FromLong(libcode->code);
4559 mnemo = PyUnicode_FromString(libcode->library);
4560 if (key == NULL || mnemo == NULL)
4561 return NULL;
4562 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4563 return NULL;
4564 Py_DECREF(key);
4565 Py_DECREF(mnemo);
4566 libcode++;
4567 }
4568 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4569 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004571 /* OpenSSL version */
4572 /* SSLeay() gives us the version of the library linked against,
4573 which could be different from the headers version.
4574 */
4575 libver = SSLeay();
4576 r = PyLong_FromUnsignedLong(libver);
4577 if (r == NULL)
4578 return NULL;
4579 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4580 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004581 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004582 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4583 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4584 return NULL;
4585 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4586 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4587 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004588
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004589 libver = OPENSSL_VERSION_NUMBER;
4590 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4591 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4592 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4593 return NULL;
4594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004595 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004596}