blob: 1c04998ebc73c2d2fbe36671f69735f2d88db6b8 [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
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000165/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
166 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
167 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
168#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000169# define HAVE_SSL_CTX_CLEAR_OPTIONS
170#else
171# undef HAVE_SSL_CTX_CLEAR_OPTIONS
172#endif
173
Antoine Pitroud6494802011-07-21 01:11:30 +0200174/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
175 * older SSL, but let's be safe */
176#define PySSL_CB_MAXLEN 128
177
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100178
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000179typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000181 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100182#ifdef OPENSSL_NPN_NEGOTIATED
183 char *npn_protocols;
184 int npn_protocols_len;
185#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100186#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200187 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100188#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100189 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000190} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000191
Antoine Pitrou152efa22010-05-16 18:19:27 +0000192typedef struct {
193 PyObject_HEAD
194 PyObject *Socket; /* weakref to socket on which we're layered */
195 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100196 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200198 char shutdown_seen_zero;
199 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200200 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200201 PyObject *owner; /* Python level "owner" passed to servername callback */
202 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000203} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000204
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200205typedef struct {
206 PyObject_HEAD
207 BIO *bio;
208 int eof_written;
209} PySSLMemoryBIO;
210
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211static PyTypeObject PySSLContext_Type;
212static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200213static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214
215static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
216static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000217static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000218 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
220static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000221
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
223#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200224#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000226typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 SOCKET_IS_NONBLOCKING,
228 SOCKET_IS_BLOCKING,
229 SOCKET_HAS_TIMED_OUT,
230 SOCKET_HAS_BEEN_CLOSED,
231 SOCKET_TOO_LARGE_FOR_SELECT,
232 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000233} timeout_state;
234
Thomas Woutersed03b412007-08-28 21:37:11 +0000235/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000236#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200237#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000238
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200239/* Get the socket from a PySSLSocket, if it has one */
240#define GET_SOCKET(obj) ((obj)->Socket ? \
241 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200242
243/*
244 * SSL errors.
245 */
246
247PyDoc_STRVAR(SSLError_doc,
248"An error occurred in the SSL implementation.");
249
250PyDoc_STRVAR(SSLZeroReturnError_doc,
251"SSL/TLS session closed cleanly.");
252
253PyDoc_STRVAR(SSLWantReadError_doc,
254"Non-blocking SSL socket needs to read more data\n"
255"before the requested operation can be completed.");
256
257PyDoc_STRVAR(SSLWantWriteError_doc,
258"Non-blocking SSL socket needs to write more data\n"
259"before the requested operation can be completed.");
260
261PyDoc_STRVAR(SSLSyscallError_doc,
262"System error when attempting SSL operation.");
263
264PyDoc_STRVAR(SSLEOFError_doc,
265"SSL/TLS connection terminated abruptly.");
266
267static PyObject *
268SSLError_str(PyOSErrorObject *self)
269{
270 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
271 Py_INCREF(self->strerror);
272 return self->strerror;
273 }
274 else
275 return PyObject_Str(self->args);
276}
277
278static PyType_Slot sslerror_type_slots[] = {
279 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
280 {Py_tp_doc, SSLError_doc},
281 {Py_tp_str, SSLError_str},
282 {0, 0},
283};
284
285static PyType_Spec sslerror_type_spec = {
286 "ssl.SSLError",
287 sizeof(PyOSErrorObject),
288 0,
289 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
290 sslerror_type_slots
291};
292
293static void
294fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
295 int lineno, unsigned long errcode)
296{
297 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
298 PyObject *init_value, *msg, *key;
299 _Py_IDENTIFIER(reason);
300 _Py_IDENTIFIER(library);
301
302 if (errcode != 0) {
303 int lib, reason;
304
305 lib = ERR_GET_LIB(errcode);
306 reason = ERR_GET_REASON(errcode);
307 key = Py_BuildValue("ii", lib, reason);
308 if (key == NULL)
309 goto fail;
310 reason_obj = PyDict_GetItem(err_codes_to_names, key);
311 Py_DECREF(key);
312 if (reason_obj == NULL) {
313 /* XXX if reason < 100, it might reflect a library number (!!) */
314 PyErr_Clear();
315 }
316 key = PyLong_FromLong(lib);
317 if (key == NULL)
318 goto fail;
319 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
320 Py_DECREF(key);
321 if (lib_obj == NULL) {
322 PyErr_Clear();
323 }
324 if (errstr == NULL)
325 errstr = ERR_reason_error_string(errcode);
326 }
327 if (errstr == NULL)
328 errstr = "unknown error";
329
330 if (reason_obj && lib_obj)
331 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
332 lib_obj, reason_obj, errstr, lineno);
333 else if (lib_obj)
334 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
335 lib_obj, errstr, lineno);
336 else
337 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200338 if (msg == NULL)
339 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100340
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200341 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100342 if (init_value == NULL)
343 goto fail;
344
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200345 err_value = PyObject_CallObject(type, init_value);
346 Py_DECREF(init_value);
347 if (err_value == NULL)
348 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100349
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350 if (reason_obj == NULL)
351 reason_obj = Py_None;
352 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
353 goto fail;
354 if (lib_obj == NULL)
355 lib_obj = Py_None;
356 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
357 goto fail;
358 PyErr_SetObject(type, err_value);
359fail:
360 Py_XDECREF(err_value);
361}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362
363static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200366 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 int err;
369 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200370 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200373 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000375 if (obj->ssl != NULL) {
376 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000378 switch (err) {
379 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200380 errstr = "TLS/SSL connection has been closed (EOF)";
381 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 p = PY_SSL_ERROR_ZERO_RETURN;
383 break;
384 case SSL_ERROR_WANT_READ:
385 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200386 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 p = PY_SSL_ERROR_WANT_READ;
388 break;
389 case SSL_ERROR_WANT_WRITE:
390 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200391 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 errstr = "The operation did not complete (write)";
393 break;
394 case SSL_ERROR_WANT_X509_LOOKUP:
395 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000396 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 break;
398 case SSL_ERROR_WANT_CONNECT:
399 p = PY_SSL_ERROR_WANT_CONNECT;
400 errstr = "The operation did not complete (connect)";
401 break;
402 case SSL_ERROR_SYSCALL:
403 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200405 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000407 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200408 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000409 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200410 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000411 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000412 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000413 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200414 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000415 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200416 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000418 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200419 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000420 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 }
422 } else {
423 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 }
425 break;
426 }
427 case SSL_ERROR_SSL:
428 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 if (e == 0)
431 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 break;
434 }
435 default:
436 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
437 errstr = "Invalid error code";
438 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200440 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000441 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443}
444
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445static PyObject *
446_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
447
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200450 else
451 errcode = 0;
452 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000453 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455}
456
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457/*
458 * SSL objects
459 */
460
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100462newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000463 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200464 char *server_hostname,
465 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000466{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000467 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100468 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200469 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200470 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000471
Antoine Pitrou152efa22010-05-16 18:19:27 +0000472 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000473 if (self == NULL)
474 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 self->peer_cert = NULL;
477 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200480 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200481 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200482 self->owner = NULL;
483 if (server_hostname != NULL) {
484 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
485 "idna", "strict");
486 if (hostname == NULL) {
487 Py_DECREF(self);
488 return NULL;
489 }
490 self->server_hostname = hostname;
491 } else
492 self->server_hostname = NULL;
493
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100494 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 /* Make sure the SSL error state is initialized */
497 (void) ERR_get_state();
498 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200503 SSL_set_app_data(self->ssl, self);
504 if (sock) {
505 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
506 } else {
507 /* BIOs are reference counted and SSL_set_bio borrows our reference.
508 * To prevent a double free in memory_bio_dealloc() we need to take an
509 * extra reference here. */
510 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
511 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
512 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
513 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200514 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000515#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200516 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000517#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200518 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000519
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100520#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000521 if (server_hostname != NULL)
522 SSL_set_tlsext_host_name(self->ssl, server_hostname);
523#endif
524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 /* If the socket is in non-blocking mode or timeout mode, set the BIO
526 * to non-blocking mode (blocking is the default)
527 */
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200528 if (sock && sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
530 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
531 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 PySSL_BEGIN_ALLOW_THREADS
534 if (socket_type == PY_SSL_CLIENT)
535 SSL_set_connect_state(self->ssl);
536 else
537 SSL_set_accept_state(self->ssl);
538 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000539
Antoine Pitroud6494802011-07-21 01:11:30 +0200540 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200541 if (sock != NULL) {
542 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
543 if (self->Socket == NULL) {
544 Py_DECREF(self);
545 Py_XDECREF(self->server_hostname);
546 return NULL;
547 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100548 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000550}
551
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000552/* SSL object methods */
553
Antoine Pitrou152efa22010-05-16 18:19:27 +0000554static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000555{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 int ret;
557 int err;
558 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200559 PySocketSockObject *sock = GET_SOCKET(self);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000560
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200561 if (sock) {
562 if (((PyObject*)sock) == Py_None) {
563 _setSSLError("Underlying socket connection gone",
564 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
565 return NULL;
566 }
567 Py_INCREF(sock);
568
569 /* just in case the blocking state of the socket has been changed */
570 nonblocking = (sock->sock_timeout >= 0.0);
571 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
572 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 /* Actually negotiate SSL connection */
576 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000578 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 ret = SSL_do_handshake(self->ssl);
580 err = SSL_get_error(self->ssl, ret);
581 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000582 if (PyErr_CheckSignals())
583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 if (err == SSL_ERROR_WANT_READ) {
585 sockstate = check_socket_and_wait_for_timeout(sock, 0);
586 } else if (err == SSL_ERROR_WANT_WRITE) {
587 sockstate = check_socket_and_wait_for_timeout(sock, 1);
588 } else {
589 sockstate = SOCKET_OPERATION_OK;
590 }
591 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000592 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000593 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000594 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
596 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000597 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000598 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
600 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000601 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000602 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
604 break;
605 }
606 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200607 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 if (ret < 1)
609 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 if (self->peer_cert)
612 X509_free (self->peer_cert);
613 PySSL_BEGIN_ALLOW_THREADS
614 self->peer_cert = SSL_get_peer_certificate(self->ssl);
615 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200616 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617
618 Py_INCREF(Py_None);
619 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000620
621error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200622 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000623 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000624}
625
Thomas Woutersed03b412007-08-28 21:37:11 +0000626static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 char namebuf[X509_NAME_MAXLEN];
630 int buflen;
631 PyObject *name_obj;
632 PyObject *value_obj;
633 PyObject *attr;
634 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
637 if (buflen < 0) {
638 _setSSLError(NULL, 0, __FILE__, __LINE__);
639 goto fail;
640 }
641 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
642 if (name_obj == NULL)
643 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
646 if (buflen < 0) {
647 _setSSLError(NULL, 0, __FILE__, __LINE__);
648 Py_DECREF(name_obj);
649 goto fail;
650 }
651 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000652 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 OPENSSL_free(valuebuf);
654 if (value_obj == NULL) {
655 Py_DECREF(name_obj);
656 goto fail;
657 }
658 attr = PyTuple_New(2);
659 if (attr == NULL) {
660 Py_DECREF(name_obj);
661 Py_DECREF(value_obj);
662 goto fail;
663 }
664 PyTuple_SET_ITEM(attr, 0, name_obj);
665 PyTuple_SET_ITEM(attr, 1, value_obj);
666 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000667
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000669 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000670}
671
672static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000674{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
676 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
677 PyObject *rdnt;
678 PyObject *attr = NULL; /* tuple to hold an attribute */
679 int entry_count = X509_NAME_entry_count(xname);
680 X509_NAME_ENTRY *entry;
681 ASN1_OBJECT *name;
682 ASN1_STRING *value;
683 int index_counter;
684 int rdn_level = -1;
685 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 dn = PyList_New(0);
688 if (dn == NULL)
689 return NULL;
690 /* now create another tuple to hold the top-level RDN */
691 rdn = PyList_New(0);
692 if (rdn == NULL)
693 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000695 for (index_counter = 0;
696 index_counter < entry_count;
697 index_counter++)
698 {
699 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 /* check to see if we've gotten to a new RDN */
702 if (rdn_level >= 0) {
703 if (rdn_level != entry->set) {
704 /* yes, new RDN */
705 /* add old RDN to DN */
706 rdnt = PyList_AsTuple(rdn);
707 Py_DECREF(rdn);
708 if (rdnt == NULL)
709 goto fail0;
710 retcode = PyList_Append(dn, rdnt);
711 Py_DECREF(rdnt);
712 if (retcode < 0)
713 goto fail0;
714 /* create new RDN */
715 rdn = PyList_New(0);
716 if (rdn == NULL)
717 goto fail0;
718 }
719 }
720 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 /* now add this attribute to the current RDN */
723 name = X509_NAME_ENTRY_get_object(entry);
724 value = X509_NAME_ENTRY_get_data(entry);
725 attr = _create_tuple_for_attribute(name, value);
726 /*
727 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
728 entry->set,
729 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
730 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
731 */
732 if (attr == NULL)
733 goto fail1;
734 retcode = PyList_Append(rdn, attr);
735 Py_DECREF(attr);
736 if (retcode < 0)
737 goto fail1;
738 }
739 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100740 if (rdn != NULL) {
741 if (PyList_GET_SIZE(rdn) > 0) {
742 rdnt = PyList_AsTuple(rdn);
743 Py_DECREF(rdn);
744 if (rdnt == NULL)
745 goto fail0;
746 retcode = PyList_Append(dn, rdnt);
747 Py_DECREF(rdnt);
748 if (retcode < 0)
749 goto fail0;
750 }
751 else {
752 Py_DECREF(rdn);
753 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 /* convert list to tuple */
757 rdnt = PyList_AsTuple(dn);
758 Py_DECREF(dn);
759 if (rdnt == NULL)
760 return NULL;
761 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762
763 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
766 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 Py_XDECREF(dn);
768 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769}
770
771static PyObject *
772_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 /* this code follows the procedure outlined in
775 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
776 function to extract the STACK_OF(GENERAL_NAME),
777 then iterates through the stack to add the
778 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 int i, j;
781 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200782 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 X509_EXTENSION *ext = NULL;
784 GENERAL_NAMES *names = NULL;
785 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000786 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 BIO *biobuf = NULL;
788 char buf[2048];
789 char *vptr;
790 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 if (certificate == NULL)
794 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 /* get a memory buffer */
797 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200799 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 while ((i = X509_get_ext_by_NID(
801 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 if (peer_alt_names == Py_None) {
804 peer_alt_names = PyList_New(0);
805 if (peer_alt_names == NULL)
806 goto fail;
807 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 /* now decode the altName */
810 ext = X509_get_ext(certificate, i);
811 if(!(method = X509V3_EXT_get(ext))) {
812 PyErr_SetString
813 (PySSLErrorObject,
814 ERRSTR("No method for internalizing subjectAltName!"));
815 goto fail;
816 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 p = ext->value->data;
819 if (method->it)
820 names = (GENERAL_NAMES*)
821 (ASN1_item_d2i(NULL,
822 &p,
823 ext->value->length,
824 ASN1_ITEM_ptr(method->it)));
825 else
826 names = (GENERAL_NAMES*)
827 (method->d2i(NULL,
828 &p,
829 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200833 int gntype;
834 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200837 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200838 switch (gntype) {
839 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 /* we special-case DirName as a tuple of
841 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 t = PyTuple_New(2);
844 if (t == NULL) {
845 goto fail;
846 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 v = PyUnicode_FromString("DirName");
849 if (v == NULL) {
850 Py_DECREF(t);
851 goto fail;
852 }
853 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 v = _create_tuple_for_X509_NAME (name->d.dirn);
856 if (v == NULL) {
857 Py_DECREF(t);
858 goto fail;
859 }
860 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200861 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000862
Christian Heimes824f7f32013-08-17 00:54:47 +0200863 case GEN_EMAIL:
864 case GEN_DNS:
865 case GEN_URI:
866 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
867 correctly, CVE-2013-4238 */
868 t = PyTuple_New(2);
869 if (t == NULL)
870 goto fail;
871 switch (gntype) {
872 case GEN_EMAIL:
873 v = PyUnicode_FromString("email");
874 as = name->d.rfc822Name;
875 break;
876 case GEN_DNS:
877 v = PyUnicode_FromString("DNS");
878 as = name->d.dNSName;
879 break;
880 case GEN_URI:
881 v = PyUnicode_FromString("URI");
882 as = name->d.uniformResourceIdentifier;
883 break;
884 }
885 if (v == NULL) {
886 Py_DECREF(t);
887 goto fail;
888 }
889 PyTuple_SET_ITEM(t, 0, v);
890 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
891 ASN1_STRING_length(as));
892 if (v == NULL) {
893 Py_DECREF(t);
894 goto fail;
895 }
896 PyTuple_SET_ITEM(t, 1, v);
897 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898
Christian Heimes824f7f32013-08-17 00:54:47 +0200899 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200901 switch (gntype) {
902 /* check for new general name type */
903 case GEN_OTHERNAME:
904 case GEN_X400:
905 case GEN_EDIPARTY:
906 case GEN_IPADD:
907 case GEN_RID:
908 break;
909 default:
910 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
911 "Unknown general name type %d",
912 gntype) == -1) {
913 goto fail;
914 }
915 break;
916 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 (void) BIO_reset(biobuf);
918 GENERAL_NAME_print(biobuf, name);
919 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
920 if (len < 0) {
921 _setSSLError(NULL, 0, __FILE__, __LINE__);
922 goto fail;
923 }
924 vptr = strchr(buf, ':');
925 if (vptr == NULL)
926 goto fail;
927 t = PyTuple_New(2);
928 if (t == NULL)
929 goto fail;
930 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
931 if (v == NULL) {
932 Py_DECREF(t);
933 goto fail;
934 }
935 PyTuple_SET_ITEM(t, 0, v);
936 v = PyUnicode_FromStringAndSize((vptr + 1),
937 (len - (vptr - buf + 1)));
938 if (v == NULL) {
939 Py_DECREF(t);
940 goto fail;
941 }
942 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200943 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 if (PyList_Append(peer_alt_names, t) < 0) {
949 Py_DECREF(t);
950 goto fail;
951 }
952 Py_DECREF(t);
953 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100954 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 }
956 BIO_free(biobuf);
957 if (peer_alt_names != Py_None) {
958 v = PyList_AsTuple(peer_alt_names);
959 Py_DECREF(peer_alt_names);
960 return v;
961 } else {
962 return peer_alt_names;
963 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000964
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
966 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 if (biobuf != NULL)
968 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 if (peer_alt_names != Py_None) {
971 Py_XDECREF(peer_alt_names);
972 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975}
976
977static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100978_get_aia_uri(X509 *certificate, int nid) {
979 PyObject *lst = NULL, *ostr = NULL;
980 int i, result;
981 AUTHORITY_INFO_ACCESS *info;
982
983 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
984 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
985 return Py_None;
986 }
987
988 if ((lst = PyList_New(0)) == NULL) {
989 goto fail;
990 }
991
992 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
993 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
994 ASN1_IA5STRING *uri;
995
996 if ((OBJ_obj2nid(ad->method) != nid) ||
997 (ad->location->type != GEN_URI)) {
998 continue;
999 }
1000 uri = ad->location->d.uniformResourceIdentifier;
1001 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1002 uri->length);
1003 if (ostr == NULL) {
1004 goto fail;
1005 }
1006 result = PyList_Append(lst, ostr);
1007 Py_DECREF(ostr);
1008 if (result < 0) {
1009 goto fail;
1010 }
1011 }
1012 AUTHORITY_INFO_ACCESS_free(info);
1013
1014 /* convert to tuple or None */
1015 if (PyList_Size(lst) == 0) {
1016 Py_DECREF(lst);
1017 return Py_None;
1018 } else {
1019 PyObject *tup;
1020 tup = PyList_AsTuple(lst);
1021 Py_DECREF(lst);
1022 return tup;
1023 }
1024
1025 fail:
1026 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001027 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001028 return NULL;
1029}
1030
1031static PyObject *
1032_get_crl_dp(X509 *certificate) {
1033 STACK_OF(DIST_POINT) *dps;
1034 int i, j, result;
1035 PyObject *lst;
1036
Christian Heimes949ec142013-11-21 16:26:51 +01001037#if OPENSSL_VERSION_NUMBER < 0x10001000L
1038 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1039 NULL, NULL);
1040#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001041 /* Calls x509v3_cache_extensions and sets up crldp */
1042 X509_check_ca(certificate);
1043 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001044#endif
1045
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001046 if (dps == NULL) {
1047 return Py_None;
1048 }
1049
1050 if ((lst = PyList_New(0)) == NULL) {
1051 return NULL;
1052 }
1053
1054 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1055 DIST_POINT *dp;
1056 STACK_OF(GENERAL_NAME) *gns;
1057
1058 dp = sk_DIST_POINT_value(dps, i);
1059 gns = dp->distpoint->name.fullname;
1060
1061 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1062 GENERAL_NAME *gn;
1063 ASN1_IA5STRING *uri;
1064 PyObject *ouri;
1065
1066 gn = sk_GENERAL_NAME_value(gns, j);
1067 if (gn->type != GEN_URI) {
1068 continue;
1069 }
1070 uri = gn->d.uniformResourceIdentifier;
1071 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1072 uri->length);
1073 if (ouri == NULL) {
1074 Py_DECREF(lst);
1075 return NULL;
1076 }
1077 result = PyList_Append(lst, ouri);
1078 Py_DECREF(ouri);
1079 if (result < 0) {
1080 Py_DECREF(lst);
1081 return NULL;
1082 }
1083 }
1084 }
1085 /* convert to tuple or None */
1086 if (PyList_Size(lst) == 0) {
1087 Py_DECREF(lst);
1088 return Py_None;
1089 } else {
1090 PyObject *tup;
1091 tup = PyList_AsTuple(lst);
1092 Py_DECREF(lst);
1093 return tup;
1094 }
1095}
1096
1097static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001098_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 PyObject *retval = NULL;
1101 BIO *biobuf = NULL;
1102 PyObject *peer;
1103 PyObject *peer_alt_names = NULL;
1104 PyObject *issuer;
1105 PyObject *version;
1106 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001107 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 ASN1_INTEGER *serialNumber;
1109 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001110 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 ASN1_TIME *notBefore, *notAfter;
1112 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 retval = PyDict_New();
1115 if (retval == NULL)
1116 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 peer = _create_tuple_for_X509_NAME(
1119 X509_get_subject_name(certificate));
1120 if (peer == NULL)
1121 goto fail0;
1122 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1123 Py_DECREF(peer);
1124 goto fail0;
1125 }
1126 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001127
Antoine Pitroufb046912010-11-09 20:21:19 +00001128 issuer = _create_tuple_for_X509_NAME(
1129 X509_get_issuer_name(certificate));
1130 if (issuer == NULL)
1131 goto fail0;
1132 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001134 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001136 Py_DECREF(issuer);
1137
1138 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001139 if (version == NULL)
1140 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001141 if (PyDict_SetItemString(retval, "version", version) < 0) {
1142 Py_DECREF(version);
1143 goto fail0;
1144 }
1145 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 /* get a memory buffer */
1148 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001149
Antoine Pitroufb046912010-11-09 20:21:19 +00001150 (void) BIO_reset(biobuf);
1151 serialNumber = X509_get_serialNumber(certificate);
1152 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1153 i2a_ASN1_INTEGER(biobuf, serialNumber);
1154 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1155 if (len < 0) {
1156 _setSSLError(NULL, 0, __FILE__, __LINE__);
1157 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001159 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1160 if (sn_obj == NULL)
1161 goto fail1;
1162 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1163 Py_DECREF(sn_obj);
1164 goto fail1;
1165 }
1166 Py_DECREF(sn_obj);
1167
1168 (void) BIO_reset(biobuf);
1169 notBefore = X509_get_notBefore(certificate);
1170 ASN1_TIME_print(biobuf, notBefore);
1171 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1172 if (len < 0) {
1173 _setSSLError(NULL, 0, __FILE__, __LINE__);
1174 goto fail1;
1175 }
1176 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1177 if (pnotBefore == NULL)
1178 goto fail1;
1179 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1180 Py_DECREF(pnotBefore);
1181 goto fail1;
1182 }
1183 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 (void) BIO_reset(biobuf);
1186 notAfter = X509_get_notAfter(certificate);
1187 ASN1_TIME_print(biobuf, notAfter);
1188 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1189 if (len < 0) {
1190 _setSSLError(NULL, 0, __FILE__, __LINE__);
1191 goto fail1;
1192 }
1193 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1194 if (pnotAfter == NULL)
1195 goto fail1;
1196 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1197 Py_DECREF(pnotAfter);
1198 goto fail1;
1199 }
1200 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 peer_alt_names = _get_peer_alt_names(certificate);
1205 if (peer_alt_names == NULL)
1206 goto fail1;
1207 else if (peer_alt_names != Py_None) {
1208 if (PyDict_SetItemString(retval, "subjectAltName",
1209 peer_alt_names) < 0) {
1210 Py_DECREF(peer_alt_names);
1211 goto fail1;
1212 }
1213 Py_DECREF(peer_alt_names);
1214 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001215
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001216 /* Authority Information Access: OCSP URIs */
1217 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1218 if (obj == NULL) {
1219 goto fail1;
1220 } else if (obj != Py_None) {
1221 result = PyDict_SetItemString(retval, "OCSP", obj);
1222 Py_DECREF(obj);
1223 if (result < 0) {
1224 goto fail1;
1225 }
1226 }
1227
1228 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1229 if (obj == NULL) {
1230 goto fail1;
1231 } else if (obj != Py_None) {
1232 result = PyDict_SetItemString(retval, "caIssuers", obj);
1233 Py_DECREF(obj);
1234 if (result < 0) {
1235 goto fail1;
1236 }
1237 }
1238
1239 /* CDP (CRL distribution points) */
1240 obj = _get_crl_dp(certificate);
1241 if (obj == NULL) {
1242 goto fail1;
1243 } else if (obj != Py_None) {
1244 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1245 Py_DECREF(obj);
1246 if (result < 0) {
1247 goto fail1;
1248 }
1249 }
1250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 BIO_free(biobuf);
1252 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001253
1254 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 if (biobuf != NULL)
1256 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001257 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 Py_XDECREF(retval);
1259 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001260}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001261
Christian Heimes9a5395a2013-06-17 15:44:12 +02001262static PyObject *
1263_certificate_to_der(X509 *certificate)
1264{
1265 unsigned char *bytes_buf = NULL;
1266 int len;
1267 PyObject *retval;
1268
1269 bytes_buf = NULL;
1270 len = i2d_X509(certificate, &bytes_buf);
1271 if (len < 0) {
1272 _setSSLError(NULL, 0, __FILE__, __LINE__);
1273 return NULL;
1274 }
1275 /* this is actually an immutable bytes sequence */
1276 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1277 OPENSSL_free(bytes_buf);
1278 return retval;
1279}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001280
1281static PyObject *
1282PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001285 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 X509 *x=NULL;
1287 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288
Antoine Pitroufb046912010-11-09 20:21:19 +00001289 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1290 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1294 PyErr_SetString(PySSLErrorObject,
1295 "Can't malloc memory to read file");
1296 goto fail0;
1297 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298
Victor Stinner3800e1e2010-05-16 21:23:48 +00001299 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 PyErr_SetString(PySSLErrorObject,
1301 "Can't open file");
1302 goto fail0;
1303 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1306 if (x == NULL) {
1307 PyErr_SetString(PySSLErrorObject,
1308 "Error decoding PEM-encoded file");
1309 goto fail0;
1310 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroufb046912010-11-09 20:21:19 +00001312 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001313 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
1315 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001316 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 if (cert != NULL) BIO_free(cert);
1318 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319}
1320
1321
1322static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001323PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001326 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327
Antoine Pitrou721738f2012-08-15 23:20:39 +02001328 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Antoine Pitrou20b85552013-09-29 19:50:53 +02001331 if (!self->handshake_done) {
1332 PyErr_SetString(PyExc_ValueError,
1333 "handshake not done yet");
1334 return NULL;
1335 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 if (!self->peer_cert)
1337 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338
Antoine Pitrou721738f2012-08-15 23:20:39 +02001339 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001341 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001343 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 if ((verification & SSL_VERIFY_PEER) == 0)
1345 return PyDict_New();
1346 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001347 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001349}
1350
1351PyDoc_STRVAR(PySSL_peercert_doc,
1352"peer_certificate([der=False]) -> certificate\n\
1353\n\
1354Returns the certificate for the peer. If no certificate was provided,\n\
1355returns None. If a certificate was provided, but not validated, returns\n\
1356an empty dictionary. Otherwise returns a dict containing information\n\
1357about the peer certificate.\n\
1358\n\
1359If the optional argument is True, returns a DER-encoded copy of the\n\
1360peer certificate, or None if no certificate was provided. This will\n\
1361return the certificate even if it wasn't validated.");
1362
Antoine Pitrou152efa22010-05-16 18:19:27 +00001363static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001366 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 char *cipher_name;
1368 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001371 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 current = SSL_get_current_cipher(self->ssl);
1373 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001374 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 retval = PyTuple_New(3);
1377 if (retval == NULL)
1378 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 cipher_name = (char *) SSL_CIPHER_get_name(current);
1381 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001382 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 PyTuple_SET_ITEM(retval, 0, Py_None);
1384 } else {
1385 v = PyUnicode_FromString(cipher_name);
1386 if (v == NULL)
1387 goto fail0;
1388 PyTuple_SET_ITEM(retval, 0, v);
1389 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001390 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001392 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 PyTuple_SET_ITEM(retval, 1, Py_None);
1394 } else {
1395 v = PyUnicode_FromString(cipher_protocol);
1396 if (v == NULL)
1397 goto fail0;
1398 PyTuple_SET_ITEM(retval, 1, v);
1399 }
1400 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1401 if (v == NULL)
1402 goto fail0;
1403 PyTuple_SET_ITEM(retval, 2, v);
1404 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001405
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 Py_DECREF(retval);
1408 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409}
1410
Antoine Pitrou47e40422014-09-04 21:00:10 +02001411static PyObject *PySSL_version(PySSLSocket *self)
1412{
1413 const char *version;
1414
1415 if (self->ssl == NULL)
1416 Py_RETURN_NONE;
1417 version = SSL_get_version(self->ssl);
1418 if (!strcmp(version, "unknown"))
1419 Py_RETURN_NONE;
1420 return PyUnicode_FromString(version);
1421}
1422
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001423#ifdef OPENSSL_NPN_NEGOTIATED
1424static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1425 const unsigned char *out;
1426 unsigned int outlen;
1427
Victor Stinner4569cd52013-06-23 14:58:43 +02001428 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001429 &out, &outlen);
1430
1431 if (out == NULL)
1432 Py_RETURN_NONE;
1433 return PyUnicode_FromStringAndSize((char *) out, outlen);
1434}
1435#endif
1436
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001437static PyObject *PySSL_compression(PySSLSocket *self) {
1438#ifdef OPENSSL_NO_COMP
1439 Py_RETURN_NONE;
1440#else
1441 const COMP_METHOD *comp_method;
1442 const char *short_name;
1443
1444 if (self->ssl == NULL)
1445 Py_RETURN_NONE;
1446 comp_method = SSL_get_current_compression(self->ssl);
1447 if (comp_method == NULL || comp_method->type == NID_undef)
1448 Py_RETURN_NONE;
1449 short_name = OBJ_nid2sn(comp_method->type);
1450 if (short_name == NULL)
1451 Py_RETURN_NONE;
1452 return PyUnicode_DecodeFSDefault(short_name);
1453#endif
1454}
1455
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001456static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1457 Py_INCREF(self->ctx);
1458 return self->ctx;
1459}
1460
1461static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1462 void *closure) {
1463
1464 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001465#if !HAVE_SNI
1466 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1467 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001468 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001469#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001470 Py_INCREF(value);
1471 Py_DECREF(self->ctx);
1472 self->ctx = (PySSLContext *) value;
1473 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001474#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001475 } else {
1476 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1477 return -1;
1478 }
1479
1480 return 0;
1481}
1482
1483PyDoc_STRVAR(PySSL_set_context_doc,
1484"_setter_context(ctx)\n\
1485\
1486This changes the context associated with the SSLSocket. This is typically\n\
1487used from within a callback function set by the set_servername_callback\n\
1488on the SSLContext to change the certificate information associated with the\n\
1489SSLSocket before the cryptographic exchange handshake messages\n");
1490
1491
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001492static PyObject *
1493PySSL_get_server_side(PySSLSocket *self, void *c)
1494{
1495 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1496}
1497
1498PyDoc_STRVAR(PySSL_get_server_side_doc,
1499"Whether this is a server-side socket.");
1500
1501static PyObject *
1502PySSL_get_server_hostname(PySSLSocket *self, void *c)
1503{
1504 if (self->server_hostname == NULL)
1505 Py_RETURN_NONE;
1506 Py_INCREF(self->server_hostname);
1507 return self->server_hostname;
1508}
1509
1510PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1511"The currently set server hostname (for SNI).");
1512
1513static PyObject *
1514PySSL_get_owner(PySSLSocket *self, void *c)
1515{
1516 PyObject *owner;
1517
1518 if (self->owner == NULL)
1519 Py_RETURN_NONE;
1520
1521 owner = PyWeakref_GetObject(self->owner);
1522 Py_INCREF(owner);
1523 return owner;
1524}
1525
1526static int
1527PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1528{
1529 Py_XDECREF(self->owner);
1530 self->owner = PyWeakref_NewRef(value, NULL);
1531 if (self->owner == NULL)
1532 return -1;
1533 return 0;
1534}
1535
1536PyDoc_STRVAR(PySSL_get_owner_doc,
1537"The Python-level owner of this object.\
1538Passed as \"self\" in servername callback.");
1539
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001540
Antoine Pitrou152efa22010-05-16 18:19:27 +00001541static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001542{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 if (self->peer_cert) /* Possible not to have one? */
1544 X509_free (self->peer_cert);
1545 if (self->ssl)
1546 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001548 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001549 Py_XDECREF(self->server_hostname);
1550 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001552}
1553
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001554/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001555 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001556 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001557 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001558
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001559static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001560check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001561{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 fd_set fds;
1563 struct timeval tv;
1564 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001567 if ((s == NULL) || (s->sock_timeout == 0.0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 return SOCKET_IS_NONBLOCKING;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001569 else if (s->sock_timeout < 0.0)
1570 return SOCKET_IS_BLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 /* Guard against closed socket */
1573 if (s->sock_fd < 0)
1574 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 /* Prefer poll, if available, since you can poll() any fd
1577 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001578#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 {
1580 struct pollfd pollfd;
1581 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001583 pollfd.fd = s->sock_fd;
1584 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 /* s->sock_timeout is in seconds, timeout in ms */
1587 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1588 PySSL_BEGIN_ALLOW_THREADS
1589 rc = poll(&pollfd, 1, timeout);
1590 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 goto normal_return;
1593 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001594#endif
1595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001596 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001597 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 /* Construct the arguments to select */
1601 tv.tv_sec = (int)s->sock_timeout;
1602 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1603 FD_ZERO(&fds);
1604 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 /* See if the socket is ready */
1607 PySSL_BEGIN_ALLOW_THREADS
1608 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001609 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1610 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001612 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1613 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001615
Bill Janssen6e027db2007-11-15 22:23:56 +00001616#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001617normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001618#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1620 (when we are able to write or when there's something to read) */
1621 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001622}
1623
Antoine Pitrou152efa22010-05-16 18:19:27 +00001624static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001625{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 Py_buffer buf;
1627 int len;
1628 int sockstate;
1629 int err;
1630 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001631 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001632
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001633 if (sock != NULL) {
1634 if (((PyObject*)sock) == Py_None) {
1635 _setSSLError("Underlying socket connection gone",
1636 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1637 return NULL;
1638 }
1639 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 }
1641
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001642 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001643 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001645 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646
Victor Stinner6efa9652013-06-25 00:42:31 +02001647 if (buf.len > INT_MAX) {
1648 PyErr_Format(PyExc_OverflowError,
1649 "string longer than %d bytes", INT_MAX);
1650 goto error;
1651 }
1652
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001653 if (sock != NULL) {
1654 /* just in case the blocking state of the socket has been changed */
1655 nonblocking = (sock->sock_timeout >= 0.0);
1656 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1657 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1658 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659
1660 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1661 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001662 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 "The write operation timed out");
1664 goto error;
1665 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1666 PyErr_SetString(PySSLErrorObject,
1667 "Underlying socket has been closed.");
1668 goto error;
1669 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1670 PyErr_SetString(PySSLErrorObject,
1671 "Underlying socket too large for select().");
1672 goto error;
1673 }
1674 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001676 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 err = SSL_get_error(self->ssl, len);
1678 PySSL_END_ALLOW_THREADS
1679 if (PyErr_CheckSignals()) {
1680 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001681 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001683 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001685 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686 } else {
1687 sockstate = SOCKET_OPERATION_OK;
1688 }
1689 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001690 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 "The write operation timed out");
1692 goto error;
1693 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1694 PyErr_SetString(PySSLErrorObject,
1695 "Underlying socket has been closed.");
1696 goto error;
1697 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1698 break;
1699 }
1700 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001701
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001702 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 PyBuffer_Release(&buf);
1704 if (len > 0)
1705 return PyLong_FromLong(len);
1706 else
1707 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001708
1709error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001710 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 PyBuffer_Release(&buf);
1712 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001713}
1714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001715PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001716"write(s) -> len\n\
1717\n\
1718Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001719of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001720
Antoine Pitrou152efa22010-05-16 18:19:27 +00001721static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001722{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 PySSL_BEGIN_ALLOW_THREADS
1726 count = SSL_pending(self->ssl);
1727 PySSL_END_ALLOW_THREADS
1728 if (count < 0)
1729 return PySSL_SetError(self, count, __FILE__, __LINE__);
1730 else
1731 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001732}
1733
1734PyDoc_STRVAR(PySSL_SSLpending_doc,
1735"pending() -> count\n\
1736\n\
1737Returns the number of already decrypted bytes available for read,\n\
1738pending on the connection.\n");
1739
Antoine Pitrou152efa22010-05-16 18:19:27 +00001740static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001741{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 PyObject *dest = NULL;
1743 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001744 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001745 int len, count;
1746 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 int sockstate;
1748 int err;
1749 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001750 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001751
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001752 if (sock != NULL) {
1753 if (((PyObject*)sock) == Py_None) {
1754 _setSSLError("Underlying socket connection gone",
1755 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1756 return NULL;
1757 }
1758 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 }
1760
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001761 buf.obj = NULL;
1762 buf.buf = NULL;
1763 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001764 goto error;
1765
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001766 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1767 dest = PyBytes_FromStringAndSize(NULL, len);
1768 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001769 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001770 mem = PyBytes_AS_STRING(dest);
1771 }
1772 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001773 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001774 mem = buf.buf;
1775 if (len <= 0 || len > buf.len) {
1776 len = (int) buf.len;
1777 if (buf.len != len) {
1778 PyErr_SetString(PyExc_OverflowError,
1779 "maximum length can't fit in a C 'int'");
1780 goto error;
1781 }
1782 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 }
1784
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001785 if (sock != NULL) {
1786 /* just in case the blocking state of the socket has been changed */
1787 nonblocking = (sock->sock_timeout >= 0.0);
1788 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1789 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1790 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791
1792 /* first check if there are bytes ready to be read */
1793 PySSL_BEGIN_ALLOW_THREADS
1794 count = SSL_pending(self->ssl);
1795 PySSL_END_ALLOW_THREADS
1796
1797 if (!count) {
1798 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1799 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001800 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 "The read operation timed out");
1802 goto error;
1803 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1804 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001805 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 goto error;
1807 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1808 count = 0;
1809 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001810 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 }
1812 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 PySSL_BEGIN_ALLOW_THREADS
1814 count = SSL_read(self->ssl, mem, len);
1815 err = SSL_get_error(self->ssl, count);
1816 PySSL_END_ALLOW_THREADS
1817 if (PyErr_CheckSignals())
1818 goto error;
1819 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001820 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001822 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1824 (SSL_get_shutdown(self->ssl) ==
1825 SSL_RECEIVED_SHUTDOWN))
1826 {
1827 count = 0;
1828 goto done;
1829 } else {
1830 sockstate = SOCKET_OPERATION_OK;
1831 }
1832 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001833 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 "The read operation timed out");
1835 goto error;
1836 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1837 break;
1838 }
1839 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1840 if (count <= 0) {
1841 PySSL_SetError(self, count, __FILE__, __LINE__);
1842 goto error;
1843 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001844
1845done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001846 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001848 _PyBytes_Resize(&dest, count);
1849 return dest;
1850 }
1851 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 PyBuffer_Release(&buf);
1853 return PyLong_FromLong(count);
1854 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001855
1856error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001857 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001858 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001859 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001860 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001863}
1864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001865PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001866"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001867\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001869
Antoine Pitrou152efa22010-05-16 18:19:27 +00001870static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001871{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 int err, ssl_err, sockstate, nonblocking;
1873 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001874 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001875
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001876 if (sock != NULL) {
1877 /* Guard against closed socket */
1878 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1879 _setSSLError("Underlying socket connection gone",
1880 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1881 return NULL;
1882 }
1883 Py_INCREF(sock);
1884
1885 /* Just in case the blocking state of the socket has been changed */
1886 nonblocking = (sock->sock_timeout >= 0.0);
1887 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1888 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890
1891 while (1) {
1892 PySSL_BEGIN_ALLOW_THREADS
1893 /* Disable read-ahead so that unwrap can work correctly.
1894 * Otherwise OpenSSL might read in too much data,
1895 * eating clear text data that happens to be
1896 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001897 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 * function is used and the shutdown_seen_zero != 0
1899 * condition is met.
1900 */
1901 if (self->shutdown_seen_zero)
1902 SSL_set_read_ahead(self->ssl, 0);
1903 err = SSL_shutdown(self->ssl);
1904 PySSL_END_ALLOW_THREADS
1905 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1906 if (err > 0)
1907 break;
1908 if (err == 0) {
1909 /* Don't loop endlessly; instead preserve legacy
1910 behaviour of trying SSL_shutdown() only twice.
1911 This looks necessary for OpenSSL < 0.9.8m */
1912 if (++zeros > 1)
1913 break;
1914 /* Shutdown was sent, now try receiving */
1915 self->shutdown_seen_zero = 1;
1916 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001917 }
1918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 /* Possibly retry shutdown until timeout or failure */
1920 ssl_err = SSL_get_error(self->ssl, err);
1921 if (ssl_err == SSL_ERROR_WANT_READ)
1922 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1923 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1924 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1925 else
1926 break;
1927 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1928 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001929 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 "The read operation timed out");
1931 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001932 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001934 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 }
1936 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1937 PyErr_SetString(PySSLErrorObject,
1938 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001939 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 }
1941 else if (sockstate != SOCKET_OPERATION_OK)
1942 /* Retain the SSL error code */
1943 break;
1944 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001945
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001946 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001947 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001950 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001951 /* It's already INCREF'ed */
1952 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001953 else
1954 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001955
1956error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001957 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001958 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001959}
1960
1961PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1962"shutdown(s) -> socket\n\
1963\n\
1964Does the SSL shutdown handshake with the remote end, and returns\n\
1965the underlying socket object.");
1966
Antoine Pitroud6494802011-07-21 01:11:30 +02001967static PyObject *
1968PySSL_tls_unique_cb(PySSLSocket *self)
1969{
1970 PyObject *retval = NULL;
1971 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001972 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001973
1974 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1975 /* if session is resumed XOR we are the client */
1976 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1977 }
1978 else {
1979 /* if a new session XOR we are the server */
1980 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1981 }
1982
1983 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001984 if (len == 0)
1985 Py_RETURN_NONE;
1986
1987 retval = PyBytes_FromStringAndSize(buf, len);
1988
1989 return retval;
1990}
1991
1992PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1993"tls_unique_cb() -> bytes\n\
1994\n\
1995Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1996\n\
1997If the TLS handshake is not yet complete, None is returned");
1998
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001999static PyGetSetDef ssl_getsetlist[] = {
2000 {"context", (getter) PySSL_get_context,
2001 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002002 {"server_side", (getter) PySSL_get_server_side, NULL,
2003 PySSL_get_server_side_doc},
2004 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2005 PySSL_get_server_hostname_doc},
2006 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2007 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002008 {NULL}, /* sentinel */
2009};
2010
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002011static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2013 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2014 PySSL_SSLwrite_doc},
2015 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2016 PySSL_SSLread_doc},
2017 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2018 PySSL_SSLpending_doc},
2019 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2020 PySSL_peercert_doc},
2021 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002022 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002023#ifdef OPENSSL_NPN_NEGOTIATED
2024 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2025#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002026 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2028 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002029 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2030 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002031 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002032};
2033
Antoine Pitrou152efa22010-05-16 18:19:27 +00002034static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002035 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002036 "_ssl._SSLSocket", /*tp_name*/
2037 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002038 0, /*tp_itemsize*/
2039 /* methods */
2040 (destructor)PySSL_dealloc, /*tp_dealloc*/
2041 0, /*tp_print*/
2042 0, /*tp_getattr*/
2043 0, /*tp_setattr*/
2044 0, /*tp_reserved*/
2045 0, /*tp_repr*/
2046 0, /*tp_as_number*/
2047 0, /*tp_as_sequence*/
2048 0, /*tp_as_mapping*/
2049 0, /*tp_hash*/
2050 0, /*tp_call*/
2051 0, /*tp_str*/
2052 0, /*tp_getattro*/
2053 0, /*tp_setattro*/
2054 0, /*tp_as_buffer*/
2055 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2056 0, /*tp_doc*/
2057 0, /*tp_traverse*/
2058 0, /*tp_clear*/
2059 0, /*tp_richcompare*/
2060 0, /*tp_weaklistoffset*/
2061 0, /*tp_iter*/
2062 0, /*tp_iternext*/
2063 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002064 0, /*tp_members*/
2065 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002066};
2067
Antoine Pitrou152efa22010-05-16 18:19:27 +00002068
2069/*
2070 * _SSLContext objects
2071 */
2072
2073static PyObject *
2074context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2075{
2076 char *kwlist[] = {"protocol", NULL};
2077 PySSLContext *self;
2078 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002079 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080 SSL_CTX *ctx = NULL;
2081
2082 if (!PyArg_ParseTupleAndKeywords(
2083 args, kwds, "i:_SSLContext", kwlist,
2084 &proto_version))
2085 return NULL;
2086
2087 PySSL_BEGIN_ALLOW_THREADS
2088 if (proto_version == PY_SSL_VERSION_TLS1)
2089 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002090#if HAVE_TLSv1_2
2091 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2092 ctx = SSL_CTX_new(TLSv1_1_method());
2093 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2094 ctx = SSL_CTX_new(TLSv1_2_method());
2095#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002096#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097 else if (proto_version == PY_SSL_VERSION_SSL3)
2098 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002099#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002100#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002101 else if (proto_version == PY_SSL_VERSION_SSL2)
2102 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002103#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104 else if (proto_version == PY_SSL_VERSION_SSL23)
2105 ctx = SSL_CTX_new(SSLv23_method());
2106 else
2107 proto_version = -1;
2108 PySSL_END_ALLOW_THREADS
2109
2110 if (proto_version == -1) {
2111 PyErr_SetString(PyExc_ValueError,
2112 "invalid protocol version");
2113 return NULL;
2114 }
2115 if (ctx == NULL) {
2116 PyErr_SetString(PySSLErrorObject,
2117 "failed to allocate SSL context");
2118 return NULL;
2119 }
2120
2121 assert(type != NULL && type->tp_alloc != NULL);
2122 self = (PySSLContext *) type->tp_alloc(type, 0);
2123 if (self == NULL) {
2124 SSL_CTX_free(ctx);
2125 return NULL;
2126 }
2127 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002128#ifdef OPENSSL_NPN_NEGOTIATED
2129 self->npn_protocols = NULL;
2130#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002131#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002132 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002133#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002134 /* Don't check host name by default */
2135 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 /* Defaults */
2137 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002138 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2139 if (proto_version != PY_SSL_VERSION_SSL2)
2140 options |= SSL_OP_NO_SSLv2;
2141 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002142
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002143#ifndef OPENSSL_NO_ECDH
2144 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2145 prime256v1 by default. This is Apache mod_ssl's initialization
2146 policy, so we should be safe. */
2147#if defined(SSL_CTX_set_ecdh_auto)
2148 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2149#else
2150 {
2151 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2152 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2153 EC_KEY_free(key);
2154 }
2155#endif
2156#endif
2157
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002158#define SID_CTX "Python"
2159 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2160 sizeof(SID_CTX));
2161#undef SID_CTX
2162
Antoine Pitrou152efa22010-05-16 18:19:27 +00002163 return (PyObject *)self;
2164}
2165
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002166static int
2167context_traverse(PySSLContext *self, visitproc visit, void *arg)
2168{
2169#ifndef OPENSSL_NO_TLSEXT
2170 Py_VISIT(self->set_hostname);
2171#endif
2172 return 0;
2173}
2174
2175static int
2176context_clear(PySSLContext *self)
2177{
2178#ifndef OPENSSL_NO_TLSEXT
2179 Py_CLEAR(self->set_hostname);
2180#endif
2181 return 0;
2182}
2183
Antoine Pitrou152efa22010-05-16 18:19:27 +00002184static void
2185context_dealloc(PySSLContext *self)
2186{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002187 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002188 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002189#ifdef OPENSSL_NPN_NEGOTIATED
2190 PyMem_Free(self->npn_protocols);
2191#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 Py_TYPE(self)->tp_free(self);
2193}
2194
2195static PyObject *
2196set_ciphers(PySSLContext *self, PyObject *args)
2197{
2198 int ret;
2199 const char *cipherlist;
2200
2201 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2202 return NULL;
2203 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2204 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002205 /* Clearing the error queue is necessary on some OpenSSL versions,
2206 otherwise the error will be reported again when another SSL call
2207 is done. */
2208 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002209 PyErr_SetString(PySSLErrorObject,
2210 "No cipher can be selected.");
2211 return NULL;
2212 }
2213 Py_RETURN_NONE;
2214}
2215
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002216#ifdef OPENSSL_NPN_NEGOTIATED
2217/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2218static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002219_advertiseNPN_cb(SSL *s,
2220 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002221 void *args)
2222{
2223 PySSLContext *ssl_ctx = (PySSLContext *) args;
2224
2225 if (ssl_ctx->npn_protocols == NULL) {
2226 *data = (unsigned char *) "";
2227 *len = 0;
2228 } else {
2229 *data = (unsigned char *) ssl_ctx->npn_protocols;
2230 *len = ssl_ctx->npn_protocols_len;
2231 }
2232
2233 return SSL_TLSEXT_ERR_OK;
2234}
2235/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2236static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002237_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002238 unsigned char **out, unsigned char *outlen,
2239 const unsigned char *server, unsigned int server_len,
2240 void *args)
2241{
2242 PySSLContext *ssl_ctx = (PySSLContext *) args;
2243
2244 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2245 int client_len;
2246
2247 if (client == NULL) {
2248 client = (unsigned char *) "";
2249 client_len = 0;
2250 } else {
2251 client_len = ssl_ctx->npn_protocols_len;
2252 }
2253
2254 SSL_select_next_proto(out, outlen,
2255 server, server_len,
2256 client, client_len);
2257
2258 return SSL_TLSEXT_ERR_OK;
2259}
2260#endif
2261
2262static PyObject *
2263_set_npn_protocols(PySSLContext *self, PyObject *args)
2264{
2265#ifdef OPENSSL_NPN_NEGOTIATED
2266 Py_buffer protos;
2267
2268 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2269 return NULL;
2270
Christian Heimes5cb31c92012-09-20 12:42:54 +02002271 if (self->npn_protocols != NULL) {
2272 PyMem_Free(self->npn_protocols);
2273 }
2274
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002275 self->npn_protocols = PyMem_Malloc(protos.len);
2276 if (self->npn_protocols == NULL) {
2277 PyBuffer_Release(&protos);
2278 return PyErr_NoMemory();
2279 }
2280 memcpy(self->npn_protocols, protos.buf, protos.len);
2281 self->npn_protocols_len = (int) protos.len;
2282
2283 /* set both server and client callbacks, because the context can
2284 * be used to create both types of sockets */
2285 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2286 _advertiseNPN_cb,
2287 self);
2288 SSL_CTX_set_next_proto_select_cb(self->ctx,
2289 _selectNPN_cb,
2290 self);
2291
2292 PyBuffer_Release(&protos);
2293 Py_RETURN_NONE;
2294#else
2295 PyErr_SetString(PyExc_NotImplementedError,
2296 "The NPN extension requires OpenSSL 1.0.1 or later.");
2297 return NULL;
2298#endif
2299}
2300
Antoine Pitrou152efa22010-05-16 18:19:27 +00002301static PyObject *
2302get_verify_mode(PySSLContext *self, void *c)
2303{
2304 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2305 case SSL_VERIFY_NONE:
2306 return PyLong_FromLong(PY_SSL_CERT_NONE);
2307 case SSL_VERIFY_PEER:
2308 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2309 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2310 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2311 }
2312 PyErr_SetString(PySSLErrorObject,
2313 "invalid return value from SSL_CTX_get_verify_mode");
2314 return NULL;
2315}
2316
2317static int
2318set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2319{
2320 int n, mode;
2321 if (!PyArg_Parse(arg, "i", &n))
2322 return -1;
2323 if (n == PY_SSL_CERT_NONE)
2324 mode = SSL_VERIFY_NONE;
2325 else if (n == PY_SSL_CERT_OPTIONAL)
2326 mode = SSL_VERIFY_PEER;
2327 else if (n == PY_SSL_CERT_REQUIRED)
2328 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2329 else {
2330 PyErr_SetString(PyExc_ValueError,
2331 "invalid value for verify_mode");
2332 return -1;
2333 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002334 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2335 PyErr_SetString(PyExc_ValueError,
2336 "Cannot set verify_mode to CERT_NONE when "
2337 "check_hostname is enabled.");
2338 return -1;
2339 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340 SSL_CTX_set_verify(self->ctx, mode, NULL);
2341 return 0;
2342}
2343
2344static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002345get_verify_flags(PySSLContext *self, void *c)
2346{
2347 X509_STORE *store;
2348 unsigned long flags;
2349
2350 store = SSL_CTX_get_cert_store(self->ctx);
2351 flags = X509_VERIFY_PARAM_get_flags(store->param);
2352 return PyLong_FromUnsignedLong(flags);
2353}
2354
2355static int
2356set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2357{
2358 X509_STORE *store;
2359 unsigned long new_flags, flags, set, clear;
2360
2361 if (!PyArg_Parse(arg, "k", &new_flags))
2362 return -1;
2363 store = SSL_CTX_get_cert_store(self->ctx);
2364 flags = X509_VERIFY_PARAM_get_flags(store->param);
2365 clear = flags & ~new_flags;
2366 set = ~flags & new_flags;
2367 if (clear) {
2368 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2369 _setSSLError(NULL, 0, __FILE__, __LINE__);
2370 return -1;
2371 }
2372 }
2373 if (set) {
2374 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2375 _setSSLError(NULL, 0, __FILE__, __LINE__);
2376 return -1;
2377 }
2378 }
2379 return 0;
2380}
2381
2382static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002383get_options(PySSLContext *self, void *c)
2384{
2385 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2386}
2387
2388static int
2389set_options(PySSLContext *self, PyObject *arg, void *c)
2390{
2391 long new_opts, opts, set, clear;
2392 if (!PyArg_Parse(arg, "l", &new_opts))
2393 return -1;
2394 opts = SSL_CTX_get_options(self->ctx);
2395 clear = opts & ~new_opts;
2396 set = ~opts & new_opts;
2397 if (clear) {
2398#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2399 SSL_CTX_clear_options(self->ctx, clear);
2400#else
2401 PyErr_SetString(PyExc_ValueError,
2402 "can't clear options before OpenSSL 0.9.8m");
2403 return -1;
2404#endif
2405 }
2406 if (set)
2407 SSL_CTX_set_options(self->ctx, set);
2408 return 0;
2409}
2410
Christian Heimes1aa9a752013-12-02 02:41:19 +01002411static PyObject *
2412get_check_hostname(PySSLContext *self, void *c)
2413{
2414 return PyBool_FromLong(self->check_hostname);
2415}
2416
2417static int
2418set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2419{
2420 int check_hostname;
2421 if (!PyArg_Parse(arg, "p", &check_hostname))
2422 return -1;
2423 if (check_hostname &&
2424 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2425 PyErr_SetString(PyExc_ValueError,
2426 "check_hostname needs a SSL context with either "
2427 "CERT_OPTIONAL or CERT_REQUIRED");
2428 return -1;
2429 }
2430 self->check_hostname = check_hostname;
2431 return 0;
2432}
2433
2434
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002435typedef struct {
2436 PyThreadState *thread_state;
2437 PyObject *callable;
2438 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002439 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002440 int error;
2441} _PySSLPasswordInfo;
2442
2443static int
2444_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2445 const char *bad_type_error)
2446{
2447 /* Set the password and size fields of a _PySSLPasswordInfo struct
2448 from a unicode, bytes, or byte array object.
2449 The password field will be dynamically allocated and must be freed
2450 by the caller */
2451 PyObject *password_bytes = NULL;
2452 const char *data = NULL;
2453 Py_ssize_t size;
2454
2455 if (PyUnicode_Check(password)) {
2456 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2457 if (!password_bytes) {
2458 goto error;
2459 }
2460 data = PyBytes_AS_STRING(password_bytes);
2461 size = PyBytes_GET_SIZE(password_bytes);
2462 } else if (PyBytes_Check(password)) {
2463 data = PyBytes_AS_STRING(password);
2464 size = PyBytes_GET_SIZE(password);
2465 } else if (PyByteArray_Check(password)) {
2466 data = PyByteArray_AS_STRING(password);
2467 size = PyByteArray_GET_SIZE(password);
2468 } else {
2469 PyErr_SetString(PyExc_TypeError, bad_type_error);
2470 goto error;
2471 }
2472
Victor Stinner9ee02032013-06-23 15:08:23 +02002473 if (size > (Py_ssize_t)INT_MAX) {
2474 PyErr_Format(PyExc_ValueError,
2475 "password cannot be longer than %d bytes", INT_MAX);
2476 goto error;
2477 }
2478
Victor Stinner11ebff22013-07-07 17:07:52 +02002479 PyMem_Free(pw_info->password);
2480 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002481 if (!pw_info->password) {
2482 PyErr_SetString(PyExc_MemoryError,
2483 "unable to allocate password buffer");
2484 goto error;
2485 }
2486 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002487 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002488
2489 Py_XDECREF(password_bytes);
2490 return 1;
2491
2492error:
2493 Py_XDECREF(password_bytes);
2494 return 0;
2495}
2496
2497static int
2498_password_callback(char *buf, int size, int rwflag, void *userdata)
2499{
2500 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2501 PyObject *fn_ret = NULL;
2502
2503 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2504
2505 if (pw_info->callable) {
2506 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2507 if (!fn_ret) {
2508 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2509 core python API, so we could use it to add a frame here */
2510 goto error;
2511 }
2512
2513 if (!_pwinfo_set(pw_info, fn_ret,
2514 "password callback must return a string")) {
2515 goto error;
2516 }
2517 Py_CLEAR(fn_ret);
2518 }
2519
2520 if (pw_info->size > size) {
2521 PyErr_Format(PyExc_ValueError,
2522 "password cannot be longer than %d bytes", size);
2523 goto error;
2524 }
2525
2526 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2527 memcpy(buf, pw_info->password, pw_info->size);
2528 return pw_info->size;
2529
2530error:
2531 Py_XDECREF(fn_ret);
2532 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2533 pw_info->error = 1;
2534 return -1;
2535}
2536
Antoine Pitroub5218772010-05-21 09:56:06 +00002537static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002538load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2539{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002540 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2541 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002542 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002543 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2544 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2545 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002546 int r;
2547
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002548 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002549 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002550 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002551 "O|OO:load_cert_chain", kwlist,
2552 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002553 return NULL;
2554 if (keyfile == Py_None)
2555 keyfile = NULL;
2556 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2557 PyErr_SetString(PyExc_TypeError,
2558 "certfile should be a valid filesystem path");
2559 return NULL;
2560 }
2561 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2562 PyErr_SetString(PyExc_TypeError,
2563 "keyfile should be a valid filesystem path");
2564 goto error;
2565 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002566 if (password && password != Py_None) {
2567 if (PyCallable_Check(password)) {
2568 pw_info.callable = password;
2569 } else if (!_pwinfo_set(&pw_info, password,
2570 "password should be a string or callable")) {
2571 goto error;
2572 }
2573 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2574 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2575 }
2576 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002577 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2578 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002579 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002580 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002581 if (pw_info.error) {
2582 ERR_clear_error();
2583 /* the password callback has already set the error information */
2584 }
2585 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002586 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002587 PyErr_SetFromErrno(PyExc_IOError);
2588 }
2589 else {
2590 _setSSLError(NULL, 0, __FILE__, __LINE__);
2591 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002592 goto error;
2593 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002594 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002595 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002596 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2597 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002598 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2599 Py_CLEAR(keyfile_bytes);
2600 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002601 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002602 if (pw_info.error) {
2603 ERR_clear_error();
2604 /* the password callback has already set the error information */
2605 }
2606 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002607 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002608 PyErr_SetFromErrno(PyExc_IOError);
2609 }
2610 else {
2611 _setSSLError(NULL, 0, __FILE__, __LINE__);
2612 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002613 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002614 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002615 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002616 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002617 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618 if (r != 1) {
2619 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002620 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002621 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002622 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2623 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002624 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002625 Py_RETURN_NONE;
2626
2627error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002628 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2629 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002630 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002631 Py_XDECREF(keyfile_bytes);
2632 Py_XDECREF(certfile_bytes);
2633 return NULL;
2634}
2635
Christian Heimesefff7062013-11-21 03:35:02 +01002636/* internal helper function, returns -1 on error
2637 */
2638static int
2639_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2640 int filetype)
2641{
2642 BIO *biobuf = NULL;
2643 X509_STORE *store;
2644 int retval = 0, err, loaded = 0;
2645
2646 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2647
2648 if (len <= 0) {
2649 PyErr_SetString(PyExc_ValueError,
2650 "Empty certificate data");
2651 return -1;
2652 } else if (len > INT_MAX) {
2653 PyErr_SetString(PyExc_OverflowError,
2654 "Certificate data is too long.");
2655 return -1;
2656 }
2657
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002658 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002659 if (biobuf == NULL) {
2660 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2661 return -1;
2662 }
2663
2664 store = SSL_CTX_get_cert_store(self->ctx);
2665 assert(store != NULL);
2666
2667 while (1) {
2668 X509 *cert = NULL;
2669 int r;
2670
2671 if (filetype == SSL_FILETYPE_ASN1) {
2672 cert = d2i_X509_bio(biobuf, NULL);
2673 } else {
2674 cert = PEM_read_bio_X509(biobuf, NULL,
2675 self->ctx->default_passwd_callback,
2676 self->ctx->default_passwd_callback_userdata);
2677 }
2678 if (cert == NULL) {
2679 break;
2680 }
2681 r = X509_STORE_add_cert(store, cert);
2682 X509_free(cert);
2683 if (!r) {
2684 err = ERR_peek_last_error();
2685 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2686 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2687 /* cert already in hash table, not an error */
2688 ERR_clear_error();
2689 } else {
2690 break;
2691 }
2692 }
2693 loaded++;
2694 }
2695
2696 err = ERR_peek_last_error();
2697 if ((filetype == SSL_FILETYPE_ASN1) &&
2698 (loaded > 0) &&
2699 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2700 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2701 /* EOF ASN1 file, not an error */
2702 ERR_clear_error();
2703 retval = 0;
2704 } else if ((filetype == SSL_FILETYPE_PEM) &&
2705 (loaded > 0) &&
2706 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2707 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2708 /* EOF PEM file, not an error */
2709 ERR_clear_error();
2710 retval = 0;
2711 } else {
2712 _setSSLError(NULL, 0, __FILE__, __LINE__);
2713 retval = -1;
2714 }
2715
2716 BIO_free(biobuf);
2717 return retval;
2718}
2719
2720
Antoine Pitrou152efa22010-05-16 18:19:27 +00002721static PyObject *
2722load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2723{
Christian Heimesefff7062013-11-21 03:35:02 +01002724 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2725 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002726 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2727 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002728 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002729
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002730 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002731 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002732 "|OOO:load_verify_locations", kwlist,
2733 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002735
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736 if (cafile == Py_None)
2737 cafile = NULL;
2738 if (capath == Py_None)
2739 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002740 if (cadata == Py_None)
2741 cadata = NULL;
2742
2743 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002744 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002745 "cafile, capath and cadata cannot be all omitted");
2746 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002747 }
2748 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2749 PyErr_SetString(PyExc_TypeError,
2750 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002751 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002752 }
2753 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002754 PyErr_SetString(PyExc_TypeError,
2755 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002756 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 }
Christian Heimesefff7062013-11-21 03:35:02 +01002758
2759 /* validata cadata type and load cadata */
2760 if (cadata) {
2761 Py_buffer buf;
2762 PyObject *cadata_ascii = NULL;
2763
2764 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2765 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2766 PyBuffer_Release(&buf);
2767 PyErr_SetString(PyExc_TypeError,
2768 "cadata should be a contiguous buffer with "
2769 "a single dimension");
2770 goto error;
2771 }
2772 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2773 PyBuffer_Release(&buf);
2774 if (r == -1) {
2775 goto error;
2776 }
2777 } else {
2778 PyErr_Clear();
2779 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2780 if (cadata_ascii == NULL) {
2781 PyErr_SetString(PyExc_TypeError,
2782 "cadata should be a ASCII string or a "
2783 "bytes-like object");
2784 goto error;
2785 }
2786 r = _add_ca_certs(self,
2787 PyBytes_AS_STRING(cadata_ascii),
2788 PyBytes_GET_SIZE(cadata_ascii),
2789 SSL_FILETYPE_PEM);
2790 Py_DECREF(cadata_ascii);
2791 if (r == -1) {
2792 goto error;
2793 }
2794 }
2795 }
2796
2797 /* load cafile or capath */
2798 if (cafile || capath) {
2799 if (cafile)
2800 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2801 if (capath)
2802 capath_buf = PyBytes_AS_STRING(capath_bytes);
2803 PySSL_BEGIN_ALLOW_THREADS
2804 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2805 PySSL_END_ALLOW_THREADS
2806 if (r != 1) {
2807 ok = 0;
2808 if (errno != 0) {
2809 ERR_clear_error();
2810 PyErr_SetFromErrno(PyExc_IOError);
2811 }
2812 else {
2813 _setSSLError(NULL, 0, __FILE__, __LINE__);
2814 }
2815 goto error;
2816 }
2817 }
2818 goto end;
2819
2820 error:
2821 ok = 0;
2822 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002823 Py_XDECREF(cafile_bytes);
2824 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002825 if (ok) {
2826 Py_RETURN_NONE;
2827 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002828 return NULL;
2829 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002830}
2831
2832static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002833load_dh_params(PySSLContext *self, PyObject *filepath)
2834{
2835 FILE *f;
2836 DH *dh;
2837
Victor Stinnerdaf45552013-08-28 00:53:59 +02002838 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002839 if (f == NULL) {
2840 if (!PyErr_Occurred())
2841 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2842 return NULL;
2843 }
2844 errno = 0;
2845 PySSL_BEGIN_ALLOW_THREADS
2846 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002847 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002848 PySSL_END_ALLOW_THREADS
2849 if (dh == NULL) {
2850 if (errno != 0) {
2851 ERR_clear_error();
2852 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2853 }
2854 else {
2855 _setSSLError(NULL, 0, __FILE__, __LINE__);
2856 }
2857 return NULL;
2858 }
2859 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2860 _setSSLError(NULL, 0, __FILE__, __LINE__);
2861 DH_free(dh);
2862 Py_RETURN_NONE;
2863}
2864
2865static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002866context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2867{
Antoine Pitroud5323212010-10-22 18:19:07 +00002868 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869 PySocketSockObject *sock;
2870 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002871 char *hostname = NULL;
2872 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873
Antoine Pitroud5323212010-10-22 18:19:07 +00002874 /* server_hostname is either None (or absent), or to be encoded
2875 using the idna encoding. */
2876 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002877 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002878 &sock, &server_side,
2879 Py_TYPE(Py_None), &hostname_obj)) {
2880 PyErr_Clear();
2881 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2882 PySocketModule.Sock_Type,
2883 &sock, &server_side,
2884 "idna", &hostname))
2885 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002886 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002887
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002888 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2889 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002890 if (hostname != NULL)
2891 PyMem_Free(hostname);
2892 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002893}
2894
Antoine Pitroub0182c82010-10-12 20:09:02 +00002895static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002896context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
2897{
2898 char *kwlist[] = {"incoming", "outgoing", "server_side",
2899 "server_hostname", NULL};
2900 int server_side;
2901 char *hostname = NULL;
2902 PyObject *hostname_obj = Py_None, *res;
2903 PySSLMemoryBIO *incoming, *outgoing;
2904
2905 /* server_hostname is either None (or absent), or to be encoded
2906 using the idna encoding. */
2907 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
2908 &PySSLMemoryBIO_Type, &incoming,
2909 &PySSLMemoryBIO_Type, &outgoing,
2910 &server_side, &hostname_obj))
2911 return NULL;
2912 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002913 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
2914 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002915 }
2916
2917 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
2918 incoming, outgoing);
2919
2920 PyMem_Free(hostname);
2921 return res;
2922}
2923
2924static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00002925session_stats(PySSLContext *self, PyObject *unused)
2926{
2927 int r;
2928 PyObject *value, *stats = PyDict_New();
2929 if (!stats)
2930 return NULL;
2931
2932#define ADD_STATS(SSL_NAME, KEY_NAME) \
2933 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2934 if (value == NULL) \
2935 goto error; \
2936 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2937 Py_DECREF(value); \
2938 if (r < 0) \
2939 goto error;
2940
2941 ADD_STATS(number, "number");
2942 ADD_STATS(connect, "connect");
2943 ADD_STATS(connect_good, "connect_good");
2944 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2945 ADD_STATS(accept, "accept");
2946 ADD_STATS(accept_good, "accept_good");
2947 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2948 ADD_STATS(accept, "accept");
2949 ADD_STATS(hits, "hits");
2950 ADD_STATS(misses, "misses");
2951 ADD_STATS(timeouts, "timeouts");
2952 ADD_STATS(cache_full, "cache_full");
2953
2954#undef ADD_STATS
2955
2956 return stats;
2957
2958error:
2959 Py_DECREF(stats);
2960 return NULL;
2961}
2962
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002963static PyObject *
2964set_default_verify_paths(PySSLContext *self, PyObject *unused)
2965{
2966 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2967 _setSSLError(NULL, 0, __FILE__, __LINE__);
2968 return NULL;
2969 }
2970 Py_RETURN_NONE;
2971}
2972
Antoine Pitrou501da612011-12-21 09:27:41 +01002973#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002974static PyObject *
2975set_ecdh_curve(PySSLContext *self, PyObject *name)
2976{
2977 PyObject *name_bytes;
2978 int nid;
2979 EC_KEY *key;
2980
2981 if (!PyUnicode_FSConverter(name, &name_bytes))
2982 return NULL;
2983 assert(PyBytes_Check(name_bytes));
2984 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2985 Py_DECREF(name_bytes);
2986 if (nid == 0) {
2987 PyErr_Format(PyExc_ValueError,
2988 "unknown elliptic curve name %R", name);
2989 return NULL;
2990 }
2991 key = EC_KEY_new_by_curve_name(nid);
2992 if (key == NULL) {
2993 _setSSLError(NULL, 0, __FILE__, __LINE__);
2994 return NULL;
2995 }
2996 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2997 EC_KEY_free(key);
2998 Py_RETURN_NONE;
2999}
Antoine Pitrou501da612011-12-21 09:27:41 +01003000#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003001
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003002#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003003static int
3004_servername_callback(SSL *s, int *al, void *args)
3005{
3006 int ret;
3007 PySSLContext *ssl_ctx = (PySSLContext *) args;
3008 PySSLSocket *ssl;
3009 PyObject *servername_o;
3010 PyObject *servername_idna;
3011 PyObject *result;
3012 /* The high-level ssl.SSLSocket object */
3013 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003014 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003015#ifdef WITH_THREAD
3016 PyGILState_STATE gstate = PyGILState_Ensure();
3017#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003018
3019 if (ssl_ctx->set_hostname == NULL) {
3020 /* remove race condition in this the call back while if removing the
3021 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003022#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003023 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003024#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003025 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003026 }
3027
3028 ssl = SSL_get_app_data(s);
3029 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003030
3031 /* The servername callback expects a argument that represents the current
3032 * SSL connection and that has a .context attribute that can be changed to
3033 * identify the requested hostname. Since the official API is the Python
3034 * level API we want to pass the callback a Python level object rather than
3035 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3036 * SSLObject) that will be passed. Otherwise if there's a socket then that
3037 * will be passed. If both do not exist only then the C-level object is
3038 * passed. */
3039 if (ssl->owner)
3040 ssl_socket = PyWeakref_GetObject(ssl->owner);
3041 else if (ssl->Socket)
3042 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3043 else
3044 ssl_socket = (PyObject *) ssl;
3045
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003046 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003047 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003048 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003049
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003050 if (servername == NULL) {
3051 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3052 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003053 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003054 else {
3055 servername_o = PyBytes_FromString(servername);
3056 if (servername_o == NULL) {
3057 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3058 goto error;
3059 }
3060 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3061 if (servername_idna == NULL) {
3062 PyErr_WriteUnraisable(servername_o);
3063 Py_DECREF(servername_o);
3064 goto error;
3065 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003066 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003067 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3068 servername_idna, ssl_ctx, NULL);
3069 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003070 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003071 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003072
3073 if (result == NULL) {
3074 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3075 *al = SSL_AD_HANDSHAKE_FAILURE;
3076 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3077 }
3078 else {
3079 if (result != Py_None) {
3080 *al = (int) PyLong_AsLong(result);
3081 if (PyErr_Occurred()) {
3082 PyErr_WriteUnraisable(result);
3083 *al = SSL_AD_INTERNAL_ERROR;
3084 }
3085 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3086 }
3087 else {
3088 ret = SSL_TLSEXT_ERR_OK;
3089 }
3090 Py_DECREF(result);
3091 }
3092
Stefan Krah20d60802013-01-17 17:07:17 +01003093#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003094 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003095#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003096 return ret;
3097
3098error:
3099 Py_DECREF(ssl_socket);
3100 *al = SSL_AD_INTERNAL_ERROR;
3101 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003102#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003103 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003104#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003105 return ret;
3106}
Antoine Pitroua5963382013-03-30 16:39:00 +01003107#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003108
3109PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3110"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003111\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003112This sets a callback that will be called when a server name is provided by\n\
3113the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003114\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003115If the argument is None then the callback is disabled. The method is called\n\
3116with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003117See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003118
3119static PyObject *
3120set_servername_callback(PySSLContext *self, PyObject *args)
3121{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003122#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003123 PyObject *cb;
3124
3125 if (!PyArg_ParseTuple(args, "O", &cb))
3126 return NULL;
3127
3128 Py_CLEAR(self->set_hostname);
3129 if (cb == Py_None) {
3130 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3131 }
3132 else {
3133 if (!PyCallable_Check(cb)) {
3134 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3135 PyErr_SetString(PyExc_TypeError,
3136 "not a callable object");
3137 return NULL;
3138 }
3139 Py_INCREF(cb);
3140 self->set_hostname = cb;
3141 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3142 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3143 }
3144 Py_RETURN_NONE;
3145#else
3146 PyErr_SetString(PyExc_NotImplementedError,
3147 "The TLS extension servername callback, "
3148 "SSL_CTX_set_tlsext_servername_callback, "
3149 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003150 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003151#endif
3152}
3153
Christian Heimes9a5395a2013-06-17 15:44:12 +02003154PyDoc_STRVAR(PySSL_get_stats_doc,
3155"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3156\n\
3157Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3158CA extension and certificate revocation lists inside the context's cert\n\
3159store.\n\
3160NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3161been used at least once.");
3162
3163static PyObject *
3164cert_store_stats(PySSLContext *self)
3165{
3166 X509_STORE *store;
3167 X509_OBJECT *obj;
3168 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3169
3170 store = SSL_CTX_get_cert_store(self->ctx);
3171 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3172 obj = sk_X509_OBJECT_value(store->objs, i);
3173 switch (obj->type) {
3174 case X509_LU_X509:
3175 x509++;
3176 if (X509_check_ca(obj->data.x509)) {
3177 ca++;
3178 }
3179 break;
3180 case X509_LU_CRL:
3181 crl++;
3182 break;
3183 case X509_LU_PKEY:
3184 pkey++;
3185 break;
3186 default:
3187 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3188 * As far as I can tell they are internal states and never
3189 * stored in a cert store */
3190 break;
3191 }
3192 }
3193 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3194 "x509_ca", ca);
3195}
3196
3197PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003198"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003199\n\
3200Returns a list of dicts with information of loaded CA certs. If the\n\
3201optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3202NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3203been used at least once.");
3204
3205static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003206get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003207{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003208 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003209 X509_STORE *store;
3210 PyObject *ci = NULL, *rlist = NULL;
3211 int i;
3212 int binary_mode = 0;
3213
Christian Heimesf22e8e52013-11-22 02:22:51 +01003214 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3215 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003216 return NULL;
3217 }
3218
3219 if ((rlist = PyList_New(0)) == NULL) {
3220 return NULL;
3221 }
3222
3223 store = SSL_CTX_get_cert_store(self->ctx);
3224 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3225 X509_OBJECT *obj;
3226 X509 *cert;
3227
3228 obj = sk_X509_OBJECT_value(store->objs, i);
3229 if (obj->type != X509_LU_X509) {
3230 /* not a x509 cert */
3231 continue;
3232 }
3233 /* CA for any purpose */
3234 cert = obj->data.x509;
3235 if (!X509_check_ca(cert)) {
3236 continue;
3237 }
3238 if (binary_mode) {
3239 ci = _certificate_to_der(cert);
3240 } else {
3241 ci = _decode_certificate(cert);
3242 }
3243 if (ci == NULL) {
3244 goto error;
3245 }
3246 if (PyList_Append(rlist, ci) == -1) {
3247 goto error;
3248 }
3249 Py_CLEAR(ci);
3250 }
3251 return rlist;
3252
3253 error:
3254 Py_XDECREF(ci);
3255 Py_XDECREF(rlist);
3256 return NULL;
3257}
3258
3259
Antoine Pitrou152efa22010-05-16 18:19:27 +00003260static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003261 {"check_hostname", (getter) get_check_hostname,
3262 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003263 {"options", (getter) get_options,
3264 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003265 {"verify_flags", (getter) get_verify_flags,
3266 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003267 {"verify_mode", (getter) get_verify_mode,
3268 (setter) set_verify_mode, NULL},
3269 {NULL}, /* sentinel */
3270};
3271
3272static struct PyMethodDef context_methods[] = {
3273 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3274 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003275 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3276 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003277 {"set_ciphers", (PyCFunction) set_ciphers,
3278 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003279 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3280 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281 {"load_cert_chain", (PyCFunction) load_cert_chain,
3282 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003283 {"load_dh_params", (PyCFunction) load_dh_params,
3284 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003285 {"load_verify_locations", (PyCFunction) load_verify_locations,
3286 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003287 {"session_stats", (PyCFunction) session_stats,
3288 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003289 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3290 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003291#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003292 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3293 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003294#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003295 {"set_servername_callback", (PyCFunction) set_servername_callback,
3296 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003297 {"cert_store_stats", (PyCFunction) cert_store_stats,
3298 METH_NOARGS, PySSL_get_stats_doc},
3299 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003300 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003301 {NULL, NULL} /* sentinel */
3302};
3303
3304static PyTypeObject PySSLContext_Type = {
3305 PyVarObject_HEAD_INIT(NULL, 0)
3306 "_ssl._SSLContext", /*tp_name*/
3307 sizeof(PySSLContext), /*tp_basicsize*/
3308 0, /*tp_itemsize*/
3309 (destructor)context_dealloc, /*tp_dealloc*/
3310 0, /*tp_print*/
3311 0, /*tp_getattr*/
3312 0, /*tp_setattr*/
3313 0, /*tp_reserved*/
3314 0, /*tp_repr*/
3315 0, /*tp_as_number*/
3316 0, /*tp_as_sequence*/
3317 0, /*tp_as_mapping*/
3318 0, /*tp_hash*/
3319 0, /*tp_call*/
3320 0, /*tp_str*/
3321 0, /*tp_getattro*/
3322 0, /*tp_setattro*/
3323 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003324 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003326 (traverseproc) context_traverse, /*tp_traverse*/
3327 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 0, /*tp_richcompare*/
3329 0, /*tp_weaklistoffset*/
3330 0, /*tp_iter*/
3331 0, /*tp_iternext*/
3332 context_methods, /*tp_methods*/
3333 0, /*tp_members*/
3334 context_getsetlist, /*tp_getset*/
3335 0, /*tp_base*/
3336 0, /*tp_dict*/
3337 0, /*tp_descr_get*/
3338 0, /*tp_descr_set*/
3339 0, /*tp_dictoffset*/
3340 0, /*tp_init*/
3341 0, /*tp_alloc*/
3342 context_new, /*tp_new*/
3343};
3344
3345
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003346/*
3347 * MemoryBIO objects
3348 */
3349
3350static PyObject *
3351memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3352{
3353 char *kwlist[] = {NULL};
3354 BIO *bio;
3355 PySSLMemoryBIO *self;
3356
3357 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3358 return NULL;
3359
3360 bio = BIO_new(BIO_s_mem());
3361 if (bio == NULL) {
3362 PyErr_SetString(PySSLErrorObject,
3363 "failed to allocate BIO");
3364 return NULL;
3365 }
3366 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3367 * just that no data is currently available. The SSL routines should retry
3368 * the read, which we can achieve by calling BIO_set_retry_read(). */
3369 BIO_set_retry_read(bio);
3370 BIO_set_mem_eof_return(bio, -1);
3371
3372 assert(type != NULL && type->tp_alloc != NULL);
3373 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3374 if (self == NULL) {
3375 BIO_free(bio);
3376 return NULL;
3377 }
3378 self->bio = bio;
3379 self->eof_written = 0;
3380
3381 return (PyObject *) self;
3382}
3383
3384static void
3385memory_bio_dealloc(PySSLMemoryBIO *self)
3386{
3387 BIO_free(self->bio);
3388 Py_TYPE(self)->tp_free(self);
3389}
3390
3391static PyObject *
3392memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3393{
3394 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3395}
3396
3397PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3398"The number of bytes pending in the memory BIO.");
3399
3400static PyObject *
3401memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3402{
3403 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3404 && self->eof_written);
3405}
3406
3407PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3408"Whether the memory BIO is at EOF.");
3409
3410static PyObject *
3411memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3412{
3413 int len = -1, avail, nbytes;
3414 PyObject *result;
3415
3416 if (!PyArg_ParseTuple(args, "|i:read", &len))
3417 return NULL;
3418
3419 avail = BIO_ctrl_pending(self->bio);
3420 if ((len < 0) || (len > avail))
3421 len = avail;
3422
3423 result = PyBytes_FromStringAndSize(NULL, len);
3424 if ((result == NULL) || (len == 0))
3425 return result;
3426
3427 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3428 /* There should never be any short reads but check anyway. */
3429 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3430 Py_DECREF(result);
3431 return NULL;
3432 }
3433
3434 return result;
3435}
3436
3437PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3438"read([len]) -> bytes\n\
3439\n\
3440Read up to len bytes from the memory BIO.\n\
3441\n\
3442If len is not specified, read the entire buffer.\n\
3443If the return value is an empty bytes instance, this means either\n\
3444EOF or that no data is available. Use the \"eof\" property to\n\
3445distinguish between the two.");
3446
3447static PyObject *
3448memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3449{
3450 Py_buffer buf;
3451 int nbytes;
3452
3453 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3454 return NULL;
3455
3456 if (buf.len > INT_MAX) {
3457 PyErr_Format(PyExc_OverflowError,
3458 "string longer than %d bytes", INT_MAX);
3459 goto error;
3460 }
3461
3462 if (self->eof_written) {
3463 PyErr_SetString(PySSLErrorObject,
3464 "cannot write() after write_eof()");
3465 goto error;
3466 }
3467
3468 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3469 if (nbytes < 0) {
3470 _setSSLError(NULL, 0, __FILE__, __LINE__);
3471 goto error;
3472 }
3473
3474 PyBuffer_Release(&buf);
3475 return PyLong_FromLong(nbytes);
3476
3477error:
3478 PyBuffer_Release(&buf);
3479 return NULL;
3480}
3481
3482PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3483"write(b) -> len\n\
3484\n\
3485Writes the bytes b into the memory BIO. Returns the number\n\
3486of bytes written.");
3487
3488static PyObject *
3489memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3490{
3491 self->eof_written = 1;
3492 /* After an EOF is written, a zero return from read() should be a real EOF
3493 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3494 BIO_clear_retry_flags(self->bio);
3495 BIO_set_mem_eof_return(self->bio, 0);
3496
3497 Py_RETURN_NONE;
3498}
3499
3500PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3501"write_eof()\n\
3502\n\
3503Write an EOF marker to the memory BIO.\n\
3504When all data has been read, the \"eof\" property will be True.");
3505
3506static PyGetSetDef memory_bio_getsetlist[] = {
3507 {"pending", (getter) memory_bio_get_pending, NULL,
3508 PySSL_memory_bio_pending_doc},
3509 {"eof", (getter) memory_bio_get_eof, NULL,
3510 PySSL_memory_bio_eof_doc},
3511 {NULL}, /* sentinel */
3512};
3513
3514static struct PyMethodDef memory_bio_methods[] = {
3515 {"read", (PyCFunction) memory_bio_read,
3516 METH_VARARGS, PySSL_memory_bio_read_doc},
3517 {"write", (PyCFunction) memory_bio_write,
3518 METH_VARARGS, PySSL_memory_bio_write_doc},
3519 {"write_eof", (PyCFunction) memory_bio_write_eof,
3520 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3521 {NULL, NULL} /* sentinel */
3522};
3523
3524static PyTypeObject PySSLMemoryBIO_Type = {
3525 PyVarObject_HEAD_INIT(NULL, 0)
3526 "_ssl.MemoryBIO", /*tp_name*/
3527 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3528 0, /*tp_itemsize*/
3529 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3530 0, /*tp_print*/
3531 0, /*tp_getattr*/
3532 0, /*tp_setattr*/
3533 0, /*tp_reserved*/
3534 0, /*tp_repr*/
3535 0, /*tp_as_number*/
3536 0, /*tp_as_sequence*/
3537 0, /*tp_as_mapping*/
3538 0, /*tp_hash*/
3539 0, /*tp_call*/
3540 0, /*tp_str*/
3541 0, /*tp_getattro*/
3542 0, /*tp_setattro*/
3543 0, /*tp_as_buffer*/
3544 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3545 0, /*tp_doc*/
3546 0, /*tp_traverse*/
3547 0, /*tp_clear*/
3548 0, /*tp_richcompare*/
3549 0, /*tp_weaklistoffset*/
3550 0, /*tp_iter*/
3551 0, /*tp_iternext*/
3552 memory_bio_methods, /*tp_methods*/
3553 0, /*tp_members*/
3554 memory_bio_getsetlist, /*tp_getset*/
3555 0, /*tp_base*/
3556 0, /*tp_dict*/
3557 0, /*tp_descr_get*/
3558 0, /*tp_descr_set*/
3559 0, /*tp_dictoffset*/
3560 0, /*tp_init*/
3561 0, /*tp_alloc*/
3562 memory_bio_new, /*tp_new*/
3563};
3564
Antoine Pitrou152efa22010-05-16 18:19:27 +00003565
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003566/* helper routines for seeding the SSL PRNG */
3567static PyObject *
3568PySSL_RAND_add(PyObject *self, PyObject *args)
3569{
3570 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003571 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003572 double entropy;
3573
3574 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003575 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003576 do {
3577 written = Py_MIN(len, INT_MAX);
3578 RAND_add(buf, (int)written, entropy);
3579 buf += written;
3580 len -= written;
3581 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003582 Py_INCREF(Py_None);
3583 return Py_None;
3584}
3585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003587"RAND_add(string, entropy)\n\
3588\n\
3589Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003590bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003591
3592static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003593PySSL_RAND(int len, int pseudo)
3594{
3595 int ok;
3596 PyObject *bytes;
3597 unsigned long err;
3598 const char *errstr;
3599 PyObject *v;
3600
Victor Stinner1e81a392013-12-19 16:47:04 +01003601 if (len < 0) {
3602 PyErr_SetString(PyExc_ValueError, "num must be positive");
3603 return NULL;
3604 }
3605
Victor Stinner99c8b162011-05-24 12:05:19 +02003606 bytes = PyBytes_FromStringAndSize(NULL, len);
3607 if (bytes == NULL)
3608 return NULL;
3609 if (pseudo) {
3610 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3611 if (ok == 0 || ok == 1)
3612 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3613 }
3614 else {
3615 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3616 if (ok == 1)
3617 return bytes;
3618 }
3619 Py_DECREF(bytes);
3620
3621 err = ERR_get_error();
3622 errstr = ERR_reason_error_string(err);
3623 v = Py_BuildValue("(ks)", err, errstr);
3624 if (v != NULL) {
3625 PyErr_SetObject(PySSLErrorObject, v);
3626 Py_DECREF(v);
3627 }
3628 return NULL;
3629}
3630
3631static PyObject *
3632PySSL_RAND_bytes(PyObject *self, PyObject *args)
3633{
3634 int len;
3635 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3636 return NULL;
3637 return PySSL_RAND(len, 0);
3638}
3639
3640PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3641"RAND_bytes(n) -> bytes\n\
3642\n\
3643Generate n cryptographically strong pseudo-random bytes.");
3644
3645static PyObject *
3646PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3647{
3648 int len;
3649 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3650 return NULL;
3651 return PySSL_RAND(len, 1);
3652}
3653
3654PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3655"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3656\n\
3657Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3658generated are cryptographically strong.");
3659
3660static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003661PySSL_RAND_status(PyObject *self)
3662{
Christian Heimes217cfd12007-12-02 14:31:20 +00003663 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003664}
3665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003666PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003667"RAND_status() -> 0 or 1\n\
3668\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003669Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3670It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3671using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003672
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003673#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003674static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003675PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003676{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003677 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003678 int bytes;
3679
Jesus Ceac8754a12012-09-11 02:00:58 +02003680 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003681 PyUnicode_FSConverter, &path))
3682 return NULL;
3683
3684 bytes = RAND_egd(PyBytes_AsString(path));
3685 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003686 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003687 PyErr_SetString(PySSLErrorObject,
3688 "EGD connection failed or EGD did not return "
3689 "enough data to seed the PRNG");
3690 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003691 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003692 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003693}
3694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003695PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003696"RAND_egd(path) -> bytes\n\
3697\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003698Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3699Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003700fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003701#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003702
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003703
Christian Heimes6d7ad132013-06-09 18:02:55 +02003704PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3705"get_default_verify_paths() -> tuple\n\
3706\n\
3707Return search paths and environment vars that are used by SSLContext's\n\
3708set_default_verify_paths() to load default CAs. The values are\n\
3709'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3710
3711static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003712PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003713{
3714 PyObject *ofile_env = NULL;
3715 PyObject *ofile = NULL;
3716 PyObject *odir_env = NULL;
3717 PyObject *odir = NULL;
3718
3719#define convert(info, target) { \
3720 const char *tmp = (info); \
3721 target = NULL; \
3722 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3723 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3724 target = PyBytes_FromString(tmp); } \
3725 if (!target) goto error; \
3726 } while(0)
3727
3728 convert(X509_get_default_cert_file_env(), ofile_env);
3729 convert(X509_get_default_cert_file(), ofile);
3730 convert(X509_get_default_cert_dir_env(), odir_env);
3731 convert(X509_get_default_cert_dir(), odir);
3732#undef convert
3733
Christian Heimes200bb1b2013-06-14 15:14:29 +02003734 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003735
3736 error:
3737 Py_XDECREF(ofile_env);
3738 Py_XDECREF(ofile);
3739 Py_XDECREF(odir_env);
3740 Py_XDECREF(odir);
3741 return NULL;
3742}
3743
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003744static PyObject*
3745asn1obj2py(ASN1_OBJECT *obj)
3746{
3747 int nid;
3748 const char *ln, *sn;
3749 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003750 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003751
3752 nid = OBJ_obj2nid(obj);
3753 if (nid == NID_undef) {
3754 PyErr_Format(PyExc_ValueError, "Unknown object");
3755 return NULL;
3756 }
3757 sn = OBJ_nid2sn(nid);
3758 ln = OBJ_nid2ln(nid);
3759 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3760 if (buflen < 0) {
3761 _setSSLError(NULL, 0, __FILE__, __LINE__);
3762 return NULL;
3763 }
3764 if (buflen) {
3765 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3766 } else {
3767 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3768 }
3769}
3770
3771PyDoc_STRVAR(PySSL_txt2obj_doc,
3772"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3773\n\
3774Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3775objects are looked up by OID. With name=True short and long name are also\n\
3776matched.");
3777
3778static PyObject*
3779PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3780{
3781 char *kwlist[] = {"txt", "name", NULL};
3782 PyObject *result = NULL;
3783 char *txt;
3784 int name = 0;
3785 ASN1_OBJECT *obj;
3786
3787 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3788 kwlist, &txt, &name)) {
3789 return NULL;
3790 }
3791 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3792 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003793 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003794 return NULL;
3795 }
3796 result = asn1obj2py(obj);
3797 ASN1_OBJECT_free(obj);
3798 return result;
3799}
3800
3801PyDoc_STRVAR(PySSL_nid2obj_doc,
3802"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3803\n\
3804Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3805
3806static PyObject*
3807PySSL_nid2obj(PyObject *self, PyObject *args)
3808{
3809 PyObject *result = NULL;
3810 int nid;
3811 ASN1_OBJECT *obj;
3812
3813 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3814 return NULL;
3815 }
3816 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003817 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003818 return NULL;
3819 }
3820 obj = OBJ_nid2obj(nid);
3821 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003822 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003823 return NULL;
3824 }
3825 result = asn1obj2py(obj);
3826 ASN1_OBJECT_free(obj);
3827 return result;
3828}
3829
Christian Heimes46bebee2013-06-09 19:03:31 +02003830#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003831
3832static PyObject*
3833certEncodingType(DWORD encodingType)
3834{
3835 static PyObject *x509_asn = NULL;
3836 static PyObject *pkcs_7_asn = NULL;
3837
3838 if (x509_asn == NULL) {
3839 x509_asn = PyUnicode_InternFromString("x509_asn");
3840 if (x509_asn == NULL)
3841 return NULL;
3842 }
3843 if (pkcs_7_asn == NULL) {
3844 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3845 if (pkcs_7_asn == NULL)
3846 return NULL;
3847 }
3848 switch(encodingType) {
3849 case X509_ASN_ENCODING:
3850 Py_INCREF(x509_asn);
3851 return x509_asn;
3852 case PKCS_7_ASN_ENCODING:
3853 Py_INCREF(pkcs_7_asn);
3854 return pkcs_7_asn;
3855 default:
3856 return PyLong_FromLong(encodingType);
3857 }
3858}
3859
3860static PyObject*
3861parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3862{
3863 CERT_ENHKEY_USAGE *usage;
3864 DWORD size, error, i;
3865 PyObject *retval;
3866
3867 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3868 error = GetLastError();
3869 if (error == CRYPT_E_NOT_FOUND) {
3870 Py_RETURN_TRUE;
3871 }
3872 return PyErr_SetFromWindowsErr(error);
3873 }
3874
3875 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3876 if (usage == NULL) {
3877 return PyErr_NoMemory();
3878 }
3879
3880 /* Now get the actual enhanced usage property */
3881 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3882 PyMem_Free(usage);
3883 error = GetLastError();
3884 if (error == CRYPT_E_NOT_FOUND) {
3885 Py_RETURN_TRUE;
3886 }
3887 return PyErr_SetFromWindowsErr(error);
3888 }
3889 retval = PySet_New(NULL);
3890 if (retval == NULL) {
3891 goto error;
3892 }
3893 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3894 if (usage->rgpszUsageIdentifier[i]) {
3895 PyObject *oid;
3896 int err;
3897 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3898 if (oid == NULL) {
3899 Py_CLEAR(retval);
3900 goto error;
3901 }
3902 err = PySet_Add(retval, oid);
3903 Py_DECREF(oid);
3904 if (err == -1) {
3905 Py_CLEAR(retval);
3906 goto error;
3907 }
3908 }
3909 }
3910 error:
3911 PyMem_Free(usage);
3912 return retval;
3913}
3914
3915PyDoc_STRVAR(PySSL_enum_certificates_doc,
3916"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003917\n\
3918Retrieve certificates from Windows' cert store. store_name may be one of\n\
3919'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003920The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003921encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003922PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3923boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003924
Christian Heimes46bebee2013-06-09 19:03:31 +02003925static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003926PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003927{
Christian Heimes44109d72013-11-22 01:51:30 +01003928 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003929 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003930 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003931 PCCERT_CONTEXT pCertCtx = NULL;
3932 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003933 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003934
Christian Heimes44109d72013-11-22 01:51:30 +01003935 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3936 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003937 return NULL;
3938 }
Christian Heimes44109d72013-11-22 01:51:30 +01003939 result = PyList_New(0);
3940 if (result == NULL) {
3941 return NULL;
3942 }
3943 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3944 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003945 Py_DECREF(result);
3946 return PyErr_SetFromWindowsErr(GetLastError());
3947 }
3948
Christian Heimes44109d72013-11-22 01:51:30 +01003949 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3950 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3951 pCertCtx->cbCertEncoded);
3952 if (!cert) {
3953 Py_CLEAR(result);
3954 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003955 }
Christian Heimes44109d72013-11-22 01:51:30 +01003956 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3957 Py_CLEAR(result);
3958 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003959 }
Christian Heimes44109d72013-11-22 01:51:30 +01003960 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3961 if (keyusage == Py_True) {
3962 Py_DECREF(keyusage);
3963 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003964 }
Christian Heimes44109d72013-11-22 01:51:30 +01003965 if (keyusage == NULL) {
3966 Py_CLEAR(result);
3967 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003968 }
Christian Heimes44109d72013-11-22 01:51:30 +01003969 if ((tup = PyTuple_New(3)) == NULL) {
3970 Py_CLEAR(result);
3971 break;
3972 }
3973 PyTuple_SET_ITEM(tup, 0, cert);
3974 cert = NULL;
3975 PyTuple_SET_ITEM(tup, 1, enc);
3976 enc = NULL;
3977 PyTuple_SET_ITEM(tup, 2, keyusage);
3978 keyusage = NULL;
3979 if (PyList_Append(result, tup) < 0) {
3980 Py_CLEAR(result);
3981 break;
3982 }
3983 Py_CLEAR(tup);
3984 }
3985 if (pCertCtx) {
3986 /* loop ended with an error, need to clean up context manually */
3987 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003988 }
3989
3990 /* In error cases cert, enc and tup may not be NULL */
3991 Py_XDECREF(cert);
3992 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003993 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003994 Py_XDECREF(tup);
3995
3996 if (!CertCloseStore(hStore, 0)) {
3997 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003998 Py_XDECREF(result);
3999 return PyErr_SetFromWindowsErr(GetLastError());
4000 }
4001 return result;
4002}
4003
4004PyDoc_STRVAR(PySSL_enum_crls_doc,
4005"enum_crls(store_name) -> []\n\
4006\n\
4007Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4008'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4009The function returns a list of (bytes, encoding_type) tuples. The\n\
4010encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4011PKCS_7_ASN_ENCODING.");
4012
4013static PyObject *
4014PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4015{
4016 char *kwlist[] = {"store_name", NULL};
4017 char *store_name;
4018 HCERTSTORE hStore = NULL;
4019 PCCRL_CONTEXT pCrlCtx = NULL;
4020 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4021 PyObject *result = NULL;
4022
4023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4024 kwlist, &store_name)) {
4025 return NULL;
4026 }
4027 result = PyList_New(0);
4028 if (result == NULL) {
4029 return NULL;
4030 }
4031 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4032 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004033 Py_DECREF(result);
4034 return PyErr_SetFromWindowsErr(GetLastError());
4035 }
Christian Heimes44109d72013-11-22 01:51:30 +01004036
4037 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4038 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4039 pCrlCtx->cbCrlEncoded);
4040 if (!crl) {
4041 Py_CLEAR(result);
4042 break;
4043 }
4044 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4045 Py_CLEAR(result);
4046 break;
4047 }
4048 if ((tup = PyTuple_New(2)) == NULL) {
4049 Py_CLEAR(result);
4050 break;
4051 }
4052 PyTuple_SET_ITEM(tup, 0, crl);
4053 crl = NULL;
4054 PyTuple_SET_ITEM(tup, 1, enc);
4055 enc = NULL;
4056
4057 if (PyList_Append(result, tup) < 0) {
4058 Py_CLEAR(result);
4059 break;
4060 }
4061 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004062 }
Christian Heimes44109d72013-11-22 01:51:30 +01004063 if (pCrlCtx) {
4064 /* loop ended with an error, need to clean up context manually */
4065 CertFreeCRLContext(pCrlCtx);
4066 }
4067
4068 /* In error cases cert, enc and tup may not be NULL */
4069 Py_XDECREF(crl);
4070 Py_XDECREF(enc);
4071 Py_XDECREF(tup);
4072
4073 if (!CertCloseStore(hStore, 0)) {
4074 /* This error case might shadow another exception.*/
4075 Py_XDECREF(result);
4076 return PyErr_SetFromWindowsErr(GetLastError());
4077 }
4078 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004079}
Christian Heimes44109d72013-11-22 01:51:30 +01004080
4081#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004082
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004083/* List of functions exported by this module. */
4084
4085static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004086 {"_test_decode_cert", PySSL_test_decode_certificate,
4087 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004088 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4089 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004090 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4091 PySSL_RAND_bytes_doc},
4092 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4093 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004094#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004095 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004096 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004097#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004098 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4099 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004100 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004101 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004102#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004103 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4104 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4105 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4106 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004107#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004108 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4109 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4110 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4111 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004112 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004113};
4114
4115
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004116#ifdef WITH_THREAD
4117
4118/* an implementation of OpenSSL threading operations in terms
4119 of the Python C thread library */
4120
4121static PyThread_type_lock *_ssl_locks = NULL;
4122
Christian Heimes4d98ca92013-08-19 17:36:29 +02004123#if OPENSSL_VERSION_NUMBER >= 0x10000000
4124/* use new CRYPTO_THREADID API. */
4125static void
4126_ssl_threadid_callback(CRYPTO_THREADID *id)
4127{
4128 CRYPTO_THREADID_set_numeric(id,
4129 (unsigned long)PyThread_get_thread_ident());
4130}
4131#else
4132/* deprecated CRYPTO_set_id_callback() API. */
4133static unsigned long
4134_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004135 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004136}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004137#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004138
Bill Janssen6e027db2007-11-15 22:23:56 +00004139static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004140 (int mode, int n, const char *file, int line) {
4141 /* this function is needed to perform locking on shared data
4142 structures. (Note that OpenSSL uses a number of global data
4143 structures that will be implicitly shared whenever multiple
4144 threads use OpenSSL.) Multi-threaded applications will
4145 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004147 locking_function() must be able to handle up to
4148 CRYPTO_num_locks() different mutex locks. It sets the n-th
4149 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004151 file and line are the file number of the function setting the
4152 lock. They can be useful for debugging.
4153 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004155 if ((_ssl_locks == NULL) ||
4156 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4157 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004159 if (mode & CRYPTO_LOCK) {
4160 PyThread_acquire_lock(_ssl_locks[n], 1);
4161 } else {
4162 PyThread_release_lock(_ssl_locks[n]);
4163 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004164}
4165
4166static int _setup_ssl_threads(void) {
4167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004168 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004170 if (_ssl_locks == NULL) {
4171 _ssl_locks_count = CRYPTO_num_locks();
4172 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02004173 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004174 if (_ssl_locks == NULL)
4175 return 0;
4176 memset(_ssl_locks, 0,
4177 sizeof(PyThread_type_lock) * _ssl_locks_count);
4178 for (i = 0; i < _ssl_locks_count; i++) {
4179 _ssl_locks[i] = PyThread_allocate_lock();
4180 if (_ssl_locks[i] == NULL) {
4181 unsigned int j;
4182 for (j = 0; j < i; j++) {
4183 PyThread_free_lock(_ssl_locks[j]);
4184 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004185 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004186 return 0;
4187 }
4188 }
4189 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004190#if OPENSSL_VERSION_NUMBER >= 0x10000000
4191 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4192#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004193 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004194#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004195 }
4196 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004197}
4198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004199#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004201PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004202"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004203for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004204
Martin v. Löwis1a214512008-06-11 05:26:20 +00004205
4206static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004207 PyModuleDef_HEAD_INIT,
4208 "_ssl",
4209 module_doc,
4210 -1,
4211 PySSL_methods,
4212 NULL,
4213 NULL,
4214 NULL,
4215 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004216};
4217
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004218
4219static void
4220parse_openssl_version(unsigned long libver,
4221 unsigned int *major, unsigned int *minor,
4222 unsigned int *fix, unsigned int *patch,
4223 unsigned int *status)
4224{
4225 *status = libver & 0xF;
4226 libver >>= 4;
4227 *patch = libver & 0xFF;
4228 libver >>= 8;
4229 *fix = libver & 0xFF;
4230 libver >>= 8;
4231 *minor = libver & 0xFF;
4232 libver >>= 8;
4233 *major = libver & 0xFF;
4234}
4235
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004236PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004237PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004238{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004239 PyObject *m, *d, *r;
4240 unsigned long libver;
4241 unsigned int major, minor, fix, patch, status;
4242 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004243 struct py_ssl_error_code *errcode;
4244 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004245
Antoine Pitrou152efa22010-05-16 18:19:27 +00004246 if (PyType_Ready(&PySSLContext_Type) < 0)
4247 return NULL;
4248 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004249 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004250 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4251 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004252
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004253 m = PyModule_Create(&_sslmodule);
4254 if (m == NULL)
4255 return NULL;
4256 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004257
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004258 /* Load _socket module and its C API */
4259 socket_api = PySocketModule_ImportModuleAndAPI();
4260 if (!socket_api)
4261 return NULL;
4262 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004264 /* Init OpenSSL */
4265 SSL_load_error_strings();
4266 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004267#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004268 /* note that this will start threading if not already started */
4269 if (!_setup_ssl_threads()) {
4270 return NULL;
4271 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004273 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004275 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004276 sslerror_type_slots[0].pfunc = PyExc_OSError;
4277 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004278 if (PySSLErrorObject == NULL)
4279 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004280
Antoine Pitrou41032a62011-10-27 23:56:55 +02004281 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4282 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4283 PySSLErrorObject, NULL);
4284 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4285 "ssl.SSLWantReadError", SSLWantReadError_doc,
4286 PySSLErrorObject, NULL);
4287 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4288 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4289 PySSLErrorObject, NULL);
4290 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4291 "ssl.SSLSyscallError", SSLSyscallError_doc,
4292 PySSLErrorObject, NULL);
4293 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4294 "ssl.SSLEOFError", SSLEOFError_doc,
4295 PySSLErrorObject, NULL);
4296 if (PySSLZeroReturnErrorObject == NULL
4297 || PySSLWantReadErrorObject == NULL
4298 || PySSLWantWriteErrorObject == NULL
4299 || PySSLSyscallErrorObject == NULL
4300 || PySSLEOFErrorObject == NULL)
4301 return NULL;
4302 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4303 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4304 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4305 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4306 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4307 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004308 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004309 if (PyDict_SetItemString(d, "_SSLContext",
4310 (PyObject *)&PySSLContext_Type) != 0)
4311 return NULL;
4312 if (PyDict_SetItemString(d, "_SSLSocket",
4313 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004314 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004315 if (PyDict_SetItemString(d, "MemoryBIO",
4316 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4317 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004318 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4319 PY_SSL_ERROR_ZERO_RETURN);
4320 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4321 PY_SSL_ERROR_WANT_READ);
4322 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4323 PY_SSL_ERROR_WANT_WRITE);
4324 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4325 PY_SSL_ERROR_WANT_X509_LOOKUP);
4326 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4327 PY_SSL_ERROR_SYSCALL);
4328 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4329 PY_SSL_ERROR_SSL);
4330 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4331 PY_SSL_ERROR_WANT_CONNECT);
4332 /* non ssl.h errorcodes */
4333 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4334 PY_SSL_ERROR_EOF);
4335 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4336 PY_SSL_ERROR_INVALID_ERROR_CODE);
4337 /* cert requirements */
4338 PyModule_AddIntConstant(m, "CERT_NONE",
4339 PY_SSL_CERT_NONE);
4340 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4341 PY_SSL_CERT_OPTIONAL);
4342 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4343 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004344 /* CRL verification for verification_flags */
4345 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4346 0);
4347 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4348 X509_V_FLAG_CRL_CHECK);
4349 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4350 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4351 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4352 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004353
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004354 /* Alert Descriptions from ssl.h */
4355 /* note RESERVED constants no longer intended for use have been removed */
4356 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4357
4358#define ADD_AD_CONSTANT(s) \
4359 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4360 SSL_AD_##s)
4361
4362 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4363 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4364 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4365 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4366 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4367 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4368 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4369 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4370 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4371 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4372 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4373 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4374 ADD_AD_CONSTANT(UNKNOWN_CA);
4375 ADD_AD_CONSTANT(ACCESS_DENIED);
4376 ADD_AD_CONSTANT(DECODE_ERROR);
4377 ADD_AD_CONSTANT(DECRYPT_ERROR);
4378 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4379 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4380 ADD_AD_CONSTANT(INTERNAL_ERROR);
4381 ADD_AD_CONSTANT(USER_CANCELLED);
4382 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004383 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004384#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4385 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4386#endif
4387#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4388 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4389#endif
4390#ifdef SSL_AD_UNRECOGNIZED_NAME
4391 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4392#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004393#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4394 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4395#endif
4396#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4397 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4398#endif
4399#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4400 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4401#endif
4402
4403#undef ADD_AD_CONSTANT
4404
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004405 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004406#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004407 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4408 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004409#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004410#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004411 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4412 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004413#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004414 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4415 PY_SSL_VERSION_SSL23);
4416 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4417 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004418#if HAVE_TLSv1_2
4419 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4420 PY_SSL_VERSION_TLS1_1);
4421 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4422 PY_SSL_VERSION_TLS1_2);
4423#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004424
Antoine Pitroub5218772010-05-21 09:56:06 +00004425 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004426 PyModule_AddIntConstant(m, "OP_ALL",
4427 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004428 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4429 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4430 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004431#if HAVE_TLSv1_2
4432 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4433 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4434#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004435 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4436 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004437 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004438#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004439 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004440#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004441#ifdef SSL_OP_NO_COMPRESSION
4442 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4443 SSL_OP_NO_COMPRESSION);
4444#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004445
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004446#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004447 r = Py_True;
4448#else
4449 r = Py_False;
4450#endif
4451 Py_INCREF(r);
4452 PyModule_AddObject(m, "HAS_SNI", r);
4453
Antoine Pitroud6494802011-07-21 01:11:30 +02004454 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004455 Py_INCREF(r);
4456 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4457
Antoine Pitrou501da612011-12-21 09:27:41 +01004458#ifdef OPENSSL_NO_ECDH
4459 r = Py_False;
4460#else
4461 r = Py_True;
4462#endif
4463 Py_INCREF(r);
4464 PyModule_AddObject(m, "HAS_ECDH", r);
4465
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004466#ifdef OPENSSL_NPN_NEGOTIATED
4467 r = Py_True;
4468#else
4469 r = Py_False;
4470#endif
4471 Py_INCREF(r);
4472 PyModule_AddObject(m, "HAS_NPN", r);
4473
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004474 /* Mappings for error codes */
4475 err_codes_to_names = PyDict_New();
4476 err_names_to_codes = PyDict_New();
4477 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4478 return NULL;
4479 errcode = error_codes;
4480 while (errcode->mnemonic != NULL) {
4481 PyObject *mnemo, *key;
4482 mnemo = PyUnicode_FromString(errcode->mnemonic);
4483 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4484 if (mnemo == NULL || key == NULL)
4485 return NULL;
4486 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4487 return NULL;
4488 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4489 return NULL;
4490 Py_DECREF(key);
4491 Py_DECREF(mnemo);
4492 errcode++;
4493 }
4494 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4495 return NULL;
4496 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4497 return NULL;
4498
4499 lib_codes_to_names = PyDict_New();
4500 if (lib_codes_to_names == NULL)
4501 return NULL;
4502 libcode = library_codes;
4503 while (libcode->library != NULL) {
4504 PyObject *mnemo, *key;
4505 key = PyLong_FromLong(libcode->code);
4506 mnemo = PyUnicode_FromString(libcode->library);
4507 if (key == NULL || mnemo == NULL)
4508 return NULL;
4509 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4510 return NULL;
4511 Py_DECREF(key);
4512 Py_DECREF(mnemo);
4513 libcode++;
4514 }
4515 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4516 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004518 /* OpenSSL version */
4519 /* SSLeay() gives us the version of the library linked against,
4520 which could be different from the headers version.
4521 */
4522 libver = SSLeay();
4523 r = PyLong_FromUnsignedLong(libver);
4524 if (r == NULL)
4525 return NULL;
4526 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4527 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004528 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004529 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4530 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4531 return NULL;
4532 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4533 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4534 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004535
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004536 libver = OPENSSL_VERSION_NUMBER;
4537 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4538 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4539 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4540 return NULL;
4541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004542 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004543}