blob: 596966323e38c2b959348c60e7415f9606357278 [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
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001363static PyObject *
1364cipher_to_tuple(const SSL_CIPHER *cipher)
1365{
1366 const char *cipher_name, *cipher_protocol;
1367 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 if (retval == NULL)
1369 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001371 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001373 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 PyTuple_SET_ITEM(retval, 0, Py_None);
1375 } else {
1376 v = PyUnicode_FromString(cipher_name);
1377 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001378 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 PyTuple_SET_ITEM(retval, 0, v);
1380 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001381
1382 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001384 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 PyTuple_SET_ITEM(retval, 1, Py_None);
1386 } else {
1387 v = PyUnicode_FromString(cipher_protocol);
1388 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001389 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 PyTuple_SET_ITEM(retval, 1, v);
1391 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001392
1393 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001395 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001399
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001400 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 Py_DECREF(retval);
1402 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403}
1404
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001405static PyObject *PySSL_shared_ciphers(PySSLSocket *self)
1406{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001407 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001408 STACK_OF(SSL_CIPHER) *ciphers;
1409 int i;
1410 PyObject *res;
1411
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001412 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001413 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001414 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001415 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1416 if (!res)
1417 return NULL;
1418 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1419 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1420 if (!tup) {
1421 Py_DECREF(res);
1422 return NULL;
1423 }
1424 PyList_SET_ITEM(res, i, tup);
1425 }
1426 return res;
1427}
1428
1429static PyObject *PySSL_cipher (PySSLSocket *self)
1430{
1431 const SSL_CIPHER *current;
1432
1433 if (self->ssl == NULL)
1434 Py_RETURN_NONE;
1435 current = SSL_get_current_cipher(self->ssl);
1436 if (current == NULL)
1437 Py_RETURN_NONE;
1438 return cipher_to_tuple(current);
1439}
1440
Antoine Pitrou47e40422014-09-04 21:00:10 +02001441static PyObject *PySSL_version(PySSLSocket *self)
1442{
1443 const char *version;
1444
1445 if (self->ssl == NULL)
1446 Py_RETURN_NONE;
1447 version = SSL_get_version(self->ssl);
1448 if (!strcmp(version, "unknown"))
1449 Py_RETURN_NONE;
1450 return PyUnicode_FromString(version);
1451}
1452
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001453#ifdef OPENSSL_NPN_NEGOTIATED
1454static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1455 const unsigned char *out;
1456 unsigned int outlen;
1457
Victor Stinner4569cd52013-06-23 14:58:43 +02001458 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001459 &out, &outlen);
1460
1461 if (out == NULL)
1462 Py_RETURN_NONE;
1463 return PyUnicode_FromStringAndSize((char *) out, outlen);
1464}
1465#endif
1466
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001467static PyObject *PySSL_compression(PySSLSocket *self) {
1468#ifdef OPENSSL_NO_COMP
1469 Py_RETURN_NONE;
1470#else
1471 const COMP_METHOD *comp_method;
1472 const char *short_name;
1473
1474 if (self->ssl == NULL)
1475 Py_RETURN_NONE;
1476 comp_method = SSL_get_current_compression(self->ssl);
1477 if (comp_method == NULL || comp_method->type == NID_undef)
1478 Py_RETURN_NONE;
1479 short_name = OBJ_nid2sn(comp_method->type);
1480 if (short_name == NULL)
1481 Py_RETURN_NONE;
1482 return PyUnicode_DecodeFSDefault(short_name);
1483#endif
1484}
1485
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001486static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1487 Py_INCREF(self->ctx);
1488 return self->ctx;
1489}
1490
1491static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1492 void *closure) {
1493
1494 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001495#if !HAVE_SNI
1496 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1497 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001498 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001499#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001500 Py_INCREF(value);
1501 Py_DECREF(self->ctx);
1502 self->ctx = (PySSLContext *) value;
1503 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001504#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001505 } else {
1506 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1507 return -1;
1508 }
1509
1510 return 0;
1511}
1512
1513PyDoc_STRVAR(PySSL_set_context_doc,
1514"_setter_context(ctx)\n\
1515\
1516This changes the context associated with the SSLSocket. This is typically\n\
1517used from within a callback function set by the set_servername_callback\n\
1518on the SSLContext to change the certificate information associated with the\n\
1519SSLSocket before the cryptographic exchange handshake messages\n");
1520
1521
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001522static PyObject *
1523PySSL_get_server_side(PySSLSocket *self, void *c)
1524{
1525 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1526}
1527
1528PyDoc_STRVAR(PySSL_get_server_side_doc,
1529"Whether this is a server-side socket.");
1530
1531static PyObject *
1532PySSL_get_server_hostname(PySSLSocket *self, void *c)
1533{
1534 if (self->server_hostname == NULL)
1535 Py_RETURN_NONE;
1536 Py_INCREF(self->server_hostname);
1537 return self->server_hostname;
1538}
1539
1540PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1541"The currently set server hostname (for SNI).");
1542
1543static PyObject *
1544PySSL_get_owner(PySSLSocket *self, void *c)
1545{
1546 PyObject *owner;
1547
1548 if (self->owner == NULL)
1549 Py_RETURN_NONE;
1550
1551 owner = PyWeakref_GetObject(self->owner);
1552 Py_INCREF(owner);
1553 return owner;
1554}
1555
1556static int
1557PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1558{
1559 Py_XDECREF(self->owner);
1560 self->owner = PyWeakref_NewRef(value, NULL);
1561 if (self->owner == NULL)
1562 return -1;
1563 return 0;
1564}
1565
1566PyDoc_STRVAR(PySSL_get_owner_doc,
1567"The Python-level owner of this object.\
1568Passed as \"self\" in servername callback.");
1569
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001570
Antoine Pitrou152efa22010-05-16 18:19:27 +00001571static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001572{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 if (self->peer_cert) /* Possible not to have one? */
1574 X509_free (self->peer_cert);
1575 if (self->ssl)
1576 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001578 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001579 Py_XDECREF(self->server_hostname);
1580 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001582}
1583
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001584/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001585 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001586 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001587 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001588
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001589static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001590check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001591{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 fd_set fds;
1593 struct timeval tv;
1594 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001596 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001597 if ((s == NULL) || (s->sock_timeout == 0.0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 return SOCKET_IS_NONBLOCKING;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001599 else if (s->sock_timeout < 0.0)
1600 return SOCKET_IS_BLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 /* Guard against closed socket */
1603 if (s->sock_fd < 0)
1604 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 /* Prefer poll, if available, since you can poll() any fd
1607 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001608#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 {
1610 struct pollfd pollfd;
1611 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 pollfd.fd = s->sock_fd;
1614 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 /* s->sock_timeout is in seconds, timeout in ms */
1617 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1618 PySSL_BEGIN_ALLOW_THREADS
1619 rc = poll(&pollfd, 1, timeout);
1620 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 goto normal_return;
1623 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001624#endif
1625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001627 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 /* Construct the arguments to select */
1631 tv.tv_sec = (int)s->sock_timeout;
1632 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1633 FD_ZERO(&fds);
1634 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 /* See if the socket is ready */
1637 PySSL_BEGIN_ALLOW_THREADS
1638 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001639 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1640 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001642 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1643 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001645
Bill Janssen6e027db2007-11-15 22:23:56 +00001646#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001648#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001649 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1650 (when we are able to write or when there's something to read) */
1651 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001652}
1653
Antoine Pitrou152efa22010-05-16 18:19:27 +00001654static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001655{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001656 Py_buffer buf;
1657 int len;
1658 int sockstate;
1659 int err;
1660 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001661 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001662
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001663 if (sock != NULL) {
1664 if (((PyObject*)sock) == Py_None) {
1665 _setSSLError("Underlying socket connection gone",
1666 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1667 return NULL;
1668 }
1669 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 }
1671
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001672 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001673 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001675 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676
Victor Stinner6efa9652013-06-25 00:42:31 +02001677 if (buf.len > INT_MAX) {
1678 PyErr_Format(PyExc_OverflowError,
1679 "string longer than %d bytes", INT_MAX);
1680 goto error;
1681 }
1682
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001683 if (sock != NULL) {
1684 /* just in case the blocking state of the socket has been changed */
1685 nonblocking = (sock->sock_timeout >= 0.0);
1686 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1687 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1688 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689
1690 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1691 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001692 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 "The write operation timed out");
1694 goto error;
1695 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1696 PyErr_SetString(PySSLErrorObject,
1697 "Underlying socket has been closed.");
1698 goto error;
1699 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1700 PyErr_SetString(PySSLErrorObject,
1701 "Underlying socket too large for select().");
1702 goto error;
1703 }
1704 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001706 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 err = SSL_get_error(self->ssl, len);
1708 PySSL_END_ALLOW_THREADS
1709 if (PyErr_CheckSignals()) {
1710 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001711 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001713 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001715 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716 } else {
1717 sockstate = SOCKET_OPERATION_OK;
1718 }
1719 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001720 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 "The write operation timed out");
1722 goto error;
1723 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1724 PyErr_SetString(PySSLErrorObject,
1725 "Underlying socket has been closed.");
1726 goto error;
1727 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1728 break;
1729 }
1730 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001731
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001732 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 PyBuffer_Release(&buf);
1734 if (len > 0)
1735 return PyLong_FromLong(len);
1736 else
1737 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001738
1739error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001740 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 PyBuffer_Release(&buf);
1742 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001743}
1744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001745PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001746"write(s) -> len\n\
1747\n\
1748Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001749of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001750
Antoine Pitrou152efa22010-05-16 18:19:27 +00001751static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001752{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 PySSL_BEGIN_ALLOW_THREADS
1756 count = SSL_pending(self->ssl);
1757 PySSL_END_ALLOW_THREADS
1758 if (count < 0)
1759 return PySSL_SetError(self, count, __FILE__, __LINE__);
1760 else
1761 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001762}
1763
1764PyDoc_STRVAR(PySSL_SSLpending_doc,
1765"pending() -> count\n\
1766\n\
1767Returns the number of already decrypted bytes available for read,\n\
1768pending on the connection.\n");
1769
Antoine Pitrou152efa22010-05-16 18:19:27 +00001770static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001771{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 PyObject *dest = NULL;
1773 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001775 int len, count;
1776 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001777 int sockstate;
1778 int err;
1779 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001780 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001781
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001782 if (sock != NULL) {
1783 if (((PyObject*)sock) == Py_None) {
1784 _setSSLError("Underlying socket connection gone",
1785 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1786 return NULL;
1787 }
1788 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 }
1790
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001791 buf.obj = NULL;
1792 buf.buf = NULL;
1793 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001794 goto error;
1795
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001796 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1797 dest = PyBytes_FromStringAndSize(NULL, len);
1798 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001799 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001800 mem = PyBytes_AS_STRING(dest);
1801 }
1802 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001804 mem = buf.buf;
1805 if (len <= 0 || len > buf.len) {
1806 len = (int) buf.len;
1807 if (buf.len != len) {
1808 PyErr_SetString(PyExc_OverflowError,
1809 "maximum length can't fit in a C 'int'");
1810 goto error;
1811 }
1812 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 }
1814
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001815 if (sock != NULL) {
1816 /* just in case the blocking state of the socket has been changed */
1817 nonblocking = (sock->sock_timeout >= 0.0);
1818 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1819 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1820 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821
1822 /* first check if there are bytes ready to be read */
1823 PySSL_BEGIN_ALLOW_THREADS
1824 count = SSL_pending(self->ssl);
1825 PySSL_END_ALLOW_THREADS
1826
1827 if (!count) {
1828 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1829 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001830 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 "The read operation timed out");
1832 goto error;
1833 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1834 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001835 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 goto error;
1837 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1838 count = 0;
1839 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001840 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 }
1842 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 PySSL_BEGIN_ALLOW_THREADS
1844 count = SSL_read(self->ssl, mem, len);
1845 err = SSL_get_error(self->ssl, count);
1846 PySSL_END_ALLOW_THREADS
1847 if (PyErr_CheckSignals())
1848 goto error;
1849 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001850 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001852 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1854 (SSL_get_shutdown(self->ssl) ==
1855 SSL_RECEIVED_SHUTDOWN))
1856 {
1857 count = 0;
1858 goto done;
1859 } else {
1860 sockstate = SOCKET_OPERATION_OK;
1861 }
1862 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001863 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 "The read operation timed out");
1865 goto error;
1866 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1867 break;
1868 }
1869 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1870 if (count <= 0) {
1871 PySSL_SetError(self, count, __FILE__, __LINE__);
1872 goto error;
1873 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001874
1875done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001876 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001878 _PyBytes_Resize(&dest, count);
1879 return dest;
1880 }
1881 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 PyBuffer_Release(&buf);
1883 return PyLong_FromLong(count);
1884 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001885
1886error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001887 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001888 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001889 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001890 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001893}
1894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001895PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001896"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001897\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001898Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001899
Antoine Pitrou152efa22010-05-16 18:19:27 +00001900static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001901{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 int err, ssl_err, sockstate, nonblocking;
1903 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001904 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001905
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001906 if (sock != NULL) {
1907 /* Guard against closed socket */
1908 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1909 _setSSLError("Underlying socket connection gone",
1910 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1911 return NULL;
1912 }
1913 Py_INCREF(sock);
1914
1915 /* Just in case the blocking state of the socket has been changed */
1916 nonblocking = (sock->sock_timeout >= 0.0);
1917 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1918 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920
1921 while (1) {
1922 PySSL_BEGIN_ALLOW_THREADS
1923 /* Disable read-ahead so that unwrap can work correctly.
1924 * Otherwise OpenSSL might read in too much data,
1925 * eating clear text data that happens to be
1926 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001927 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 * function is used and the shutdown_seen_zero != 0
1929 * condition is met.
1930 */
1931 if (self->shutdown_seen_zero)
1932 SSL_set_read_ahead(self->ssl, 0);
1933 err = SSL_shutdown(self->ssl);
1934 PySSL_END_ALLOW_THREADS
1935 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1936 if (err > 0)
1937 break;
1938 if (err == 0) {
1939 /* Don't loop endlessly; instead preserve legacy
1940 behaviour of trying SSL_shutdown() only twice.
1941 This looks necessary for OpenSSL < 0.9.8m */
1942 if (++zeros > 1)
1943 break;
1944 /* Shutdown was sent, now try receiving */
1945 self->shutdown_seen_zero = 1;
1946 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001947 }
1948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 /* Possibly retry shutdown until timeout or failure */
1950 ssl_err = SSL_get_error(self->ssl, err);
1951 if (ssl_err == SSL_ERROR_WANT_READ)
1952 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1953 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1954 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1955 else
1956 break;
1957 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1958 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001959 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 "The read operation timed out");
1961 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001962 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001964 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 }
1966 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1967 PyErr_SetString(PySSLErrorObject,
1968 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001969 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 }
1971 else if (sockstate != SOCKET_OPERATION_OK)
1972 /* Retain the SSL error code */
1973 break;
1974 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001975
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001976 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001977 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001980 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001981 /* It's already INCREF'ed */
1982 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001983 else
1984 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001985
1986error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001987 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001988 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001989}
1990
1991PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1992"shutdown(s) -> socket\n\
1993\n\
1994Does the SSL shutdown handshake with the remote end, and returns\n\
1995the underlying socket object.");
1996
Antoine Pitroud6494802011-07-21 01:11:30 +02001997static PyObject *
1998PySSL_tls_unique_cb(PySSLSocket *self)
1999{
2000 PyObject *retval = NULL;
2001 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002002 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002003
2004 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2005 /* if session is resumed XOR we are the client */
2006 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2007 }
2008 else {
2009 /* if a new session XOR we are the server */
2010 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2011 }
2012
2013 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002014 if (len == 0)
2015 Py_RETURN_NONE;
2016
2017 retval = PyBytes_FromStringAndSize(buf, len);
2018
2019 return retval;
2020}
2021
2022PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2023"tls_unique_cb() -> bytes\n\
2024\n\
2025Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2026\n\
2027If the TLS handshake is not yet complete, None is returned");
2028
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002029static PyGetSetDef ssl_getsetlist[] = {
2030 {"context", (getter) PySSL_get_context,
2031 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002032 {"server_side", (getter) PySSL_get_server_side, NULL,
2033 PySSL_get_server_side_doc},
2034 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2035 PySSL_get_server_hostname_doc},
2036 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2037 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002038 {NULL}, /* sentinel */
2039};
2040
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002041static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002042 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2043 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2044 PySSL_SSLwrite_doc},
2045 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2046 PySSL_SSLread_doc},
2047 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2048 PySSL_SSLpending_doc},
2049 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2050 PySSL_peercert_doc},
2051 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002052 {"shared_ciphers", (PyCFunction)PySSL_shared_ciphers, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002053 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002054#ifdef OPENSSL_NPN_NEGOTIATED
2055 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2056#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002057 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002058 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2059 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002060 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2061 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002062 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002063};
2064
Antoine Pitrou152efa22010-05-16 18:19:27 +00002065static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002067 "_ssl._SSLSocket", /*tp_name*/
2068 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002069 0, /*tp_itemsize*/
2070 /* methods */
2071 (destructor)PySSL_dealloc, /*tp_dealloc*/
2072 0, /*tp_print*/
2073 0, /*tp_getattr*/
2074 0, /*tp_setattr*/
2075 0, /*tp_reserved*/
2076 0, /*tp_repr*/
2077 0, /*tp_as_number*/
2078 0, /*tp_as_sequence*/
2079 0, /*tp_as_mapping*/
2080 0, /*tp_hash*/
2081 0, /*tp_call*/
2082 0, /*tp_str*/
2083 0, /*tp_getattro*/
2084 0, /*tp_setattro*/
2085 0, /*tp_as_buffer*/
2086 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2087 0, /*tp_doc*/
2088 0, /*tp_traverse*/
2089 0, /*tp_clear*/
2090 0, /*tp_richcompare*/
2091 0, /*tp_weaklistoffset*/
2092 0, /*tp_iter*/
2093 0, /*tp_iternext*/
2094 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002095 0, /*tp_members*/
2096 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002097};
2098
Antoine Pitrou152efa22010-05-16 18:19:27 +00002099
2100/*
2101 * _SSLContext objects
2102 */
2103
2104static PyObject *
2105context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2106{
2107 char *kwlist[] = {"protocol", NULL};
2108 PySSLContext *self;
2109 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002110 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002111 SSL_CTX *ctx = NULL;
2112
2113 if (!PyArg_ParseTupleAndKeywords(
2114 args, kwds, "i:_SSLContext", kwlist,
2115 &proto_version))
2116 return NULL;
2117
2118 PySSL_BEGIN_ALLOW_THREADS
2119 if (proto_version == PY_SSL_VERSION_TLS1)
2120 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002121#if HAVE_TLSv1_2
2122 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2123 ctx = SSL_CTX_new(TLSv1_1_method());
2124 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2125 ctx = SSL_CTX_new(TLSv1_2_method());
2126#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002127#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002128 else if (proto_version == PY_SSL_VERSION_SSL3)
2129 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002130#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002131#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002132 else if (proto_version == PY_SSL_VERSION_SSL2)
2133 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002134#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002135 else if (proto_version == PY_SSL_VERSION_SSL23)
2136 ctx = SSL_CTX_new(SSLv23_method());
2137 else
2138 proto_version = -1;
2139 PySSL_END_ALLOW_THREADS
2140
2141 if (proto_version == -1) {
2142 PyErr_SetString(PyExc_ValueError,
2143 "invalid protocol version");
2144 return NULL;
2145 }
2146 if (ctx == NULL) {
2147 PyErr_SetString(PySSLErrorObject,
2148 "failed to allocate SSL context");
2149 return NULL;
2150 }
2151
2152 assert(type != NULL && type->tp_alloc != NULL);
2153 self = (PySSLContext *) type->tp_alloc(type, 0);
2154 if (self == NULL) {
2155 SSL_CTX_free(ctx);
2156 return NULL;
2157 }
2158 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002159#ifdef OPENSSL_NPN_NEGOTIATED
2160 self->npn_protocols = NULL;
2161#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002162#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002163 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002164#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002165 /* Don't check host name by default */
2166 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002167 /* Defaults */
2168 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002169 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2170 if (proto_version != PY_SSL_VERSION_SSL2)
2171 options |= SSL_OP_NO_SSLv2;
2172 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002174#ifndef OPENSSL_NO_ECDH
2175 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2176 prime256v1 by default. This is Apache mod_ssl's initialization
2177 policy, so we should be safe. */
2178#if defined(SSL_CTX_set_ecdh_auto)
2179 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2180#else
2181 {
2182 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2183 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2184 EC_KEY_free(key);
2185 }
2186#endif
2187#endif
2188
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002189#define SID_CTX "Python"
2190 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2191 sizeof(SID_CTX));
2192#undef SID_CTX
2193
Antoine Pitrou152efa22010-05-16 18:19:27 +00002194 return (PyObject *)self;
2195}
2196
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002197static int
2198context_traverse(PySSLContext *self, visitproc visit, void *arg)
2199{
2200#ifndef OPENSSL_NO_TLSEXT
2201 Py_VISIT(self->set_hostname);
2202#endif
2203 return 0;
2204}
2205
2206static int
2207context_clear(PySSLContext *self)
2208{
2209#ifndef OPENSSL_NO_TLSEXT
2210 Py_CLEAR(self->set_hostname);
2211#endif
2212 return 0;
2213}
2214
Antoine Pitrou152efa22010-05-16 18:19:27 +00002215static void
2216context_dealloc(PySSLContext *self)
2217{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002218 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002219 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002220#ifdef OPENSSL_NPN_NEGOTIATED
2221 PyMem_Free(self->npn_protocols);
2222#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002223 Py_TYPE(self)->tp_free(self);
2224}
2225
2226static PyObject *
2227set_ciphers(PySSLContext *self, PyObject *args)
2228{
2229 int ret;
2230 const char *cipherlist;
2231
2232 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2233 return NULL;
2234 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2235 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002236 /* Clearing the error queue is necessary on some OpenSSL versions,
2237 otherwise the error will be reported again when another SSL call
2238 is done. */
2239 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002240 PyErr_SetString(PySSLErrorObject,
2241 "No cipher can be selected.");
2242 return NULL;
2243 }
2244 Py_RETURN_NONE;
2245}
2246
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002247#ifdef OPENSSL_NPN_NEGOTIATED
2248/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2249static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002250_advertiseNPN_cb(SSL *s,
2251 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002252 void *args)
2253{
2254 PySSLContext *ssl_ctx = (PySSLContext *) args;
2255
2256 if (ssl_ctx->npn_protocols == NULL) {
2257 *data = (unsigned char *) "";
2258 *len = 0;
2259 } else {
2260 *data = (unsigned char *) ssl_ctx->npn_protocols;
2261 *len = ssl_ctx->npn_protocols_len;
2262 }
2263
2264 return SSL_TLSEXT_ERR_OK;
2265}
2266/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2267static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002268_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002269 unsigned char **out, unsigned char *outlen,
2270 const unsigned char *server, unsigned int server_len,
2271 void *args)
2272{
2273 PySSLContext *ssl_ctx = (PySSLContext *) args;
2274
2275 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2276 int client_len;
2277
2278 if (client == NULL) {
2279 client = (unsigned char *) "";
2280 client_len = 0;
2281 } else {
2282 client_len = ssl_ctx->npn_protocols_len;
2283 }
2284
2285 SSL_select_next_proto(out, outlen,
2286 server, server_len,
2287 client, client_len);
2288
2289 return SSL_TLSEXT_ERR_OK;
2290}
2291#endif
2292
2293static PyObject *
2294_set_npn_protocols(PySSLContext *self, PyObject *args)
2295{
2296#ifdef OPENSSL_NPN_NEGOTIATED
2297 Py_buffer protos;
2298
2299 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2300 return NULL;
2301
Christian Heimes5cb31c92012-09-20 12:42:54 +02002302 if (self->npn_protocols != NULL) {
2303 PyMem_Free(self->npn_protocols);
2304 }
2305
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002306 self->npn_protocols = PyMem_Malloc(protos.len);
2307 if (self->npn_protocols == NULL) {
2308 PyBuffer_Release(&protos);
2309 return PyErr_NoMemory();
2310 }
2311 memcpy(self->npn_protocols, protos.buf, protos.len);
2312 self->npn_protocols_len = (int) protos.len;
2313
2314 /* set both server and client callbacks, because the context can
2315 * be used to create both types of sockets */
2316 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2317 _advertiseNPN_cb,
2318 self);
2319 SSL_CTX_set_next_proto_select_cb(self->ctx,
2320 _selectNPN_cb,
2321 self);
2322
2323 PyBuffer_Release(&protos);
2324 Py_RETURN_NONE;
2325#else
2326 PyErr_SetString(PyExc_NotImplementedError,
2327 "The NPN extension requires OpenSSL 1.0.1 or later.");
2328 return NULL;
2329#endif
2330}
2331
Antoine Pitrou152efa22010-05-16 18:19:27 +00002332static PyObject *
2333get_verify_mode(PySSLContext *self, void *c)
2334{
2335 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2336 case SSL_VERIFY_NONE:
2337 return PyLong_FromLong(PY_SSL_CERT_NONE);
2338 case SSL_VERIFY_PEER:
2339 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2340 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2341 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2342 }
2343 PyErr_SetString(PySSLErrorObject,
2344 "invalid return value from SSL_CTX_get_verify_mode");
2345 return NULL;
2346}
2347
2348static int
2349set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2350{
2351 int n, mode;
2352 if (!PyArg_Parse(arg, "i", &n))
2353 return -1;
2354 if (n == PY_SSL_CERT_NONE)
2355 mode = SSL_VERIFY_NONE;
2356 else if (n == PY_SSL_CERT_OPTIONAL)
2357 mode = SSL_VERIFY_PEER;
2358 else if (n == PY_SSL_CERT_REQUIRED)
2359 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2360 else {
2361 PyErr_SetString(PyExc_ValueError,
2362 "invalid value for verify_mode");
2363 return -1;
2364 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002365 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2366 PyErr_SetString(PyExc_ValueError,
2367 "Cannot set verify_mode to CERT_NONE when "
2368 "check_hostname is enabled.");
2369 return -1;
2370 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002371 SSL_CTX_set_verify(self->ctx, mode, NULL);
2372 return 0;
2373}
2374
2375static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002376get_verify_flags(PySSLContext *self, void *c)
2377{
2378 X509_STORE *store;
2379 unsigned long flags;
2380
2381 store = SSL_CTX_get_cert_store(self->ctx);
2382 flags = X509_VERIFY_PARAM_get_flags(store->param);
2383 return PyLong_FromUnsignedLong(flags);
2384}
2385
2386static int
2387set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2388{
2389 X509_STORE *store;
2390 unsigned long new_flags, flags, set, clear;
2391
2392 if (!PyArg_Parse(arg, "k", &new_flags))
2393 return -1;
2394 store = SSL_CTX_get_cert_store(self->ctx);
2395 flags = X509_VERIFY_PARAM_get_flags(store->param);
2396 clear = flags & ~new_flags;
2397 set = ~flags & new_flags;
2398 if (clear) {
2399 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2400 _setSSLError(NULL, 0, __FILE__, __LINE__);
2401 return -1;
2402 }
2403 }
2404 if (set) {
2405 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2406 _setSSLError(NULL, 0, __FILE__, __LINE__);
2407 return -1;
2408 }
2409 }
2410 return 0;
2411}
2412
2413static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002414get_options(PySSLContext *self, void *c)
2415{
2416 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2417}
2418
2419static int
2420set_options(PySSLContext *self, PyObject *arg, void *c)
2421{
2422 long new_opts, opts, set, clear;
2423 if (!PyArg_Parse(arg, "l", &new_opts))
2424 return -1;
2425 opts = SSL_CTX_get_options(self->ctx);
2426 clear = opts & ~new_opts;
2427 set = ~opts & new_opts;
2428 if (clear) {
2429#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2430 SSL_CTX_clear_options(self->ctx, clear);
2431#else
2432 PyErr_SetString(PyExc_ValueError,
2433 "can't clear options before OpenSSL 0.9.8m");
2434 return -1;
2435#endif
2436 }
2437 if (set)
2438 SSL_CTX_set_options(self->ctx, set);
2439 return 0;
2440}
2441
Christian Heimes1aa9a752013-12-02 02:41:19 +01002442static PyObject *
2443get_check_hostname(PySSLContext *self, void *c)
2444{
2445 return PyBool_FromLong(self->check_hostname);
2446}
2447
2448static int
2449set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2450{
2451 int check_hostname;
2452 if (!PyArg_Parse(arg, "p", &check_hostname))
2453 return -1;
2454 if (check_hostname &&
2455 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2456 PyErr_SetString(PyExc_ValueError,
2457 "check_hostname needs a SSL context with either "
2458 "CERT_OPTIONAL or CERT_REQUIRED");
2459 return -1;
2460 }
2461 self->check_hostname = check_hostname;
2462 return 0;
2463}
2464
2465
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002466typedef struct {
2467 PyThreadState *thread_state;
2468 PyObject *callable;
2469 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002470 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002471 int error;
2472} _PySSLPasswordInfo;
2473
2474static int
2475_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2476 const char *bad_type_error)
2477{
2478 /* Set the password and size fields of a _PySSLPasswordInfo struct
2479 from a unicode, bytes, or byte array object.
2480 The password field will be dynamically allocated and must be freed
2481 by the caller */
2482 PyObject *password_bytes = NULL;
2483 const char *data = NULL;
2484 Py_ssize_t size;
2485
2486 if (PyUnicode_Check(password)) {
2487 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2488 if (!password_bytes) {
2489 goto error;
2490 }
2491 data = PyBytes_AS_STRING(password_bytes);
2492 size = PyBytes_GET_SIZE(password_bytes);
2493 } else if (PyBytes_Check(password)) {
2494 data = PyBytes_AS_STRING(password);
2495 size = PyBytes_GET_SIZE(password);
2496 } else if (PyByteArray_Check(password)) {
2497 data = PyByteArray_AS_STRING(password);
2498 size = PyByteArray_GET_SIZE(password);
2499 } else {
2500 PyErr_SetString(PyExc_TypeError, bad_type_error);
2501 goto error;
2502 }
2503
Victor Stinner9ee02032013-06-23 15:08:23 +02002504 if (size > (Py_ssize_t)INT_MAX) {
2505 PyErr_Format(PyExc_ValueError,
2506 "password cannot be longer than %d bytes", INT_MAX);
2507 goto error;
2508 }
2509
Victor Stinner11ebff22013-07-07 17:07:52 +02002510 PyMem_Free(pw_info->password);
2511 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002512 if (!pw_info->password) {
2513 PyErr_SetString(PyExc_MemoryError,
2514 "unable to allocate password buffer");
2515 goto error;
2516 }
2517 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002518 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002519
2520 Py_XDECREF(password_bytes);
2521 return 1;
2522
2523error:
2524 Py_XDECREF(password_bytes);
2525 return 0;
2526}
2527
2528static int
2529_password_callback(char *buf, int size, int rwflag, void *userdata)
2530{
2531 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2532 PyObject *fn_ret = NULL;
2533
2534 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2535
2536 if (pw_info->callable) {
2537 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2538 if (!fn_ret) {
2539 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2540 core python API, so we could use it to add a frame here */
2541 goto error;
2542 }
2543
2544 if (!_pwinfo_set(pw_info, fn_ret,
2545 "password callback must return a string")) {
2546 goto error;
2547 }
2548 Py_CLEAR(fn_ret);
2549 }
2550
2551 if (pw_info->size > size) {
2552 PyErr_Format(PyExc_ValueError,
2553 "password cannot be longer than %d bytes", size);
2554 goto error;
2555 }
2556
2557 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2558 memcpy(buf, pw_info->password, pw_info->size);
2559 return pw_info->size;
2560
2561error:
2562 Py_XDECREF(fn_ret);
2563 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2564 pw_info->error = 1;
2565 return -1;
2566}
2567
Antoine Pitroub5218772010-05-21 09:56:06 +00002568static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002569load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2570{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002571 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2572 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002573 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002574 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2575 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2576 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002577 int r;
2578
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002579 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002580 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002581 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002582 "O|OO:load_cert_chain", kwlist,
2583 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002584 return NULL;
2585 if (keyfile == Py_None)
2586 keyfile = NULL;
2587 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2588 PyErr_SetString(PyExc_TypeError,
2589 "certfile should be a valid filesystem path");
2590 return NULL;
2591 }
2592 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2593 PyErr_SetString(PyExc_TypeError,
2594 "keyfile should be a valid filesystem path");
2595 goto error;
2596 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002597 if (password && password != Py_None) {
2598 if (PyCallable_Check(password)) {
2599 pw_info.callable = password;
2600 } else if (!_pwinfo_set(&pw_info, password,
2601 "password should be a string or callable")) {
2602 goto error;
2603 }
2604 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2605 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2606 }
2607 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002608 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2609 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002610 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002611 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002612 if (pw_info.error) {
2613 ERR_clear_error();
2614 /* the password callback has already set the error information */
2615 }
2616 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002617 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002618 PyErr_SetFromErrno(PyExc_IOError);
2619 }
2620 else {
2621 _setSSLError(NULL, 0, __FILE__, __LINE__);
2622 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002623 goto error;
2624 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002625 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002626 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002627 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2628 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002629 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2630 Py_CLEAR(keyfile_bytes);
2631 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002632 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002633 if (pw_info.error) {
2634 ERR_clear_error();
2635 /* the password callback has already set the error information */
2636 }
2637 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002638 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002639 PyErr_SetFromErrno(PyExc_IOError);
2640 }
2641 else {
2642 _setSSLError(NULL, 0, __FILE__, __LINE__);
2643 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002644 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002645 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002646 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002647 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002648 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002649 if (r != 1) {
2650 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002651 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002652 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002653 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2654 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002655 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002656 Py_RETURN_NONE;
2657
2658error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002659 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2660 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002661 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662 Py_XDECREF(keyfile_bytes);
2663 Py_XDECREF(certfile_bytes);
2664 return NULL;
2665}
2666
Christian Heimesefff7062013-11-21 03:35:02 +01002667/* internal helper function, returns -1 on error
2668 */
2669static int
2670_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2671 int filetype)
2672{
2673 BIO *biobuf = NULL;
2674 X509_STORE *store;
2675 int retval = 0, err, loaded = 0;
2676
2677 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2678
2679 if (len <= 0) {
2680 PyErr_SetString(PyExc_ValueError,
2681 "Empty certificate data");
2682 return -1;
2683 } else if (len > INT_MAX) {
2684 PyErr_SetString(PyExc_OverflowError,
2685 "Certificate data is too long.");
2686 return -1;
2687 }
2688
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002689 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002690 if (biobuf == NULL) {
2691 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2692 return -1;
2693 }
2694
2695 store = SSL_CTX_get_cert_store(self->ctx);
2696 assert(store != NULL);
2697
2698 while (1) {
2699 X509 *cert = NULL;
2700 int r;
2701
2702 if (filetype == SSL_FILETYPE_ASN1) {
2703 cert = d2i_X509_bio(biobuf, NULL);
2704 } else {
2705 cert = PEM_read_bio_X509(biobuf, NULL,
2706 self->ctx->default_passwd_callback,
2707 self->ctx->default_passwd_callback_userdata);
2708 }
2709 if (cert == NULL) {
2710 break;
2711 }
2712 r = X509_STORE_add_cert(store, cert);
2713 X509_free(cert);
2714 if (!r) {
2715 err = ERR_peek_last_error();
2716 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2717 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2718 /* cert already in hash table, not an error */
2719 ERR_clear_error();
2720 } else {
2721 break;
2722 }
2723 }
2724 loaded++;
2725 }
2726
2727 err = ERR_peek_last_error();
2728 if ((filetype == SSL_FILETYPE_ASN1) &&
2729 (loaded > 0) &&
2730 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2731 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2732 /* EOF ASN1 file, not an error */
2733 ERR_clear_error();
2734 retval = 0;
2735 } else if ((filetype == SSL_FILETYPE_PEM) &&
2736 (loaded > 0) &&
2737 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2738 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2739 /* EOF PEM file, not an error */
2740 ERR_clear_error();
2741 retval = 0;
2742 } else {
2743 _setSSLError(NULL, 0, __FILE__, __LINE__);
2744 retval = -1;
2745 }
2746
2747 BIO_free(biobuf);
2748 return retval;
2749}
2750
2751
Antoine Pitrou152efa22010-05-16 18:19:27 +00002752static PyObject *
2753load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2754{
Christian Heimesefff7062013-11-21 03:35:02 +01002755 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2756 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2758 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002759 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002761 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002763 "|OOO:load_verify_locations", kwlist,
2764 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002766
Antoine Pitrou152efa22010-05-16 18:19:27 +00002767 if (cafile == Py_None)
2768 cafile = NULL;
2769 if (capath == Py_None)
2770 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002771 if (cadata == Py_None)
2772 cadata = NULL;
2773
2774 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002775 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002776 "cafile, capath and cadata cannot be all omitted");
2777 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002778 }
2779 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2780 PyErr_SetString(PyExc_TypeError,
2781 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002782 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002783 }
2784 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785 PyErr_SetString(PyExc_TypeError,
2786 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002787 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788 }
Christian Heimesefff7062013-11-21 03:35:02 +01002789
2790 /* validata cadata type and load cadata */
2791 if (cadata) {
2792 Py_buffer buf;
2793 PyObject *cadata_ascii = NULL;
2794
2795 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2796 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2797 PyBuffer_Release(&buf);
2798 PyErr_SetString(PyExc_TypeError,
2799 "cadata should be a contiguous buffer with "
2800 "a single dimension");
2801 goto error;
2802 }
2803 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2804 PyBuffer_Release(&buf);
2805 if (r == -1) {
2806 goto error;
2807 }
2808 } else {
2809 PyErr_Clear();
2810 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2811 if (cadata_ascii == NULL) {
2812 PyErr_SetString(PyExc_TypeError,
2813 "cadata should be a ASCII string or a "
2814 "bytes-like object");
2815 goto error;
2816 }
2817 r = _add_ca_certs(self,
2818 PyBytes_AS_STRING(cadata_ascii),
2819 PyBytes_GET_SIZE(cadata_ascii),
2820 SSL_FILETYPE_PEM);
2821 Py_DECREF(cadata_ascii);
2822 if (r == -1) {
2823 goto error;
2824 }
2825 }
2826 }
2827
2828 /* load cafile or capath */
2829 if (cafile || capath) {
2830 if (cafile)
2831 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2832 if (capath)
2833 capath_buf = PyBytes_AS_STRING(capath_bytes);
2834 PySSL_BEGIN_ALLOW_THREADS
2835 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2836 PySSL_END_ALLOW_THREADS
2837 if (r != 1) {
2838 ok = 0;
2839 if (errno != 0) {
2840 ERR_clear_error();
2841 PyErr_SetFromErrno(PyExc_IOError);
2842 }
2843 else {
2844 _setSSLError(NULL, 0, __FILE__, __LINE__);
2845 }
2846 goto error;
2847 }
2848 }
2849 goto end;
2850
2851 error:
2852 ok = 0;
2853 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854 Py_XDECREF(cafile_bytes);
2855 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002856 if (ok) {
2857 Py_RETURN_NONE;
2858 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 return NULL;
2860 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002861}
2862
2863static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002864load_dh_params(PySSLContext *self, PyObject *filepath)
2865{
2866 FILE *f;
2867 DH *dh;
2868
Victor Stinnerdaf45552013-08-28 00:53:59 +02002869 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002870 if (f == NULL) {
2871 if (!PyErr_Occurred())
2872 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2873 return NULL;
2874 }
2875 errno = 0;
2876 PySSL_BEGIN_ALLOW_THREADS
2877 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002878 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002879 PySSL_END_ALLOW_THREADS
2880 if (dh == NULL) {
2881 if (errno != 0) {
2882 ERR_clear_error();
2883 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2884 }
2885 else {
2886 _setSSLError(NULL, 0, __FILE__, __LINE__);
2887 }
2888 return NULL;
2889 }
2890 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2891 _setSSLError(NULL, 0, __FILE__, __LINE__);
2892 DH_free(dh);
2893 Py_RETURN_NONE;
2894}
2895
2896static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2898{
Antoine Pitroud5323212010-10-22 18:19:07 +00002899 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002900 PySocketSockObject *sock;
2901 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002902 char *hostname = NULL;
2903 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002904
Antoine Pitroud5323212010-10-22 18:19:07 +00002905 /* server_hostname is either None (or absent), or to be encoded
2906 using the idna encoding. */
2907 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002908 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002909 &sock, &server_side,
2910 Py_TYPE(Py_None), &hostname_obj)) {
2911 PyErr_Clear();
2912 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2913 PySocketModule.Sock_Type,
2914 &sock, &server_side,
2915 "idna", &hostname))
2916 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002917 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002919 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2920 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002921 if (hostname != NULL)
2922 PyMem_Free(hostname);
2923 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002924}
2925
Antoine Pitroub0182c82010-10-12 20:09:02 +00002926static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002927context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
2928{
2929 char *kwlist[] = {"incoming", "outgoing", "server_side",
2930 "server_hostname", NULL};
2931 int server_side;
2932 char *hostname = NULL;
2933 PyObject *hostname_obj = Py_None, *res;
2934 PySSLMemoryBIO *incoming, *outgoing;
2935
2936 /* server_hostname is either None (or absent), or to be encoded
2937 using the idna encoding. */
2938 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
2939 &PySSLMemoryBIO_Type, &incoming,
2940 &PySSLMemoryBIO_Type, &outgoing,
2941 &server_side, &hostname_obj))
2942 return NULL;
2943 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002944 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
2945 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002946 }
2947
2948 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
2949 incoming, outgoing);
2950
2951 PyMem_Free(hostname);
2952 return res;
2953}
2954
2955static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00002956session_stats(PySSLContext *self, PyObject *unused)
2957{
2958 int r;
2959 PyObject *value, *stats = PyDict_New();
2960 if (!stats)
2961 return NULL;
2962
2963#define ADD_STATS(SSL_NAME, KEY_NAME) \
2964 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2965 if (value == NULL) \
2966 goto error; \
2967 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2968 Py_DECREF(value); \
2969 if (r < 0) \
2970 goto error;
2971
2972 ADD_STATS(number, "number");
2973 ADD_STATS(connect, "connect");
2974 ADD_STATS(connect_good, "connect_good");
2975 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2976 ADD_STATS(accept, "accept");
2977 ADD_STATS(accept_good, "accept_good");
2978 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2979 ADD_STATS(accept, "accept");
2980 ADD_STATS(hits, "hits");
2981 ADD_STATS(misses, "misses");
2982 ADD_STATS(timeouts, "timeouts");
2983 ADD_STATS(cache_full, "cache_full");
2984
2985#undef ADD_STATS
2986
2987 return stats;
2988
2989error:
2990 Py_DECREF(stats);
2991 return NULL;
2992}
2993
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002994static PyObject *
2995set_default_verify_paths(PySSLContext *self, PyObject *unused)
2996{
2997 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2998 _setSSLError(NULL, 0, __FILE__, __LINE__);
2999 return NULL;
3000 }
3001 Py_RETURN_NONE;
3002}
3003
Antoine Pitrou501da612011-12-21 09:27:41 +01003004#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003005static PyObject *
3006set_ecdh_curve(PySSLContext *self, PyObject *name)
3007{
3008 PyObject *name_bytes;
3009 int nid;
3010 EC_KEY *key;
3011
3012 if (!PyUnicode_FSConverter(name, &name_bytes))
3013 return NULL;
3014 assert(PyBytes_Check(name_bytes));
3015 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3016 Py_DECREF(name_bytes);
3017 if (nid == 0) {
3018 PyErr_Format(PyExc_ValueError,
3019 "unknown elliptic curve name %R", name);
3020 return NULL;
3021 }
3022 key = EC_KEY_new_by_curve_name(nid);
3023 if (key == NULL) {
3024 _setSSLError(NULL, 0, __FILE__, __LINE__);
3025 return NULL;
3026 }
3027 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3028 EC_KEY_free(key);
3029 Py_RETURN_NONE;
3030}
Antoine Pitrou501da612011-12-21 09:27:41 +01003031#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003032
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003033#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003034static int
3035_servername_callback(SSL *s, int *al, void *args)
3036{
3037 int ret;
3038 PySSLContext *ssl_ctx = (PySSLContext *) args;
3039 PySSLSocket *ssl;
3040 PyObject *servername_o;
3041 PyObject *servername_idna;
3042 PyObject *result;
3043 /* The high-level ssl.SSLSocket object */
3044 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003045 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003046#ifdef WITH_THREAD
3047 PyGILState_STATE gstate = PyGILState_Ensure();
3048#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003049
3050 if (ssl_ctx->set_hostname == NULL) {
3051 /* remove race condition in this the call back while if removing the
3052 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003053#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003054 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003055#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003056 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003057 }
3058
3059 ssl = SSL_get_app_data(s);
3060 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003061
3062 /* The servername callback expects a argument that represents the current
3063 * SSL connection and that has a .context attribute that can be changed to
3064 * identify the requested hostname. Since the official API is the Python
3065 * level API we want to pass the callback a Python level object rather than
3066 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3067 * SSLObject) that will be passed. Otherwise if there's a socket then that
3068 * will be passed. If both do not exist only then the C-level object is
3069 * passed. */
3070 if (ssl->owner)
3071 ssl_socket = PyWeakref_GetObject(ssl->owner);
3072 else if (ssl->Socket)
3073 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3074 else
3075 ssl_socket = (PyObject *) ssl;
3076
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003077 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003078 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003079 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003080
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003081 if (servername == NULL) {
3082 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3083 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003084 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003085 else {
3086 servername_o = PyBytes_FromString(servername);
3087 if (servername_o == NULL) {
3088 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3089 goto error;
3090 }
3091 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3092 if (servername_idna == NULL) {
3093 PyErr_WriteUnraisable(servername_o);
3094 Py_DECREF(servername_o);
3095 goto error;
3096 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003097 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003098 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3099 servername_idna, ssl_ctx, NULL);
3100 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003101 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003102 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003103
3104 if (result == NULL) {
3105 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3106 *al = SSL_AD_HANDSHAKE_FAILURE;
3107 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3108 }
3109 else {
3110 if (result != Py_None) {
3111 *al = (int) PyLong_AsLong(result);
3112 if (PyErr_Occurred()) {
3113 PyErr_WriteUnraisable(result);
3114 *al = SSL_AD_INTERNAL_ERROR;
3115 }
3116 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3117 }
3118 else {
3119 ret = SSL_TLSEXT_ERR_OK;
3120 }
3121 Py_DECREF(result);
3122 }
3123
Stefan Krah20d60802013-01-17 17:07:17 +01003124#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003125 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003126#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003127 return ret;
3128
3129error:
3130 Py_DECREF(ssl_socket);
3131 *al = SSL_AD_INTERNAL_ERROR;
3132 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003133#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003134 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003135#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003136 return ret;
3137}
Antoine Pitroua5963382013-03-30 16:39:00 +01003138#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003139
3140PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3141"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003142\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003143This sets a callback that will be called when a server name is provided by\n\
3144the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003145\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003146If the argument is None then the callback is disabled. The method is called\n\
3147with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003148See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003149
3150static PyObject *
3151set_servername_callback(PySSLContext *self, PyObject *args)
3152{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003153#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003154 PyObject *cb;
3155
3156 if (!PyArg_ParseTuple(args, "O", &cb))
3157 return NULL;
3158
3159 Py_CLEAR(self->set_hostname);
3160 if (cb == Py_None) {
3161 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3162 }
3163 else {
3164 if (!PyCallable_Check(cb)) {
3165 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3166 PyErr_SetString(PyExc_TypeError,
3167 "not a callable object");
3168 return NULL;
3169 }
3170 Py_INCREF(cb);
3171 self->set_hostname = cb;
3172 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3173 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3174 }
3175 Py_RETURN_NONE;
3176#else
3177 PyErr_SetString(PyExc_NotImplementedError,
3178 "The TLS extension servername callback, "
3179 "SSL_CTX_set_tlsext_servername_callback, "
3180 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003181 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003182#endif
3183}
3184
Christian Heimes9a5395a2013-06-17 15:44:12 +02003185PyDoc_STRVAR(PySSL_get_stats_doc,
3186"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3187\n\
3188Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3189CA extension and certificate revocation lists inside the context's cert\n\
3190store.\n\
3191NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3192been used at least once.");
3193
3194static PyObject *
3195cert_store_stats(PySSLContext *self)
3196{
3197 X509_STORE *store;
3198 X509_OBJECT *obj;
3199 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3200
3201 store = SSL_CTX_get_cert_store(self->ctx);
3202 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3203 obj = sk_X509_OBJECT_value(store->objs, i);
3204 switch (obj->type) {
3205 case X509_LU_X509:
3206 x509++;
3207 if (X509_check_ca(obj->data.x509)) {
3208 ca++;
3209 }
3210 break;
3211 case X509_LU_CRL:
3212 crl++;
3213 break;
3214 case X509_LU_PKEY:
3215 pkey++;
3216 break;
3217 default:
3218 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3219 * As far as I can tell they are internal states and never
3220 * stored in a cert store */
3221 break;
3222 }
3223 }
3224 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3225 "x509_ca", ca);
3226}
3227
3228PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003229"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003230\n\
3231Returns a list of dicts with information of loaded CA certs. If the\n\
3232optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3233NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3234been used at least once.");
3235
3236static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003237get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003238{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003239 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003240 X509_STORE *store;
3241 PyObject *ci = NULL, *rlist = NULL;
3242 int i;
3243 int binary_mode = 0;
3244
Christian Heimesf22e8e52013-11-22 02:22:51 +01003245 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3246 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003247 return NULL;
3248 }
3249
3250 if ((rlist = PyList_New(0)) == NULL) {
3251 return NULL;
3252 }
3253
3254 store = SSL_CTX_get_cert_store(self->ctx);
3255 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3256 X509_OBJECT *obj;
3257 X509 *cert;
3258
3259 obj = sk_X509_OBJECT_value(store->objs, i);
3260 if (obj->type != X509_LU_X509) {
3261 /* not a x509 cert */
3262 continue;
3263 }
3264 /* CA for any purpose */
3265 cert = obj->data.x509;
3266 if (!X509_check_ca(cert)) {
3267 continue;
3268 }
3269 if (binary_mode) {
3270 ci = _certificate_to_der(cert);
3271 } else {
3272 ci = _decode_certificate(cert);
3273 }
3274 if (ci == NULL) {
3275 goto error;
3276 }
3277 if (PyList_Append(rlist, ci) == -1) {
3278 goto error;
3279 }
3280 Py_CLEAR(ci);
3281 }
3282 return rlist;
3283
3284 error:
3285 Py_XDECREF(ci);
3286 Py_XDECREF(rlist);
3287 return NULL;
3288}
3289
3290
Antoine Pitrou152efa22010-05-16 18:19:27 +00003291static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003292 {"check_hostname", (getter) get_check_hostname,
3293 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003294 {"options", (getter) get_options,
3295 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003296 {"verify_flags", (getter) get_verify_flags,
3297 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 {"verify_mode", (getter) get_verify_mode,
3299 (setter) set_verify_mode, NULL},
3300 {NULL}, /* sentinel */
3301};
3302
3303static struct PyMethodDef context_methods[] = {
3304 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3305 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003306 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3307 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308 {"set_ciphers", (PyCFunction) set_ciphers,
3309 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003310 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3311 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 {"load_cert_chain", (PyCFunction) load_cert_chain,
3313 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003314 {"load_dh_params", (PyCFunction) load_dh_params,
3315 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 {"load_verify_locations", (PyCFunction) load_verify_locations,
3317 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003318 {"session_stats", (PyCFunction) session_stats,
3319 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003320 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3321 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003322#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003323 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3324 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003325#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003326 {"set_servername_callback", (PyCFunction) set_servername_callback,
3327 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003328 {"cert_store_stats", (PyCFunction) cert_store_stats,
3329 METH_NOARGS, PySSL_get_stats_doc},
3330 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003331 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003332 {NULL, NULL} /* sentinel */
3333};
3334
3335static PyTypeObject PySSLContext_Type = {
3336 PyVarObject_HEAD_INIT(NULL, 0)
3337 "_ssl._SSLContext", /*tp_name*/
3338 sizeof(PySSLContext), /*tp_basicsize*/
3339 0, /*tp_itemsize*/
3340 (destructor)context_dealloc, /*tp_dealloc*/
3341 0, /*tp_print*/
3342 0, /*tp_getattr*/
3343 0, /*tp_setattr*/
3344 0, /*tp_reserved*/
3345 0, /*tp_repr*/
3346 0, /*tp_as_number*/
3347 0, /*tp_as_sequence*/
3348 0, /*tp_as_mapping*/
3349 0, /*tp_hash*/
3350 0, /*tp_call*/
3351 0, /*tp_str*/
3352 0, /*tp_getattro*/
3353 0, /*tp_setattro*/
3354 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003355 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003356 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003357 (traverseproc) context_traverse, /*tp_traverse*/
3358 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003359 0, /*tp_richcompare*/
3360 0, /*tp_weaklistoffset*/
3361 0, /*tp_iter*/
3362 0, /*tp_iternext*/
3363 context_methods, /*tp_methods*/
3364 0, /*tp_members*/
3365 context_getsetlist, /*tp_getset*/
3366 0, /*tp_base*/
3367 0, /*tp_dict*/
3368 0, /*tp_descr_get*/
3369 0, /*tp_descr_set*/
3370 0, /*tp_dictoffset*/
3371 0, /*tp_init*/
3372 0, /*tp_alloc*/
3373 context_new, /*tp_new*/
3374};
3375
3376
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003377/*
3378 * MemoryBIO objects
3379 */
3380
3381static PyObject *
3382memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3383{
3384 char *kwlist[] = {NULL};
3385 BIO *bio;
3386 PySSLMemoryBIO *self;
3387
3388 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3389 return NULL;
3390
3391 bio = BIO_new(BIO_s_mem());
3392 if (bio == NULL) {
3393 PyErr_SetString(PySSLErrorObject,
3394 "failed to allocate BIO");
3395 return NULL;
3396 }
3397 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3398 * just that no data is currently available. The SSL routines should retry
3399 * the read, which we can achieve by calling BIO_set_retry_read(). */
3400 BIO_set_retry_read(bio);
3401 BIO_set_mem_eof_return(bio, -1);
3402
3403 assert(type != NULL && type->tp_alloc != NULL);
3404 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3405 if (self == NULL) {
3406 BIO_free(bio);
3407 return NULL;
3408 }
3409 self->bio = bio;
3410 self->eof_written = 0;
3411
3412 return (PyObject *) self;
3413}
3414
3415static void
3416memory_bio_dealloc(PySSLMemoryBIO *self)
3417{
3418 BIO_free(self->bio);
3419 Py_TYPE(self)->tp_free(self);
3420}
3421
3422static PyObject *
3423memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3424{
3425 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3426}
3427
3428PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3429"The number of bytes pending in the memory BIO.");
3430
3431static PyObject *
3432memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3433{
3434 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3435 && self->eof_written);
3436}
3437
3438PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3439"Whether the memory BIO is at EOF.");
3440
3441static PyObject *
3442memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3443{
3444 int len = -1, avail, nbytes;
3445 PyObject *result;
3446
3447 if (!PyArg_ParseTuple(args, "|i:read", &len))
3448 return NULL;
3449
3450 avail = BIO_ctrl_pending(self->bio);
3451 if ((len < 0) || (len > avail))
3452 len = avail;
3453
3454 result = PyBytes_FromStringAndSize(NULL, len);
3455 if ((result == NULL) || (len == 0))
3456 return result;
3457
3458 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3459 /* There should never be any short reads but check anyway. */
3460 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3461 Py_DECREF(result);
3462 return NULL;
3463 }
3464
3465 return result;
3466}
3467
3468PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3469"read([len]) -> bytes\n\
3470\n\
3471Read up to len bytes from the memory BIO.\n\
3472\n\
3473If len is not specified, read the entire buffer.\n\
3474If the return value is an empty bytes instance, this means either\n\
3475EOF or that no data is available. Use the \"eof\" property to\n\
3476distinguish between the two.");
3477
3478static PyObject *
3479memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3480{
3481 Py_buffer buf;
3482 int nbytes;
3483
3484 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3485 return NULL;
3486
3487 if (buf.len > INT_MAX) {
3488 PyErr_Format(PyExc_OverflowError,
3489 "string longer than %d bytes", INT_MAX);
3490 goto error;
3491 }
3492
3493 if (self->eof_written) {
3494 PyErr_SetString(PySSLErrorObject,
3495 "cannot write() after write_eof()");
3496 goto error;
3497 }
3498
3499 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3500 if (nbytes < 0) {
3501 _setSSLError(NULL, 0, __FILE__, __LINE__);
3502 goto error;
3503 }
3504
3505 PyBuffer_Release(&buf);
3506 return PyLong_FromLong(nbytes);
3507
3508error:
3509 PyBuffer_Release(&buf);
3510 return NULL;
3511}
3512
3513PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3514"write(b) -> len\n\
3515\n\
3516Writes the bytes b into the memory BIO. Returns the number\n\
3517of bytes written.");
3518
3519static PyObject *
3520memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3521{
3522 self->eof_written = 1;
3523 /* After an EOF is written, a zero return from read() should be a real EOF
3524 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3525 BIO_clear_retry_flags(self->bio);
3526 BIO_set_mem_eof_return(self->bio, 0);
3527
3528 Py_RETURN_NONE;
3529}
3530
3531PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3532"write_eof()\n\
3533\n\
3534Write an EOF marker to the memory BIO.\n\
3535When all data has been read, the \"eof\" property will be True.");
3536
3537static PyGetSetDef memory_bio_getsetlist[] = {
3538 {"pending", (getter) memory_bio_get_pending, NULL,
3539 PySSL_memory_bio_pending_doc},
3540 {"eof", (getter) memory_bio_get_eof, NULL,
3541 PySSL_memory_bio_eof_doc},
3542 {NULL}, /* sentinel */
3543};
3544
3545static struct PyMethodDef memory_bio_methods[] = {
3546 {"read", (PyCFunction) memory_bio_read,
3547 METH_VARARGS, PySSL_memory_bio_read_doc},
3548 {"write", (PyCFunction) memory_bio_write,
3549 METH_VARARGS, PySSL_memory_bio_write_doc},
3550 {"write_eof", (PyCFunction) memory_bio_write_eof,
3551 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3552 {NULL, NULL} /* sentinel */
3553};
3554
3555static PyTypeObject PySSLMemoryBIO_Type = {
3556 PyVarObject_HEAD_INIT(NULL, 0)
3557 "_ssl.MemoryBIO", /*tp_name*/
3558 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3559 0, /*tp_itemsize*/
3560 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3561 0, /*tp_print*/
3562 0, /*tp_getattr*/
3563 0, /*tp_setattr*/
3564 0, /*tp_reserved*/
3565 0, /*tp_repr*/
3566 0, /*tp_as_number*/
3567 0, /*tp_as_sequence*/
3568 0, /*tp_as_mapping*/
3569 0, /*tp_hash*/
3570 0, /*tp_call*/
3571 0, /*tp_str*/
3572 0, /*tp_getattro*/
3573 0, /*tp_setattro*/
3574 0, /*tp_as_buffer*/
3575 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3576 0, /*tp_doc*/
3577 0, /*tp_traverse*/
3578 0, /*tp_clear*/
3579 0, /*tp_richcompare*/
3580 0, /*tp_weaklistoffset*/
3581 0, /*tp_iter*/
3582 0, /*tp_iternext*/
3583 memory_bio_methods, /*tp_methods*/
3584 0, /*tp_members*/
3585 memory_bio_getsetlist, /*tp_getset*/
3586 0, /*tp_base*/
3587 0, /*tp_dict*/
3588 0, /*tp_descr_get*/
3589 0, /*tp_descr_set*/
3590 0, /*tp_dictoffset*/
3591 0, /*tp_init*/
3592 0, /*tp_alloc*/
3593 memory_bio_new, /*tp_new*/
3594};
3595
Antoine Pitrou152efa22010-05-16 18:19:27 +00003596
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003597/* helper routines for seeding the SSL PRNG */
3598static PyObject *
3599PySSL_RAND_add(PyObject *self, PyObject *args)
3600{
3601 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003602 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003603 double entropy;
3604
3605 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003606 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003607 do {
3608 written = Py_MIN(len, INT_MAX);
3609 RAND_add(buf, (int)written, entropy);
3610 buf += written;
3611 len -= written;
3612 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003613 Py_INCREF(Py_None);
3614 return Py_None;
3615}
3616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003617PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003618"RAND_add(string, entropy)\n\
3619\n\
3620Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003621bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003622
3623static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003624PySSL_RAND(int len, int pseudo)
3625{
3626 int ok;
3627 PyObject *bytes;
3628 unsigned long err;
3629 const char *errstr;
3630 PyObject *v;
3631
Victor Stinner1e81a392013-12-19 16:47:04 +01003632 if (len < 0) {
3633 PyErr_SetString(PyExc_ValueError, "num must be positive");
3634 return NULL;
3635 }
3636
Victor Stinner99c8b162011-05-24 12:05:19 +02003637 bytes = PyBytes_FromStringAndSize(NULL, len);
3638 if (bytes == NULL)
3639 return NULL;
3640 if (pseudo) {
3641 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3642 if (ok == 0 || ok == 1)
3643 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3644 }
3645 else {
3646 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3647 if (ok == 1)
3648 return bytes;
3649 }
3650 Py_DECREF(bytes);
3651
3652 err = ERR_get_error();
3653 errstr = ERR_reason_error_string(err);
3654 v = Py_BuildValue("(ks)", err, errstr);
3655 if (v != NULL) {
3656 PyErr_SetObject(PySSLErrorObject, v);
3657 Py_DECREF(v);
3658 }
3659 return NULL;
3660}
3661
3662static PyObject *
3663PySSL_RAND_bytes(PyObject *self, PyObject *args)
3664{
3665 int len;
3666 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3667 return NULL;
3668 return PySSL_RAND(len, 0);
3669}
3670
3671PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3672"RAND_bytes(n) -> bytes\n\
3673\n\
3674Generate n cryptographically strong pseudo-random bytes.");
3675
3676static PyObject *
3677PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3678{
3679 int len;
3680 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3681 return NULL;
3682 return PySSL_RAND(len, 1);
3683}
3684
3685PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3686"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3687\n\
3688Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3689generated are cryptographically strong.");
3690
3691static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003692PySSL_RAND_status(PyObject *self)
3693{
Christian Heimes217cfd12007-12-02 14:31:20 +00003694 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003695}
3696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003697PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003698"RAND_status() -> 0 or 1\n\
3699\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003700Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3701It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3702using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003703
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003704#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003705static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003706PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003707{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003708 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003709 int bytes;
3710
Jesus Ceac8754a12012-09-11 02:00:58 +02003711 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003712 PyUnicode_FSConverter, &path))
3713 return NULL;
3714
3715 bytes = RAND_egd(PyBytes_AsString(path));
3716 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003717 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003718 PyErr_SetString(PySSLErrorObject,
3719 "EGD connection failed or EGD did not return "
3720 "enough data to seed the PRNG");
3721 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003722 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003723 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003724}
3725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003726PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003727"RAND_egd(path) -> bytes\n\
3728\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003729Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3730Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003731fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003732#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003733
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003734
Christian Heimes6d7ad132013-06-09 18:02:55 +02003735PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3736"get_default_verify_paths() -> tuple\n\
3737\n\
3738Return search paths and environment vars that are used by SSLContext's\n\
3739set_default_verify_paths() to load default CAs. The values are\n\
3740'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3741
3742static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003743PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003744{
3745 PyObject *ofile_env = NULL;
3746 PyObject *ofile = NULL;
3747 PyObject *odir_env = NULL;
3748 PyObject *odir = NULL;
3749
3750#define convert(info, target) { \
3751 const char *tmp = (info); \
3752 target = NULL; \
3753 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3754 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3755 target = PyBytes_FromString(tmp); } \
3756 if (!target) goto error; \
3757 } while(0)
3758
3759 convert(X509_get_default_cert_file_env(), ofile_env);
3760 convert(X509_get_default_cert_file(), ofile);
3761 convert(X509_get_default_cert_dir_env(), odir_env);
3762 convert(X509_get_default_cert_dir(), odir);
3763#undef convert
3764
Christian Heimes200bb1b2013-06-14 15:14:29 +02003765 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003766
3767 error:
3768 Py_XDECREF(ofile_env);
3769 Py_XDECREF(ofile);
3770 Py_XDECREF(odir_env);
3771 Py_XDECREF(odir);
3772 return NULL;
3773}
3774
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003775static PyObject*
3776asn1obj2py(ASN1_OBJECT *obj)
3777{
3778 int nid;
3779 const char *ln, *sn;
3780 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003781 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003782
3783 nid = OBJ_obj2nid(obj);
3784 if (nid == NID_undef) {
3785 PyErr_Format(PyExc_ValueError, "Unknown object");
3786 return NULL;
3787 }
3788 sn = OBJ_nid2sn(nid);
3789 ln = OBJ_nid2ln(nid);
3790 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3791 if (buflen < 0) {
3792 _setSSLError(NULL, 0, __FILE__, __LINE__);
3793 return NULL;
3794 }
3795 if (buflen) {
3796 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3797 } else {
3798 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3799 }
3800}
3801
3802PyDoc_STRVAR(PySSL_txt2obj_doc,
3803"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3804\n\
3805Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3806objects are looked up by OID. With name=True short and long name are also\n\
3807matched.");
3808
3809static PyObject*
3810PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3811{
3812 char *kwlist[] = {"txt", "name", NULL};
3813 PyObject *result = NULL;
3814 char *txt;
3815 int name = 0;
3816 ASN1_OBJECT *obj;
3817
3818 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3819 kwlist, &txt, &name)) {
3820 return NULL;
3821 }
3822 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3823 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003824 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003825 return NULL;
3826 }
3827 result = asn1obj2py(obj);
3828 ASN1_OBJECT_free(obj);
3829 return result;
3830}
3831
3832PyDoc_STRVAR(PySSL_nid2obj_doc,
3833"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3834\n\
3835Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3836
3837static PyObject*
3838PySSL_nid2obj(PyObject *self, PyObject *args)
3839{
3840 PyObject *result = NULL;
3841 int nid;
3842 ASN1_OBJECT *obj;
3843
3844 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3845 return NULL;
3846 }
3847 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003848 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003849 return NULL;
3850 }
3851 obj = OBJ_nid2obj(nid);
3852 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003853 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003854 return NULL;
3855 }
3856 result = asn1obj2py(obj);
3857 ASN1_OBJECT_free(obj);
3858 return result;
3859}
3860
Christian Heimes46bebee2013-06-09 19:03:31 +02003861#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003862
3863static PyObject*
3864certEncodingType(DWORD encodingType)
3865{
3866 static PyObject *x509_asn = NULL;
3867 static PyObject *pkcs_7_asn = NULL;
3868
3869 if (x509_asn == NULL) {
3870 x509_asn = PyUnicode_InternFromString("x509_asn");
3871 if (x509_asn == NULL)
3872 return NULL;
3873 }
3874 if (pkcs_7_asn == NULL) {
3875 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3876 if (pkcs_7_asn == NULL)
3877 return NULL;
3878 }
3879 switch(encodingType) {
3880 case X509_ASN_ENCODING:
3881 Py_INCREF(x509_asn);
3882 return x509_asn;
3883 case PKCS_7_ASN_ENCODING:
3884 Py_INCREF(pkcs_7_asn);
3885 return pkcs_7_asn;
3886 default:
3887 return PyLong_FromLong(encodingType);
3888 }
3889}
3890
3891static PyObject*
3892parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3893{
3894 CERT_ENHKEY_USAGE *usage;
3895 DWORD size, error, i;
3896 PyObject *retval;
3897
3898 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3899 error = GetLastError();
3900 if (error == CRYPT_E_NOT_FOUND) {
3901 Py_RETURN_TRUE;
3902 }
3903 return PyErr_SetFromWindowsErr(error);
3904 }
3905
3906 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3907 if (usage == NULL) {
3908 return PyErr_NoMemory();
3909 }
3910
3911 /* Now get the actual enhanced usage property */
3912 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3913 PyMem_Free(usage);
3914 error = GetLastError();
3915 if (error == CRYPT_E_NOT_FOUND) {
3916 Py_RETURN_TRUE;
3917 }
3918 return PyErr_SetFromWindowsErr(error);
3919 }
3920 retval = PySet_New(NULL);
3921 if (retval == NULL) {
3922 goto error;
3923 }
3924 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3925 if (usage->rgpszUsageIdentifier[i]) {
3926 PyObject *oid;
3927 int err;
3928 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3929 if (oid == NULL) {
3930 Py_CLEAR(retval);
3931 goto error;
3932 }
3933 err = PySet_Add(retval, oid);
3934 Py_DECREF(oid);
3935 if (err == -1) {
3936 Py_CLEAR(retval);
3937 goto error;
3938 }
3939 }
3940 }
3941 error:
3942 PyMem_Free(usage);
3943 return retval;
3944}
3945
3946PyDoc_STRVAR(PySSL_enum_certificates_doc,
3947"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003948\n\
3949Retrieve certificates from Windows' cert store. store_name may be one of\n\
3950'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003951The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003952encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003953PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3954boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003955
Christian Heimes46bebee2013-06-09 19:03:31 +02003956static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003957PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003958{
Christian Heimes44109d72013-11-22 01:51:30 +01003959 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003960 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003961 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003962 PCCERT_CONTEXT pCertCtx = NULL;
3963 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003964 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003965
Christian Heimes44109d72013-11-22 01:51:30 +01003966 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3967 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003968 return NULL;
3969 }
Christian Heimes44109d72013-11-22 01:51:30 +01003970 result = PyList_New(0);
3971 if (result == NULL) {
3972 return NULL;
3973 }
3974 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3975 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003976 Py_DECREF(result);
3977 return PyErr_SetFromWindowsErr(GetLastError());
3978 }
3979
Christian Heimes44109d72013-11-22 01:51:30 +01003980 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3981 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3982 pCertCtx->cbCertEncoded);
3983 if (!cert) {
3984 Py_CLEAR(result);
3985 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003986 }
Christian Heimes44109d72013-11-22 01:51:30 +01003987 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3988 Py_CLEAR(result);
3989 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003990 }
Christian Heimes44109d72013-11-22 01:51:30 +01003991 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3992 if (keyusage == Py_True) {
3993 Py_DECREF(keyusage);
3994 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003995 }
Christian Heimes44109d72013-11-22 01:51:30 +01003996 if (keyusage == NULL) {
3997 Py_CLEAR(result);
3998 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003999 }
Christian Heimes44109d72013-11-22 01:51:30 +01004000 if ((tup = PyTuple_New(3)) == NULL) {
4001 Py_CLEAR(result);
4002 break;
4003 }
4004 PyTuple_SET_ITEM(tup, 0, cert);
4005 cert = NULL;
4006 PyTuple_SET_ITEM(tup, 1, enc);
4007 enc = NULL;
4008 PyTuple_SET_ITEM(tup, 2, keyusage);
4009 keyusage = NULL;
4010 if (PyList_Append(result, tup) < 0) {
4011 Py_CLEAR(result);
4012 break;
4013 }
4014 Py_CLEAR(tup);
4015 }
4016 if (pCertCtx) {
4017 /* loop ended with an error, need to clean up context manually */
4018 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004019 }
4020
4021 /* In error cases cert, enc and tup may not be NULL */
4022 Py_XDECREF(cert);
4023 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004024 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004025 Py_XDECREF(tup);
4026
4027 if (!CertCloseStore(hStore, 0)) {
4028 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004029 Py_XDECREF(result);
4030 return PyErr_SetFromWindowsErr(GetLastError());
4031 }
4032 return result;
4033}
4034
4035PyDoc_STRVAR(PySSL_enum_crls_doc,
4036"enum_crls(store_name) -> []\n\
4037\n\
4038Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4039'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4040The function returns a list of (bytes, encoding_type) tuples. The\n\
4041encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4042PKCS_7_ASN_ENCODING.");
4043
4044static PyObject *
4045PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4046{
4047 char *kwlist[] = {"store_name", NULL};
4048 char *store_name;
4049 HCERTSTORE hStore = NULL;
4050 PCCRL_CONTEXT pCrlCtx = NULL;
4051 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4052 PyObject *result = NULL;
4053
4054 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4055 kwlist, &store_name)) {
4056 return NULL;
4057 }
4058 result = PyList_New(0);
4059 if (result == NULL) {
4060 return NULL;
4061 }
4062 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4063 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004064 Py_DECREF(result);
4065 return PyErr_SetFromWindowsErr(GetLastError());
4066 }
Christian Heimes44109d72013-11-22 01:51:30 +01004067
4068 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4069 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4070 pCrlCtx->cbCrlEncoded);
4071 if (!crl) {
4072 Py_CLEAR(result);
4073 break;
4074 }
4075 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4076 Py_CLEAR(result);
4077 break;
4078 }
4079 if ((tup = PyTuple_New(2)) == NULL) {
4080 Py_CLEAR(result);
4081 break;
4082 }
4083 PyTuple_SET_ITEM(tup, 0, crl);
4084 crl = NULL;
4085 PyTuple_SET_ITEM(tup, 1, enc);
4086 enc = NULL;
4087
4088 if (PyList_Append(result, tup) < 0) {
4089 Py_CLEAR(result);
4090 break;
4091 }
4092 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004093 }
Christian Heimes44109d72013-11-22 01:51:30 +01004094 if (pCrlCtx) {
4095 /* loop ended with an error, need to clean up context manually */
4096 CertFreeCRLContext(pCrlCtx);
4097 }
4098
4099 /* In error cases cert, enc and tup may not be NULL */
4100 Py_XDECREF(crl);
4101 Py_XDECREF(enc);
4102 Py_XDECREF(tup);
4103
4104 if (!CertCloseStore(hStore, 0)) {
4105 /* This error case might shadow another exception.*/
4106 Py_XDECREF(result);
4107 return PyErr_SetFromWindowsErr(GetLastError());
4108 }
4109 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004110}
Christian Heimes44109d72013-11-22 01:51:30 +01004111
4112#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004113
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004114/* List of functions exported by this module. */
4115
4116static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004117 {"_test_decode_cert", PySSL_test_decode_certificate,
4118 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004119 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4120 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004121 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4122 PySSL_RAND_bytes_doc},
4123 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4124 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004125#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004126 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004127 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004128#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004129 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4130 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004131 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004132 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004133#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004134 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4135 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4136 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4137 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004138#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004139 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4140 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4141 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4142 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004143 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004144};
4145
4146
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004147#ifdef WITH_THREAD
4148
4149/* an implementation of OpenSSL threading operations in terms
4150 of the Python C thread library */
4151
4152static PyThread_type_lock *_ssl_locks = NULL;
4153
Christian Heimes4d98ca92013-08-19 17:36:29 +02004154#if OPENSSL_VERSION_NUMBER >= 0x10000000
4155/* use new CRYPTO_THREADID API. */
4156static void
4157_ssl_threadid_callback(CRYPTO_THREADID *id)
4158{
4159 CRYPTO_THREADID_set_numeric(id,
4160 (unsigned long)PyThread_get_thread_ident());
4161}
4162#else
4163/* deprecated CRYPTO_set_id_callback() API. */
4164static unsigned long
4165_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004166 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004167}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004168#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004169
Bill Janssen6e027db2007-11-15 22:23:56 +00004170static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004171 (int mode, int n, const char *file, int line) {
4172 /* this function is needed to perform locking on shared data
4173 structures. (Note that OpenSSL uses a number of global data
4174 structures that will be implicitly shared whenever multiple
4175 threads use OpenSSL.) Multi-threaded applications will
4176 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004178 locking_function() must be able to handle up to
4179 CRYPTO_num_locks() different mutex locks. It sets the n-th
4180 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004182 file and line are the file number of the function setting the
4183 lock. They can be useful for debugging.
4184 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004186 if ((_ssl_locks == NULL) ||
4187 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4188 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004190 if (mode & CRYPTO_LOCK) {
4191 PyThread_acquire_lock(_ssl_locks[n], 1);
4192 } else {
4193 PyThread_release_lock(_ssl_locks[n]);
4194 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004195}
4196
4197static int _setup_ssl_threads(void) {
4198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004199 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004201 if (_ssl_locks == NULL) {
4202 _ssl_locks_count = CRYPTO_num_locks();
4203 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02004204 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004205 if (_ssl_locks == NULL)
4206 return 0;
4207 memset(_ssl_locks, 0,
4208 sizeof(PyThread_type_lock) * _ssl_locks_count);
4209 for (i = 0; i < _ssl_locks_count; i++) {
4210 _ssl_locks[i] = PyThread_allocate_lock();
4211 if (_ssl_locks[i] == NULL) {
4212 unsigned int j;
4213 for (j = 0; j < i; j++) {
4214 PyThread_free_lock(_ssl_locks[j]);
4215 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004216 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004217 return 0;
4218 }
4219 }
4220 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004221#if OPENSSL_VERSION_NUMBER >= 0x10000000
4222 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4223#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004224 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004225#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004226 }
4227 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004228}
4229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004230#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004231
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004232PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004233"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004234for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004235
Martin v. Löwis1a214512008-06-11 05:26:20 +00004236
4237static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004238 PyModuleDef_HEAD_INIT,
4239 "_ssl",
4240 module_doc,
4241 -1,
4242 PySSL_methods,
4243 NULL,
4244 NULL,
4245 NULL,
4246 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004247};
4248
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004249
4250static void
4251parse_openssl_version(unsigned long libver,
4252 unsigned int *major, unsigned int *minor,
4253 unsigned int *fix, unsigned int *patch,
4254 unsigned int *status)
4255{
4256 *status = libver & 0xF;
4257 libver >>= 4;
4258 *patch = libver & 0xFF;
4259 libver >>= 8;
4260 *fix = libver & 0xFF;
4261 libver >>= 8;
4262 *minor = libver & 0xFF;
4263 libver >>= 8;
4264 *major = libver & 0xFF;
4265}
4266
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004267PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004268PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004269{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004270 PyObject *m, *d, *r;
4271 unsigned long libver;
4272 unsigned int major, minor, fix, patch, status;
4273 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004274 struct py_ssl_error_code *errcode;
4275 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004276
Antoine Pitrou152efa22010-05-16 18:19:27 +00004277 if (PyType_Ready(&PySSLContext_Type) < 0)
4278 return NULL;
4279 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004280 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004281 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4282 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004284 m = PyModule_Create(&_sslmodule);
4285 if (m == NULL)
4286 return NULL;
4287 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004289 /* Load _socket module and its C API */
4290 socket_api = PySocketModule_ImportModuleAndAPI();
4291 if (!socket_api)
4292 return NULL;
4293 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004295 /* Init OpenSSL */
4296 SSL_load_error_strings();
4297 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004298#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004299 /* note that this will start threading if not already started */
4300 if (!_setup_ssl_threads()) {
4301 return NULL;
4302 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004303#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004304 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004306 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004307 sslerror_type_slots[0].pfunc = PyExc_OSError;
4308 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004309 if (PySSLErrorObject == NULL)
4310 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004311
Antoine Pitrou41032a62011-10-27 23:56:55 +02004312 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4313 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4314 PySSLErrorObject, NULL);
4315 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4316 "ssl.SSLWantReadError", SSLWantReadError_doc,
4317 PySSLErrorObject, NULL);
4318 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4319 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4320 PySSLErrorObject, NULL);
4321 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4322 "ssl.SSLSyscallError", SSLSyscallError_doc,
4323 PySSLErrorObject, NULL);
4324 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4325 "ssl.SSLEOFError", SSLEOFError_doc,
4326 PySSLErrorObject, NULL);
4327 if (PySSLZeroReturnErrorObject == NULL
4328 || PySSLWantReadErrorObject == NULL
4329 || PySSLWantWriteErrorObject == NULL
4330 || PySSLSyscallErrorObject == NULL
4331 || PySSLEOFErrorObject == NULL)
4332 return NULL;
4333 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4334 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4335 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4336 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4337 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4338 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004339 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004340 if (PyDict_SetItemString(d, "_SSLContext",
4341 (PyObject *)&PySSLContext_Type) != 0)
4342 return NULL;
4343 if (PyDict_SetItemString(d, "_SSLSocket",
4344 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004345 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004346 if (PyDict_SetItemString(d, "MemoryBIO",
4347 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4348 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004349 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4350 PY_SSL_ERROR_ZERO_RETURN);
4351 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4352 PY_SSL_ERROR_WANT_READ);
4353 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4354 PY_SSL_ERROR_WANT_WRITE);
4355 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4356 PY_SSL_ERROR_WANT_X509_LOOKUP);
4357 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4358 PY_SSL_ERROR_SYSCALL);
4359 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4360 PY_SSL_ERROR_SSL);
4361 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4362 PY_SSL_ERROR_WANT_CONNECT);
4363 /* non ssl.h errorcodes */
4364 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4365 PY_SSL_ERROR_EOF);
4366 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4367 PY_SSL_ERROR_INVALID_ERROR_CODE);
4368 /* cert requirements */
4369 PyModule_AddIntConstant(m, "CERT_NONE",
4370 PY_SSL_CERT_NONE);
4371 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4372 PY_SSL_CERT_OPTIONAL);
4373 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4374 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004375 /* CRL verification for verification_flags */
4376 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4377 0);
4378 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4379 X509_V_FLAG_CRL_CHECK);
4380 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4381 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4382 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4383 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004384
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004385 /* Alert Descriptions from ssl.h */
4386 /* note RESERVED constants no longer intended for use have been removed */
4387 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4388
4389#define ADD_AD_CONSTANT(s) \
4390 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4391 SSL_AD_##s)
4392
4393 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4394 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4395 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4396 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4397 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4398 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4399 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4400 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4401 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4402 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4403 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4404 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4405 ADD_AD_CONSTANT(UNKNOWN_CA);
4406 ADD_AD_CONSTANT(ACCESS_DENIED);
4407 ADD_AD_CONSTANT(DECODE_ERROR);
4408 ADD_AD_CONSTANT(DECRYPT_ERROR);
4409 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4410 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4411 ADD_AD_CONSTANT(INTERNAL_ERROR);
4412 ADD_AD_CONSTANT(USER_CANCELLED);
4413 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004414 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004415#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4416 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4417#endif
4418#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4419 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4420#endif
4421#ifdef SSL_AD_UNRECOGNIZED_NAME
4422 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4423#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004424#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4425 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4426#endif
4427#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4428 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4429#endif
4430#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4431 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4432#endif
4433
4434#undef ADD_AD_CONSTANT
4435
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004436 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004437#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004438 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4439 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004440#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004441#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004442 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4443 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004444#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004445 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4446 PY_SSL_VERSION_SSL23);
4447 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4448 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004449#if HAVE_TLSv1_2
4450 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4451 PY_SSL_VERSION_TLS1_1);
4452 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4453 PY_SSL_VERSION_TLS1_2);
4454#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004455
Antoine Pitroub5218772010-05-21 09:56:06 +00004456 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004457 PyModule_AddIntConstant(m, "OP_ALL",
4458 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004459 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4460 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4461 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004462#if HAVE_TLSv1_2
4463 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4464 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4465#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004466 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4467 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004468 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004469#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004470 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004471#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004472#ifdef SSL_OP_NO_COMPRESSION
4473 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4474 SSL_OP_NO_COMPRESSION);
4475#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004476
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004477#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004478 r = Py_True;
4479#else
4480 r = Py_False;
4481#endif
4482 Py_INCREF(r);
4483 PyModule_AddObject(m, "HAS_SNI", r);
4484
Antoine Pitroud6494802011-07-21 01:11:30 +02004485 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004486 Py_INCREF(r);
4487 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4488
Antoine Pitrou501da612011-12-21 09:27:41 +01004489#ifdef OPENSSL_NO_ECDH
4490 r = Py_False;
4491#else
4492 r = Py_True;
4493#endif
4494 Py_INCREF(r);
4495 PyModule_AddObject(m, "HAS_ECDH", r);
4496
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004497#ifdef OPENSSL_NPN_NEGOTIATED
4498 r = Py_True;
4499#else
4500 r = Py_False;
4501#endif
4502 Py_INCREF(r);
4503 PyModule_AddObject(m, "HAS_NPN", r);
4504
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004505 /* Mappings for error codes */
4506 err_codes_to_names = PyDict_New();
4507 err_names_to_codes = PyDict_New();
4508 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4509 return NULL;
4510 errcode = error_codes;
4511 while (errcode->mnemonic != NULL) {
4512 PyObject *mnemo, *key;
4513 mnemo = PyUnicode_FromString(errcode->mnemonic);
4514 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4515 if (mnemo == NULL || key == NULL)
4516 return NULL;
4517 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4518 return NULL;
4519 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4520 return NULL;
4521 Py_DECREF(key);
4522 Py_DECREF(mnemo);
4523 errcode++;
4524 }
4525 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4526 return NULL;
4527 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4528 return NULL;
4529
4530 lib_codes_to_names = PyDict_New();
4531 if (lib_codes_to_names == NULL)
4532 return NULL;
4533 libcode = library_codes;
4534 while (libcode->library != NULL) {
4535 PyObject *mnemo, *key;
4536 key = PyLong_FromLong(libcode->code);
4537 mnemo = PyUnicode_FromString(libcode->library);
4538 if (key == NULL || mnemo == NULL)
4539 return NULL;
4540 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4541 return NULL;
4542 Py_DECREF(key);
4543 Py_DECREF(mnemo);
4544 libcode++;
4545 }
4546 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4547 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004549 /* OpenSSL version */
4550 /* SSLeay() gives us the version of the library linked against,
4551 which could be different from the headers version.
4552 */
4553 libver = SSLeay();
4554 r = PyLong_FromUnsignedLong(libver);
4555 if (r == NULL)
4556 return NULL;
4557 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4558 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004559 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004560 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4561 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4562 return NULL;
4563 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4564 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4565 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004566
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004567 libver = OPENSSL_VERSION_NUMBER;
4568 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4569 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4570 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4571 return NULL;
4572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004573 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004574}