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