blob: 9bd07764bc08efc54a0b5a6d762ff04d3a290e7f [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"
67
68/* SSL error object */
69static PyObject *PySSLErrorObject;
70static PyObject *PySSLZeroReturnErrorObject;
71static PyObject *PySSLWantReadErrorObject;
72static PyObject *PySSLWantWriteErrorObject;
73static PyObject *PySSLSyscallErrorObject;
74static PyObject *PySSLEOFErrorObject;
75
76/* Error mappings */
77static PyObject *err_codes_to_names;
78static PyObject *err_names_to_codes;
79static PyObject *lib_codes_to_names;
80
81struct py_ssl_error_code {
82 const char *mnemonic;
83 int library, reason;
84};
85struct py_ssl_library_code {
86 const char *library;
87 int code;
88};
89
90/* Include generated data (error codes) */
91#include "_ssl_data.h"
92
93/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
94 http://www.openssl.org/news/changelog.html
95 */
96#if OPENSSL_VERSION_NUMBER >= 0x10001000L
97# define HAVE_TLSv1_2 1
98#else
99# define HAVE_TLSv1_2 0
100#endif
101
Christian Heimes470fba12013-11-28 15:12:15 +0100102/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100103 * This includes the SSL_set_SSL_CTX() function.
104 */
105#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
106# define HAVE_SNI 1
107#else
108# define HAVE_SNI 0
109#endif
110
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000111enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000112 /* these mirror ssl.h */
113 PY_SSL_ERROR_NONE,
114 PY_SSL_ERROR_SSL,
115 PY_SSL_ERROR_WANT_READ,
116 PY_SSL_ERROR_WANT_WRITE,
117 PY_SSL_ERROR_WANT_X509_LOOKUP,
118 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
119 PY_SSL_ERROR_ZERO_RETURN,
120 PY_SSL_ERROR_WANT_CONNECT,
121 /* start of non ssl.h errorcodes */
122 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
123 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
124 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000125};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000126
Thomas Woutersed03b412007-08-28 21:37:11 +0000127enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000128 PY_SSL_CLIENT,
129 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000130};
131
132enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000133 PY_SSL_CERT_NONE,
134 PY_SSL_CERT_OPTIONAL,
135 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000136};
137
138enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200140 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000141 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142#if HAVE_TLSv1_2
143 PY_SSL_VERSION_TLS1,
144 PY_SSL_VERSION_TLS1_1,
145 PY_SSL_VERSION_TLS1_2
146#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100149};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200150
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151#ifdef WITH_THREAD
152
153/* serves as a flag to see whether we've initialized the SSL thread support. */
154/* 0 means no, greater than 0 means yes */
155
156static unsigned int _ssl_locks_count = 0;
157
158#endif /* def WITH_THREAD */
159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160/* SSL socket object */
161
162#define X509_NAME_MAXLEN 256
163
164/* RAND_* APIs got added to OpenSSL in 0.9.5 */
165#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
166# define HAVE_OPENSSL_RAND 1
167#else
168# undef HAVE_OPENSSL_RAND
169#endif
170
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000171/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
172 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
173 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
174#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000175# define HAVE_SSL_CTX_CLEAR_OPTIONS
176#else
177# undef HAVE_SSL_CTX_CLEAR_OPTIONS
178#endif
179
Antoine Pitroud6494802011-07-21 01:11:30 +0200180/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
181 * older SSL, but let's be safe */
182#define PySSL_CB_MAXLEN 128
183
184/* SSL_get_finished got added to OpenSSL in 0.9.5 */
185#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
186# define HAVE_OPENSSL_FINISHED 1
187#else
188# define HAVE_OPENSSL_FINISHED 0
189#endif
190
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100191/* ECDH support got added to OpenSSL in 0.9.8 */
192#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
193# define OPENSSL_NO_ECDH
194#endif
195
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100196/* compression support got added to OpenSSL in 0.9.8 */
197#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
198# define OPENSSL_NO_COMP
199#endif
200
Christian Heimes2427b502013-11-23 11:24:32 +0100201/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
202#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
203# define HAVE_OPENSSL_VERIFY_PARAM
204#endif
205
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100206
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000207typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000208 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100210#ifdef OPENSSL_NPN_NEGOTIATED
211 char *npn_protocols;
212 int npn_protocols_len;
213#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100214#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200215 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100216#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100217 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000218} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000219
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220typedef struct {
221 PyObject_HEAD
222 PyObject *Socket; /* weakref to socket on which we're layered */
223 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100224 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200226 char shutdown_seen_zero;
227 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200228 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000230
Antoine Pitrou152efa22010-05-16 18:19:27 +0000231static PyTypeObject PySSLContext_Type;
232static PyTypeObject PySSLSocket_Type;
233
234static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
235static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000236static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000237 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000238static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
239static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000240
Antoine Pitrou152efa22010-05-16 18:19:27 +0000241#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
242#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000243
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000244typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000245 SOCKET_IS_NONBLOCKING,
246 SOCKET_IS_BLOCKING,
247 SOCKET_HAS_TIMED_OUT,
248 SOCKET_HAS_BEEN_CLOSED,
249 SOCKET_TOO_LARGE_FOR_SELECT,
250 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000251} timeout_state;
252
Thomas Woutersed03b412007-08-28 21:37:11 +0000253/* Wrap error strings with filename and line # */
254#define STRINGIFY1(x) #x
255#define STRINGIFY2(x) STRINGIFY1(x)
256#define ERRSTR1(x,y,z) (x ":" y ": " z)
257#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
258
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200259
260/*
261 * SSL errors.
262 */
263
264PyDoc_STRVAR(SSLError_doc,
265"An error occurred in the SSL implementation.");
266
267PyDoc_STRVAR(SSLZeroReturnError_doc,
268"SSL/TLS session closed cleanly.");
269
270PyDoc_STRVAR(SSLWantReadError_doc,
271"Non-blocking SSL socket needs to read more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLWantWriteError_doc,
275"Non-blocking SSL socket needs to write more data\n"
276"before the requested operation can be completed.");
277
278PyDoc_STRVAR(SSLSyscallError_doc,
279"System error when attempting SSL operation.");
280
281PyDoc_STRVAR(SSLEOFError_doc,
282"SSL/TLS connection terminated abruptly.");
283
284static PyObject *
285SSLError_str(PyOSErrorObject *self)
286{
287 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
288 Py_INCREF(self->strerror);
289 return self->strerror;
290 }
291 else
292 return PyObject_Str(self->args);
293}
294
295static PyType_Slot sslerror_type_slots[] = {
296 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
297 {Py_tp_doc, SSLError_doc},
298 {Py_tp_str, SSLError_str},
299 {0, 0},
300};
301
302static PyType_Spec sslerror_type_spec = {
303 "ssl.SSLError",
304 sizeof(PyOSErrorObject),
305 0,
306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
307 sslerror_type_slots
308};
309
310static void
311fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
312 int lineno, unsigned long errcode)
313{
314 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
315 PyObject *init_value, *msg, *key;
316 _Py_IDENTIFIER(reason);
317 _Py_IDENTIFIER(library);
318
319 if (errcode != 0) {
320 int lib, reason;
321
322 lib = ERR_GET_LIB(errcode);
323 reason = ERR_GET_REASON(errcode);
324 key = Py_BuildValue("ii", lib, reason);
325 if (key == NULL)
326 goto fail;
327 reason_obj = PyDict_GetItem(err_codes_to_names, key);
328 Py_DECREF(key);
329 if (reason_obj == NULL) {
330 /* XXX if reason < 100, it might reflect a library number (!!) */
331 PyErr_Clear();
332 }
333 key = PyLong_FromLong(lib);
334 if (key == NULL)
335 goto fail;
336 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
337 Py_DECREF(key);
338 if (lib_obj == NULL) {
339 PyErr_Clear();
340 }
341 if (errstr == NULL)
342 errstr = ERR_reason_error_string(errcode);
343 }
344 if (errstr == NULL)
345 errstr = "unknown error";
346
347 if (reason_obj && lib_obj)
348 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
349 lib_obj, reason_obj, errstr, lineno);
350 else if (lib_obj)
351 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
352 lib_obj, errstr, lineno);
353 else
354 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355 if (msg == NULL)
356 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100357
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200358 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100359 if (init_value == NULL)
360 goto fail;
361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 err_value = PyObject_CallObject(type, init_value);
363 Py_DECREF(init_value);
364 if (err_value == NULL)
365 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100366
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 if (reason_obj == NULL)
368 reason_obj = Py_None;
369 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
370 goto fail;
371 if (lib_obj == NULL)
372 lib_obj = Py_None;
373 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
374 goto fail;
375 PyErr_SetObject(type, err_value);
376fail:
377 Py_XDECREF(err_value);
378}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
380static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200383 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 int err;
386 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200390 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 if (obj->ssl != NULL) {
393 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 switch (err) {
396 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 errstr = "TLS/SSL connection has been closed (EOF)";
398 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 p = PY_SSL_ERROR_ZERO_RETURN;
400 break;
401 case SSL_ERROR_WANT_READ:
402 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200403 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 p = PY_SSL_ERROR_WANT_READ;
405 break;
406 case SSL_ERROR_WANT_WRITE:
407 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200408 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 errstr = "The operation did not complete (write)";
410 break;
411 case SSL_ERROR_WANT_X509_LOOKUP:
412 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000413 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 break;
415 case SSL_ERROR_WANT_CONNECT:
416 p = PY_SSL_ERROR_WANT_CONNECT;
417 errstr = "The operation did not complete (connect)";
418 break;
419 case SSL_ERROR_SYSCALL:
420 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 if (e == 0) {
422 PySocketSockObject *s
423 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
424 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200426 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000430 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000431 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000433 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200434 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200437 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000438 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 }
440 } else {
441 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 }
443 break;
444 }
445 case SSL_ERROR_SSL:
446 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448 if (e == 0)
449 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000450 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 break;
452 }
453 default:
454 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
455 errstr = "Invalid error code";
456 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000459 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000461}
462
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463static PyObject *
464_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 else
469 errcode = 0;
470 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000471 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000472 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473}
474
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200475/*
476 * SSL objects
477 */
478
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100480newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000481 enum py_ssl_server_or_client socket_type,
482 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100485 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200486 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000487
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 if (self == NULL)
490 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 self->peer_cert = NULL;
493 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100495 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200496 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200497 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100498 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 /* Make sure the SSL error state is initialized */
501 (void) ERR_get_state();
502 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000506 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100507 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100508 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000510#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200511 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000512#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200513 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000514
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100515#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000516 if (server_hostname != NULL)
517 SSL_set_tlsext_host_name(self->ssl, server_hostname);
518#endif
519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 /* If the socket is in non-blocking mode or timeout mode, set the BIO
521 * to non-blocking mode (blocking is the default)
522 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000523 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
525 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
526 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000528 PySSL_BEGIN_ALLOW_THREADS
529 if (socket_type == PY_SSL_CLIENT)
530 SSL_set_connect_state(self->ssl);
531 else
532 SSL_set_accept_state(self->ssl);
533 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000534
Antoine Pitroud6494802011-07-21 01:11:30 +0200535 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000536 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100537 if (self->Socket == NULL) {
538 Py_DECREF(self);
539 return NULL;
540 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542}
543
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000544/* SSL object methods */
545
Antoine Pitrou152efa22010-05-16 18:19:27 +0000546static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000547{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 int ret;
549 int err;
550 int sockstate, nonblocking;
551 PySocketSockObject *sock
552 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 if (((PyObject*)sock) == Py_None) {
555 _setSSLError("Underlying socket connection gone",
556 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
557 return NULL;
558 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000559 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 /* just in case the blocking state of the socket has been changed */
562 nonblocking = (sock->sock_timeout >= 0.0);
563 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
564 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 /* Actually negotiate SSL connection */
567 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000569 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 ret = SSL_do_handshake(self->ssl);
571 err = SSL_get_error(self->ssl, ret);
572 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000573 if (PyErr_CheckSignals())
574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 if (err == SSL_ERROR_WANT_READ) {
576 sockstate = check_socket_and_wait_for_timeout(sock, 0);
577 } else if (err == SSL_ERROR_WANT_WRITE) {
578 sockstate = check_socket_and_wait_for_timeout(sock, 1);
579 } else {
580 sockstate = SOCKET_OPERATION_OK;
581 }
582 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000583 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000584 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000585 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
587 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000588 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000589 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
591 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000592 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000593 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
595 break;
596 }
597 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000598 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 if (ret < 1)
600 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 if (self->peer_cert)
603 X509_free (self->peer_cert);
604 PySSL_BEGIN_ALLOW_THREADS
605 self->peer_cert = SSL_get_peer_certificate(self->ssl);
606 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200607 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608
609 Py_INCREF(Py_None);
610 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000611
612error:
613 Py_DECREF(sock);
614 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000615}
616
Thomas Woutersed03b412007-08-28 21:37:11 +0000617static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 char namebuf[X509_NAME_MAXLEN];
621 int buflen;
622 PyObject *name_obj;
623 PyObject *value_obj;
624 PyObject *attr;
625 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
628 if (buflen < 0) {
629 _setSSLError(NULL, 0, __FILE__, __LINE__);
630 goto fail;
631 }
632 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
633 if (name_obj == NULL)
634 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
637 if (buflen < 0) {
638 _setSSLError(NULL, 0, __FILE__, __LINE__);
639 Py_DECREF(name_obj);
640 goto fail;
641 }
642 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000643 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 OPENSSL_free(valuebuf);
645 if (value_obj == NULL) {
646 Py_DECREF(name_obj);
647 goto fail;
648 }
649 attr = PyTuple_New(2);
650 if (attr == NULL) {
651 Py_DECREF(name_obj);
652 Py_DECREF(value_obj);
653 goto fail;
654 }
655 PyTuple_SET_ITEM(attr, 0, name_obj);
656 PyTuple_SET_ITEM(attr, 1, value_obj);
657 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000658
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000661}
662
663static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000665{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
667 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
668 PyObject *rdnt;
669 PyObject *attr = NULL; /* tuple to hold an attribute */
670 int entry_count = X509_NAME_entry_count(xname);
671 X509_NAME_ENTRY *entry;
672 ASN1_OBJECT *name;
673 ASN1_STRING *value;
674 int index_counter;
675 int rdn_level = -1;
676 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 dn = PyList_New(0);
679 if (dn == NULL)
680 return NULL;
681 /* now create another tuple to hold the top-level RDN */
682 rdn = PyList_New(0);
683 if (rdn == NULL)
684 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 for (index_counter = 0;
687 index_counter < entry_count;
688 index_counter++)
689 {
690 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 /* check to see if we've gotten to a new RDN */
693 if (rdn_level >= 0) {
694 if (rdn_level != entry->set) {
695 /* yes, new RDN */
696 /* add old RDN to DN */
697 rdnt = PyList_AsTuple(rdn);
698 Py_DECREF(rdn);
699 if (rdnt == NULL)
700 goto fail0;
701 retcode = PyList_Append(dn, rdnt);
702 Py_DECREF(rdnt);
703 if (retcode < 0)
704 goto fail0;
705 /* create new RDN */
706 rdn = PyList_New(0);
707 if (rdn == NULL)
708 goto fail0;
709 }
710 }
711 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 /* now add this attribute to the current RDN */
714 name = X509_NAME_ENTRY_get_object(entry);
715 value = X509_NAME_ENTRY_get_data(entry);
716 attr = _create_tuple_for_attribute(name, value);
717 /*
718 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
719 entry->set,
720 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
721 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
722 */
723 if (attr == NULL)
724 goto fail1;
725 retcode = PyList_Append(rdn, attr);
726 Py_DECREF(attr);
727 if (retcode < 0)
728 goto fail1;
729 }
730 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100731 if (rdn != NULL) {
732 if (PyList_GET_SIZE(rdn) > 0) {
733 rdnt = PyList_AsTuple(rdn);
734 Py_DECREF(rdn);
735 if (rdnt == NULL)
736 goto fail0;
737 retcode = PyList_Append(dn, rdnt);
738 Py_DECREF(rdnt);
739 if (retcode < 0)
740 goto fail0;
741 }
742 else {
743 Py_DECREF(rdn);
744 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 /* convert list to tuple */
748 rdnt = PyList_AsTuple(dn);
749 Py_DECREF(dn);
750 if (rdnt == NULL)
751 return NULL;
752 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753
754 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
757 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 Py_XDECREF(dn);
759 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760}
761
762static PyObject *
763_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 /* this code follows the procedure outlined in
766 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
767 function to extract the STACK_OF(GENERAL_NAME),
768 then iterates through the stack to add the
769 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 int i, j;
772 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200773 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 X509_EXTENSION *ext = NULL;
775 GENERAL_NAMES *names = NULL;
776 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000777 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 BIO *biobuf = NULL;
779 char buf[2048];
780 char *vptr;
781 int len;
782 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000783#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000785#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000787#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 if (certificate == NULL)
790 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 /* get a memory buffer */
793 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200795 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 while ((i = X509_get_ext_by_NID(
797 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 if (peer_alt_names == Py_None) {
800 peer_alt_names = PyList_New(0);
801 if (peer_alt_names == NULL)
802 goto fail;
803 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 /* now decode the altName */
806 ext = X509_get_ext(certificate, i);
807 if(!(method = X509V3_EXT_get(ext))) {
808 PyErr_SetString
809 (PySSLErrorObject,
810 ERRSTR("No method for internalizing subjectAltName!"));
811 goto fail;
812 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 p = ext->value->data;
815 if (method->it)
816 names = (GENERAL_NAMES*)
817 (ASN1_item_d2i(NULL,
818 &p,
819 ext->value->length,
820 ASN1_ITEM_ptr(method->it)));
821 else
822 names = (GENERAL_NAMES*)
823 (method->d2i(NULL,
824 &p,
825 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200829 int gntype;
830 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200833 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200834 switch (gntype) {
835 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 /* we special-case DirName as a tuple of
837 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 t = PyTuple_New(2);
840 if (t == NULL) {
841 goto fail;
842 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 v = PyUnicode_FromString("DirName");
845 if (v == NULL) {
846 Py_DECREF(t);
847 goto fail;
848 }
849 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 v = _create_tuple_for_X509_NAME (name->d.dirn);
852 if (v == NULL) {
853 Py_DECREF(t);
854 goto fail;
855 }
856 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200857 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000858
Christian Heimes824f7f32013-08-17 00:54:47 +0200859 case GEN_EMAIL:
860 case GEN_DNS:
861 case GEN_URI:
862 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
863 correctly, CVE-2013-4238 */
864 t = PyTuple_New(2);
865 if (t == NULL)
866 goto fail;
867 switch (gntype) {
868 case GEN_EMAIL:
869 v = PyUnicode_FromString("email");
870 as = name->d.rfc822Name;
871 break;
872 case GEN_DNS:
873 v = PyUnicode_FromString("DNS");
874 as = name->d.dNSName;
875 break;
876 case GEN_URI:
877 v = PyUnicode_FromString("URI");
878 as = name->d.uniformResourceIdentifier;
879 break;
880 }
881 if (v == NULL) {
882 Py_DECREF(t);
883 goto fail;
884 }
885 PyTuple_SET_ITEM(t, 0, v);
886 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
887 ASN1_STRING_length(as));
888 if (v == NULL) {
889 Py_DECREF(t);
890 goto fail;
891 }
892 PyTuple_SET_ITEM(t, 1, v);
893 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200897 switch (gntype) {
898 /* check for new general name type */
899 case GEN_OTHERNAME:
900 case GEN_X400:
901 case GEN_EDIPARTY:
902 case GEN_IPADD:
903 case GEN_RID:
904 break;
905 default:
906 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
907 "Unknown general name type %d",
908 gntype) == -1) {
909 goto fail;
910 }
911 break;
912 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 (void) BIO_reset(biobuf);
914 GENERAL_NAME_print(biobuf, name);
915 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
916 if (len < 0) {
917 _setSSLError(NULL, 0, __FILE__, __LINE__);
918 goto fail;
919 }
920 vptr = strchr(buf, ':');
921 if (vptr == NULL)
922 goto fail;
923 t = PyTuple_New(2);
924 if (t == NULL)
925 goto fail;
926 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
927 if (v == NULL) {
928 Py_DECREF(t);
929 goto fail;
930 }
931 PyTuple_SET_ITEM(t, 0, v);
932 v = PyUnicode_FromStringAndSize((vptr + 1),
933 (len - (vptr - buf + 1)));
934 if (v == NULL) {
935 Py_DECREF(t);
936 goto fail;
937 }
938 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200939 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 if (PyList_Append(peer_alt_names, t) < 0) {
945 Py_DECREF(t);
946 goto fail;
947 }
948 Py_DECREF(t);
949 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100950 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 }
952 BIO_free(biobuf);
953 if (peer_alt_names != Py_None) {
954 v = PyList_AsTuple(peer_alt_names);
955 Py_DECREF(peer_alt_names);
956 return v;
957 } else {
958 return peer_alt_names;
959 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000960
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961
962 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 if (biobuf != NULL)
964 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 if (peer_alt_names != Py_None) {
967 Py_XDECREF(peer_alt_names);
968 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971}
972
973static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100974_get_aia_uri(X509 *certificate, int nid) {
975 PyObject *lst = NULL, *ostr = NULL;
976 int i, result;
977 AUTHORITY_INFO_ACCESS *info;
978
979 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
980 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
981 return Py_None;
982 }
983
984 if ((lst = PyList_New(0)) == NULL) {
985 goto fail;
986 }
987
988 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
989 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
990 ASN1_IA5STRING *uri;
991
992 if ((OBJ_obj2nid(ad->method) != nid) ||
993 (ad->location->type != GEN_URI)) {
994 continue;
995 }
996 uri = ad->location->d.uniformResourceIdentifier;
997 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
998 uri->length);
999 if (ostr == NULL) {
1000 goto fail;
1001 }
1002 result = PyList_Append(lst, ostr);
1003 Py_DECREF(ostr);
1004 if (result < 0) {
1005 goto fail;
1006 }
1007 }
1008 AUTHORITY_INFO_ACCESS_free(info);
1009
1010 /* convert to tuple or None */
1011 if (PyList_Size(lst) == 0) {
1012 Py_DECREF(lst);
1013 return Py_None;
1014 } else {
1015 PyObject *tup;
1016 tup = PyList_AsTuple(lst);
1017 Py_DECREF(lst);
1018 return tup;
1019 }
1020
1021 fail:
1022 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001023 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001024 return NULL;
1025}
1026
1027static PyObject *
1028_get_crl_dp(X509 *certificate) {
1029 STACK_OF(DIST_POINT) *dps;
1030 int i, j, result;
1031 PyObject *lst;
1032
Christian Heimes949ec142013-11-21 16:26:51 +01001033#if OPENSSL_VERSION_NUMBER < 0x10001000L
1034 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1035 NULL, NULL);
1036#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001037 /* Calls x509v3_cache_extensions and sets up crldp */
1038 X509_check_ca(certificate);
1039 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001040#endif
1041
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001042 if (dps == NULL) {
1043 return Py_None;
1044 }
1045
1046 if ((lst = PyList_New(0)) == NULL) {
1047 return NULL;
1048 }
1049
1050 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1051 DIST_POINT *dp;
1052 STACK_OF(GENERAL_NAME) *gns;
1053
1054 dp = sk_DIST_POINT_value(dps, i);
1055 gns = dp->distpoint->name.fullname;
1056
1057 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1058 GENERAL_NAME *gn;
1059 ASN1_IA5STRING *uri;
1060 PyObject *ouri;
1061
1062 gn = sk_GENERAL_NAME_value(gns, j);
1063 if (gn->type != GEN_URI) {
1064 continue;
1065 }
1066 uri = gn->d.uniformResourceIdentifier;
1067 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1068 uri->length);
1069 if (ouri == NULL) {
1070 Py_DECREF(lst);
1071 return NULL;
1072 }
1073 result = PyList_Append(lst, ouri);
1074 Py_DECREF(ouri);
1075 if (result < 0) {
1076 Py_DECREF(lst);
1077 return NULL;
1078 }
1079 }
1080 }
1081 /* convert to tuple or None */
1082 if (PyList_Size(lst) == 0) {
1083 Py_DECREF(lst);
1084 return Py_None;
1085 } else {
1086 PyObject *tup;
1087 tup = PyList_AsTuple(lst);
1088 Py_DECREF(lst);
1089 return tup;
1090 }
1091}
1092
1093static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001094_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 PyObject *retval = NULL;
1097 BIO *biobuf = NULL;
1098 PyObject *peer;
1099 PyObject *peer_alt_names = NULL;
1100 PyObject *issuer;
1101 PyObject *version;
1102 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001103 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 ASN1_INTEGER *serialNumber;
1105 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001106 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 ASN1_TIME *notBefore, *notAfter;
1108 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 retval = PyDict_New();
1111 if (retval == NULL)
1112 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 peer = _create_tuple_for_X509_NAME(
1115 X509_get_subject_name(certificate));
1116 if (peer == NULL)
1117 goto fail0;
1118 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1119 Py_DECREF(peer);
1120 goto fail0;
1121 }
1122 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001123
Antoine Pitroufb046912010-11-09 20:21:19 +00001124 issuer = _create_tuple_for_X509_NAME(
1125 X509_get_issuer_name(certificate));
1126 if (issuer == NULL)
1127 goto fail0;
1128 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001130 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001132 Py_DECREF(issuer);
1133
1134 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001135 if (version == NULL)
1136 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001137 if (PyDict_SetItemString(retval, "version", version) < 0) {
1138 Py_DECREF(version);
1139 goto fail0;
1140 }
1141 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 /* get a memory buffer */
1144 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001145
Antoine Pitroufb046912010-11-09 20:21:19 +00001146 (void) BIO_reset(biobuf);
1147 serialNumber = X509_get_serialNumber(certificate);
1148 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1149 i2a_ASN1_INTEGER(biobuf, serialNumber);
1150 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1151 if (len < 0) {
1152 _setSSLError(NULL, 0, __FILE__, __LINE__);
1153 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001155 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1156 if (sn_obj == NULL)
1157 goto fail1;
1158 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1159 Py_DECREF(sn_obj);
1160 goto fail1;
1161 }
1162 Py_DECREF(sn_obj);
1163
1164 (void) BIO_reset(biobuf);
1165 notBefore = X509_get_notBefore(certificate);
1166 ASN1_TIME_print(biobuf, notBefore);
1167 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1168 if (len < 0) {
1169 _setSSLError(NULL, 0, __FILE__, __LINE__);
1170 goto fail1;
1171 }
1172 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1173 if (pnotBefore == NULL)
1174 goto fail1;
1175 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1176 Py_DECREF(pnotBefore);
1177 goto fail1;
1178 }
1179 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 (void) BIO_reset(biobuf);
1182 notAfter = X509_get_notAfter(certificate);
1183 ASN1_TIME_print(biobuf, notAfter);
1184 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1185 if (len < 0) {
1186 _setSSLError(NULL, 0, __FILE__, __LINE__);
1187 goto fail1;
1188 }
1189 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1190 if (pnotAfter == NULL)
1191 goto fail1;
1192 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1193 Py_DECREF(pnotAfter);
1194 goto fail1;
1195 }
1196 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 peer_alt_names = _get_peer_alt_names(certificate);
1201 if (peer_alt_names == NULL)
1202 goto fail1;
1203 else if (peer_alt_names != Py_None) {
1204 if (PyDict_SetItemString(retval, "subjectAltName",
1205 peer_alt_names) < 0) {
1206 Py_DECREF(peer_alt_names);
1207 goto fail1;
1208 }
1209 Py_DECREF(peer_alt_names);
1210 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001211
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001212 /* Authority Information Access: OCSP URIs */
1213 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1214 if (obj == NULL) {
1215 goto fail1;
1216 } else if (obj != Py_None) {
1217 result = PyDict_SetItemString(retval, "OCSP", obj);
1218 Py_DECREF(obj);
1219 if (result < 0) {
1220 goto fail1;
1221 }
1222 }
1223
1224 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1225 if (obj == NULL) {
1226 goto fail1;
1227 } else if (obj != Py_None) {
1228 result = PyDict_SetItemString(retval, "caIssuers", obj);
1229 Py_DECREF(obj);
1230 if (result < 0) {
1231 goto fail1;
1232 }
1233 }
1234
1235 /* CDP (CRL distribution points) */
1236 obj = _get_crl_dp(certificate);
1237 if (obj == NULL) {
1238 goto fail1;
1239 } else if (obj != Py_None) {
1240 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1241 Py_DECREF(obj);
1242 if (result < 0) {
1243 goto fail1;
1244 }
1245 }
1246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 BIO_free(biobuf);
1248 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001249
1250 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 if (biobuf != NULL)
1252 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001253 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 Py_XDECREF(retval);
1255 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001256}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001257
Christian Heimes9a5395a2013-06-17 15:44:12 +02001258static PyObject *
1259_certificate_to_der(X509 *certificate)
1260{
1261 unsigned char *bytes_buf = NULL;
1262 int len;
1263 PyObject *retval;
1264
1265 bytes_buf = NULL;
1266 len = i2d_X509(certificate, &bytes_buf);
1267 if (len < 0) {
1268 _setSSLError(NULL, 0, __FILE__, __LINE__);
1269 return NULL;
1270 }
1271 /* this is actually an immutable bytes sequence */
1272 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1273 OPENSSL_free(bytes_buf);
1274 return retval;
1275}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276
1277static PyObject *
1278PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001281 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 X509 *x=NULL;
1283 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
Antoine Pitroufb046912010-11-09 20:21:19 +00001285 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1286 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1290 PyErr_SetString(PySSLErrorObject,
1291 "Can't malloc memory to read file");
1292 goto fail0;
1293 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001294
Victor Stinner3800e1e2010-05-16 21:23:48 +00001295 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 PyErr_SetString(PySSLErrorObject,
1297 "Can't open file");
1298 goto fail0;
1299 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1302 if (x == NULL) {
1303 PyErr_SetString(PySSLErrorObject,
1304 "Error decoding PEM-encoded file");
1305 goto fail0;
1306 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001307
Antoine Pitroufb046912010-11-09 20:21:19 +00001308 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001309 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001310
1311 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001312 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 if (cert != NULL) BIO_free(cert);
1314 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315}
1316
1317
1318static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001319PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001322 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323
Antoine Pitrou721738f2012-08-15 23:20:39 +02001324 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326
Antoine Pitrou20b85552013-09-29 19:50:53 +02001327 if (!self->handshake_done) {
1328 PyErr_SetString(PyExc_ValueError,
1329 "handshake not done yet");
1330 return NULL;
1331 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 if (!self->peer_cert)
1333 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001334
Antoine Pitrou721738f2012-08-15 23:20:39 +02001335 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001337 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001339 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 if ((verification & SSL_VERIFY_PEER) == 0)
1341 return PyDict_New();
1342 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001343 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345}
1346
1347PyDoc_STRVAR(PySSL_peercert_doc,
1348"peer_certificate([der=False]) -> certificate\n\
1349\n\
1350Returns the certificate for the peer. If no certificate was provided,\n\
1351returns None. If a certificate was provided, but not validated, returns\n\
1352an empty dictionary. Otherwise returns a dict containing information\n\
1353about the peer certificate.\n\
1354\n\
1355If the optional argument is True, returns a DER-encoded copy of the\n\
1356peer certificate, or None if no certificate was provided. This will\n\
1357return the certificate even if it wasn't validated.");
1358
Antoine Pitrou152efa22010-05-16 18:19:27 +00001359static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001362 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 char *cipher_name;
1364 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001367 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 current = SSL_get_current_cipher(self->ssl);
1369 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001370 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 retval = PyTuple_New(3);
1373 if (retval == NULL)
1374 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 cipher_name = (char *) SSL_CIPHER_get_name(current);
1377 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001378 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 PyTuple_SET_ITEM(retval, 0, Py_None);
1380 } else {
1381 v = PyUnicode_FromString(cipher_name);
1382 if (v == NULL)
1383 goto fail0;
1384 PyTuple_SET_ITEM(retval, 0, v);
1385 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001386 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001388 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 PyTuple_SET_ITEM(retval, 1, Py_None);
1390 } else {
1391 v = PyUnicode_FromString(cipher_protocol);
1392 if (v == NULL)
1393 goto fail0;
1394 PyTuple_SET_ITEM(retval, 1, v);
1395 }
1396 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1397 if (v == NULL)
1398 goto fail0;
1399 PyTuple_SET_ITEM(retval, 2, v);
1400 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001401
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 Py_DECREF(retval);
1404 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001405}
1406
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001407#ifdef OPENSSL_NPN_NEGOTIATED
1408static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1409 const unsigned char *out;
1410 unsigned int outlen;
1411
Victor Stinner4569cd52013-06-23 14:58:43 +02001412 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001413 &out, &outlen);
1414
1415 if (out == NULL)
1416 Py_RETURN_NONE;
1417 return PyUnicode_FromStringAndSize((char *) out, outlen);
1418}
1419#endif
1420
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001421static PyObject *PySSL_compression(PySSLSocket *self) {
1422#ifdef OPENSSL_NO_COMP
1423 Py_RETURN_NONE;
1424#else
1425 const COMP_METHOD *comp_method;
1426 const char *short_name;
1427
1428 if (self->ssl == NULL)
1429 Py_RETURN_NONE;
1430 comp_method = SSL_get_current_compression(self->ssl);
1431 if (comp_method == NULL || comp_method->type == NID_undef)
1432 Py_RETURN_NONE;
1433 short_name = OBJ_nid2sn(comp_method->type);
1434 if (short_name == NULL)
1435 Py_RETURN_NONE;
1436 return PyUnicode_DecodeFSDefault(short_name);
1437#endif
1438}
1439
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001440static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1441 Py_INCREF(self->ctx);
1442 return self->ctx;
1443}
1444
1445static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1446 void *closure) {
1447
1448 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001449#if !HAVE_SNI
1450 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1451 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001452 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001453#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001454 Py_INCREF(value);
1455 Py_DECREF(self->ctx);
1456 self->ctx = (PySSLContext *) value;
1457 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001458#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001459 } else {
1460 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1461 return -1;
1462 }
1463
1464 return 0;
1465}
1466
1467PyDoc_STRVAR(PySSL_set_context_doc,
1468"_setter_context(ctx)\n\
1469\
1470This changes the context associated with the SSLSocket. This is typically\n\
1471used from within a callback function set by the set_servername_callback\n\
1472on the SSLContext to change the certificate information associated with the\n\
1473SSLSocket before the cryptographic exchange handshake messages\n");
1474
1475
1476
Antoine Pitrou152efa22010-05-16 18:19:27 +00001477static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 if (self->peer_cert) /* Possible not to have one? */
1480 X509_free (self->peer_cert);
1481 if (self->ssl)
1482 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001484 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001486}
1487
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001488/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001489 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001490 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001491 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001492
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001493static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001494check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001495{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 fd_set fds;
1497 struct timeval tv;
1498 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1501 if (s->sock_timeout < 0.0)
1502 return SOCKET_IS_BLOCKING;
1503 else if (s->sock_timeout == 0.0)
1504 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 /* Guard against closed socket */
1507 if (s->sock_fd < 0)
1508 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 /* Prefer poll, if available, since you can poll() any fd
1511 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001512#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 {
1514 struct pollfd pollfd;
1515 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 pollfd.fd = s->sock_fd;
1518 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 /* s->sock_timeout is in seconds, timeout in ms */
1521 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1522 PySSL_BEGIN_ALLOW_THREADS
1523 rc = poll(&pollfd, 1, timeout);
1524 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 goto normal_return;
1527 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001528#endif
1529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001531 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 /* Construct the arguments to select */
1535 tv.tv_sec = (int)s->sock_timeout;
1536 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1537 FD_ZERO(&fds);
1538 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 /* See if the socket is ready */
1541 PySSL_BEGIN_ALLOW_THREADS
1542 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001543 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1544 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001546 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1547 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001549
Bill Janssen6e027db2007-11-15 22:23:56 +00001550#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001551normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001552#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1554 (when we are able to write or when there's something to read) */
1555 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001556}
1557
Antoine Pitrou152efa22010-05-16 18:19:27 +00001558static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001559{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 Py_buffer buf;
1561 int len;
1562 int sockstate;
1563 int err;
1564 int nonblocking;
1565 PySocketSockObject *sock
1566 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 if (((PyObject*)sock) == Py_None) {
1569 _setSSLError("Underlying socket connection gone",
1570 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1571 return NULL;
1572 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001573 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001575 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1576 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001578 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579
Victor Stinner6efa9652013-06-25 00:42:31 +02001580 if (buf.len > INT_MAX) {
1581 PyErr_Format(PyExc_OverflowError,
1582 "string longer than %d bytes", INT_MAX);
1583 goto error;
1584 }
1585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 /* just in case the blocking state of the socket has been changed */
1587 nonblocking = (sock->sock_timeout >= 0.0);
1588 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1589 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1590
1591 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1592 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001593 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001594 "The write operation timed out");
1595 goto error;
1596 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1597 PyErr_SetString(PySSLErrorObject,
1598 "Underlying socket has been closed.");
1599 goto error;
1600 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1601 PyErr_SetString(PySSLErrorObject,
1602 "Underlying socket too large for select().");
1603 goto error;
1604 }
1605 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001607 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001608 err = SSL_get_error(self->ssl, len);
1609 PySSL_END_ALLOW_THREADS
1610 if (PyErr_CheckSignals()) {
1611 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001612 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001614 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001616 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 } else {
1618 sockstate = SOCKET_OPERATION_OK;
1619 }
1620 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001621 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 "The write operation timed out");
1623 goto error;
1624 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1625 PyErr_SetString(PySSLErrorObject,
1626 "Underlying socket has been closed.");
1627 goto error;
1628 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1629 break;
1630 }
1631 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001632
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001633 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634 PyBuffer_Release(&buf);
1635 if (len > 0)
1636 return PyLong_FromLong(len);
1637 else
1638 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001639
1640error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001641 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 PyBuffer_Release(&buf);
1643 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001644}
1645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001646PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001647"write(s) -> len\n\
1648\n\
1649Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001650of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001651
Antoine Pitrou152efa22010-05-16 18:19:27 +00001652static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001653{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001654 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001656 PySSL_BEGIN_ALLOW_THREADS
1657 count = SSL_pending(self->ssl);
1658 PySSL_END_ALLOW_THREADS
1659 if (count < 0)
1660 return PySSL_SetError(self, count, __FILE__, __LINE__);
1661 else
1662 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001663}
1664
1665PyDoc_STRVAR(PySSL_SSLpending_doc,
1666"pending() -> count\n\
1667\n\
1668Returns the number of already decrypted bytes available for read,\n\
1669pending on the connection.\n");
1670
Antoine Pitrou152efa22010-05-16 18:19:27 +00001671static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001672{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 PyObject *dest = NULL;
1674 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001676 int len, count;
1677 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 int sockstate;
1679 int err;
1680 int nonblocking;
1681 PySocketSockObject *sock
1682 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 if (((PyObject*)sock) == Py_None) {
1685 _setSSLError("Underlying socket connection gone",
1686 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1687 return NULL;
1688 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001689 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001691 buf.obj = NULL;
1692 buf.buf = NULL;
1693 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001694 goto error;
1695
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001696 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1697 dest = PyBytes_FromStringAndSize(NULL, len);
1698 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001699 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001700 mem = PyBytes_AS_STRING(dest);
1701 }
1702 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001704 mem = buf.buf;
1705 if (len <= 0 || len > buf.len) {
1706 len = (int) buf.len;
1707 if (buf.len != len) {
1708 PyErr_SetString(PyExc_OverflowError,
1709 "maximum length can't fit in a C 'int'");
1710 goto error;
1711 }
1712 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 }
1714
1715 /* just in case the blocking state of the socket has been changed */
1716 nonblocking = (sock->sock_timeout >= 0.0);
1717 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1718 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 PySSL_BEGIN_ALLOW_THREADS
1722 count = SSL_read(self->ssl, mem, len);
1723 err = SSL_get_error(self->ssl, count);
1724 PySSL_END_ALLOW_THREADS
1725 if (PyErr_CheckSignals())
1726 goto error;
1727 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001728 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001730 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001731 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1732 (SSL_get_shutdown(self->ssl) ==
1733 SSL_RECEIVED_SHUTDOWN))
1734 {
1735 count = 0;
1736 goto done;
1737 } else {
1738 sockstate = SOCKET_OPERATION_OK;
1739 }
1740 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001741 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 "The read operation timed out");
1743 goto error;
1744 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1745 break;
1746 }
1747 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1748 if (count <= 0) {
1749 PySSL_SetError(self, count, __FILE__, __LINE__);
1750 goto error;
1751 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001752
1753done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001754 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001756 _PyBytes_Resize(&dest, count);
1757 return dest;
1758 }
1759 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 PyBuffer_Release(&buf);
1761 return PyLong_FromLong(count);
1762 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001763
1764error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001765 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001766 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001767 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001768 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001769 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001771}
1772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001773PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001774"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001775\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001776Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001777
Antoine Pitrou152efa22010-05-16 18:19:27 +00001778static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001779{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 int err, ssl_err, sockstate, nonblocking;
1781 int zeros = 0;
1782 PySocketSockObject *sock
1783 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 /* Guard against closed socket */
1786 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1787 _setSSLError("Underlying socket connection gone",
1788 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1789 return NULL;
1790 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001791 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792
1793 /* Just in case the blocking state of the socket has been changed */
1794 nonblocking = (sock->sock_timeout >= 0.0);
1795 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1796 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1797
1798 while (1) {
1799 PySSL_BEGIN_ALLOW_THREADS
1800 /* Disable read-ahead so that unwrap can work correctly.
1801 * Otherwise OpenSSL might read in too much data,
1802 * eating clear text data that happens to be
1803 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001804 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 * function is used and the shutdown_seen_zero != 0
1806 * condition is met.
1807 */
1808 if (self->shutdown_seen_zero)
1809 SSL_set_read_ahead(self->ssl, 0);
1810 err = SSL_shutdown(self->ssl);
1811 PySSL_END_ALLOW_THREADS
1812 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1813 if (err > 0)
1814 break;
1815 if (err == 0) {
1816 /* Don't loop endlessly; instead preserve legacy
1817 behaviour of trying SSL_shutdown() only twice.
1818 This looks necessary for OpenSSL < 0.9.8m */
1819 if (++zeros > 1)
1820 break;
1821 /* Shutdown was sent, now try receiving */
1822 self->shutdown_seen_zero = 1;
1823 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001824 }
1825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 /* Possibly retry shutdown until timeout or failure */
1827 ssl_err = SSL_get_error(self->ssl, err);
1828 if (ssl_err == SSL_ERROR_WANT_READ)
1829 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1830 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1831 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1832 else
1833 break;
1834 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1835 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001836 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 "The read operation timed out");
1838 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001839 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001841 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 }
1843 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1844 PyErr_SetString(PySSLErrorObject,
1845 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001846 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 }
1848 else if (sockstate != SOCKET_OPERATION_OK)
1849 /* Retain the SSL error code */
1850 break;
1851 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001852
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001853 if (err < 0) {
1854 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001857 else
1858 /* It's already INCREF'ed */
1859 return (PyObject *) sock;
1860
1861error:
1862 Py_DECREF(sock);
1863 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001864}
1865
1866PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1867"shutdown(s) -> socket\n\
1868\n\
1869Does the SSL shutdown handshake with the remote end, and returns\n\
1870the underlying socket object.");
1871
Antoine Pitroud6494802011-07-21 01:11:30 +02001872#if HAVE_OPENSSL_FINISHED
1873static PyObject *
1874PySSL_tls_unique_cb(PySSLSocket *self)
1875{
1876 PyObject *retval = NULL;
1877 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001878 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001879
1880 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1881 /* if session is resumed XOR we are the client */
1882 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1883 }
1884 else {
1885 /* if a new session XOR we are the server */
1886 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1887 }
1888
1889 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001890 if (len == 0)
1891 Py_RETURN_NONE;
1892
1893 retval = PyBytes_FromStringAndSize(buf, len);
1894
1895 return retval;
1896}
1897
1898PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1899"tls_unique_cb() -> bytes\n\
1900\n\
1901Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1902\n\
1903If the TLS handshake is not yet complete, None is returned");
1904
1905#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001906
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001907static PyGetSetDef ssl_getsetlist[] = {
1908 {"context", (getter) PySSL_get_context,
1909 (setter) PySSL_set_context, PySSL_set_context_doc},
1910 {NULL}, /* sentinel */
1911};
1912
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001913static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1915 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1916 PySSL_SSLwrite_doc},
1917 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1918 PySSL_SSLread_doc},
1919 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1920 PySSL_SSLpending_doc},
1921 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1922 PySSL_peercert_doc},
1923 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001924#ifdef OPENSSL_NPN_NEGOTIATED
1925 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1926#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001927 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1929 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001930#if HAVE_OPENSSL_FINISHED
1931 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1932 PySSL_tls_unique_cb_doc},
1933#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001935};
1936
Antoine Pitrou152efa22010-05-16 18:19:27 +00001937static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001939 "_ssl._SSLSocket", /*tp_name*/
1940 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 0, /*tp_itemsize*/
1942 /* methods */
1943 (destructor)PySSL_dealloc, /*tp_dealloc*/
1944 0, /*tp_print*/
1945 0, /*tp_getattr*/
1946 0, /*tp_setattr*/
1947 0, /*tp_reserved*/
1948 0, /*tp_repr*/
1949 0, /*tp_as_number*/
1950 0, /*tp_as_sequence*/
1951 0, /*tp_as_mapping*/
1952 0, /*tp_hash*/
1953 0, /*tp_call*/
1954 0, /*tp_str*/
1955 0, /*tp_getattro*/
1956 0, /*tp_setattro*/
1957 0, /*tp_as_buffer*/
1958 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1959 0, /*tp_doc*/
1960 0, /*tp_traverse*/
1961 0, /*tp_clear*/
1962 0, /*tp_richcompare*/
1963 0, /*tp_weaklistoffset*/
1964 0, /*tp_iter*/
1965 0, /*tp_iternext*/
1966 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001967 0, /*tp_members*/
1968 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001969};
1970
Antoine Pitrou152efa22010-05-16 18:19:27 +00001971
1972/*
1973 * _SSLContext objects
1974 */
1975
1976static PyObject *
1977context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1978{
1979 char *kwlist[] = {"protocol", NULL};
1980 PySSLContext *self;
1981 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001982 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001983 SSL_CTX *ctx = NULL;
1984
1985 if (!PyArg_ParseTupleAndKeywords(
1986 args, kwds, "i:_SSLContext", kwlist,
1987 &proto_version))
1988 return NULL;
1989
1990 PySSL_BEGIN_ALLOW_THREADS
1991 if (proto_version == PY_SSL_VERSION_TLS1)
1992 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001993#if HAVE_TLSv1_2
1994 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1995 ctx = SSL_CTX_new(TLSv1_1_method());
1996 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1997 ctx = SSL_CTX_new(TLSv1_2_method());
1998#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05001999#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002000 else if (proto_version == PY_SSL_VERSION_SSL3)
2001 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002002#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002003#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002004 else if (proto_version == PY_SSL_VERSION_SSL2)
2005 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002006#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002007 else if (proto_version == PY_SSL_VERSION_SSL23)
2008 ctx = SSL_CTX_new(SSLv23_method());
2009 else
2010 proto_version = -1;
2011 PySSL_END_ALLOW_THREADS
2012
2013 if (proto_version == -1) {
2014 PyErr_SetString(PyExc_ValueError,
2015 "invalid protocol version");
2016 return NULL;
2017 }
2018 if (ctx == NULL) {
2019 PyErr_SetString(PySSLErrorObject,
2020 "failed to allocate SSL context");
2021 return NULL;
2022 }
2023
2024 assert(type != NULL && type->tp_alloc != NULL);
2025 self = (PySSLContext *) type->tp_alloc(type, 0);
2026 if (self == NULL) {
2027 SSL_CTX_free(ctx);
2028 return NULL;
2029 }
2030 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002031#ifdef OPENSSL_NPN_NEGOTIATED
2032 self->npn_protocols = NULL;
2033#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002034#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002035 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002036#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002037 /* Don't check host name by default */
2038 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002039 /* Defaults */
2040 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002041 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2042 if (proto_version != PY_SSL_VERSION_SSL2)
2043 options |= SSL_OP_NO_SSLv2;
2044 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002045
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002046#ifndef OPENSSL_NO_ECDH
2047 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2048 prime256v1 by default. This is Apache mod_ssl's initialization
2049 policy, so we should be safe. */
2050#if defined(SSL_CTX_set_ecdh_auto)
2051 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2052#else
2053 {
2054 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2055 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2056 EC_KEY_free(key);
2057 }
2058#endif
2059#endif
2060
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002061#define SID_CTX "Python"
2062 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2063 sizeof(SID_CTX));
2064#undef SID_CTX
2065
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002066#ifdef X509_V_FLAG_TRUSTED_FIRST
2067 {
2068 /* Improve trust chain building when cross-signed intermediate
2069 certificates are present. See https://bugs.python.org/issue23476. */
2070 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2071 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2072 }
2073#endif
2074
Antoine Pitrou152efa22010-05-16 18:19:27 +00002075 return (PyObject *)self;
2076}
2077
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002078static int
2079context_traverse(PySSLContext *self, visitproc visit, void *arg)
2080{
2081#ifndef OPENSSL_NO_TLSEXT
2082 Py_VISIT(self->set_hostname);
2083#endif
2084 return 0;
2085}
2086
2087static int
2088context_clear(PySSLContext *self)
2089{
2090#ifndef OPENSSL_NO_TLSEXT
2091 Py_CLEAR(self->set_hostname);
2092#endif
2093 return 0;
2094}
2095
Antoine Pitrou152efa22010-05-16 18:19:27 +00002096static void
2097context_dealloc(PySSLContext *self)
2098{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002099 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002100 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002101#ifdef OPENSSL_NPN_NEGOTIATED
2102 PyMem_Free(self->npn_protocols);
2103#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104 Py_TYPE(self)->tp_free(self);
2105}
2106
2107static PyObject *
2108set_ciphers(PySSLContext *self, PyObject *args)
2109{
2110 int ret;
2111 const char *cipherlist;
2112
2113 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2114 return NULL;
2115 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2116 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002117 /* Clearing the error queue is necessary on some OpenSSL versions,
2118 otherwise the error will be reported again when another SSL call
2119 is done. */
2120 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002121 PyErr_SetString(PySSLErrorObject,
2122 "No cipher can be selected.");
2123 return NULL;
2124 }
2125 Py_RETURN_NONE;
2126}
2127
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002128#ifdef OPENSSL_NPN_NEGOTIATED
2129/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2130static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002131_advertiseNPN_cb(SSL *s,
2132 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002133 void *args)
2134{
2135 PySSLContext *ssl_ctx = (PySSLContext *) args;
2136
2137 if (ssl_ctx->npn_protocols == NULL) {
2138 *data = (unsigned char *) "";
2139 *len = 0;
2140 } else {
2141 *data = (unsigned char *) ssl_ctx->npn_protocols;
2142 *len = ssl_ctx->npn_protocols_len;
2143 }
2144
2145 return SSL_TLSEXT_ERR_OK;
2146}
2147/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2148static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002149_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002150 unsigned char **out, unsigned char *outlen,
2151 const unsigned char *server, unsigned int server_len,
2152 void *args)
2153{
2154 PySSLContext *ssl_ctx = (PySSLContext *) args;
2155
2156 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2157 int client_len;
2158
2159 if (client == NULL) {
2160 client = (unsigned char *) "";
2161 client_len = 0;
2162 } else {
2163 client_len = ssl_ctx->npn_protocols_len;
2164 }
2165
2166 SSL_select_next_proto(out, outlen,
2167 server, server_len,
2168 client, client_len);
2169
2170 return SSL_TLSEXT_ERR_OK;
2171}
2172#endif
2173
2174static PyObject *
2175_set_npn_protocols(PySSLContext *self, PyObject *args)
2176{
2177#ifdef OPENSSL_NPN_NEGOTIATED
2178 Py_buffer protos;
2179
2180 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2181 return NULL;
2182
Christian Heimes5cb31c92012-09-20 12:42:54 +02002183 if (self->npn_protocols != NULL) {
2184 PyMem_Free(self->npn_protocols);
2185 }
2186
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002187 self->npn_protocols = PyMem_Malloc(protos.len);
2188 if (self->npn_protocols == NULL) {
2189 PyBuffer_Release(&protos);
2190 return PyErr_NoMemory();
2191 }
2192 memcpy(self->npn_protocols, protos.buf, protos.len);
2193 self->npn_protocols_len = (int) protos.len;
2194
2195 /* set both server and client callbacks, because the context can
2196 * be used to create both types of sockets */
2197 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2198 _advertiseNPN_cb,
2199 self);
2200 SSL_CTX_set_next_proto_select_cb(self->ctx,
2201 _selectNPN_cb,
2202 self);
2203
2204 PyBuffer_Release(&protos);
2205 Py_RETURN_NONE;
2206#else
2207 PyErr_SetString(PyExc_NotImplementedError,
2208 "The NPN extension requires OpenSSL 1.0.1 or later.");
2209 return NULL;
2210#endif
2211}
2212
Antoine Pitrou152efa22010-05-16 18:19:27 +00002213static PyObject *
2214get_verify_mode(PySSLContext *self, void *c)
2215{
2216 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2217 case SSL_VERIFY_NONE:
2218 return PyLong_FromLong(PY_SSL_CERT_NONE);
2219 case SSL_VERIFY_PEER:
2220 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2221 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2222 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2223 }
2224 PyErr_SetString(PySSLErrorObject,
2225 "invalid return value from SSL_CTX_get_verify_mode");
2226 return NULL;
2227}
2228
2229static int
2230set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2231{
2232 int n, mode;
2233 if (!PyArg_Parse(arg, "i", &n))
2234 return -1;
2235 if (n == PY_SSL_CERT_NONE)
2236 mode = SSL_VERIFY_NONE;
2237 else if (n == PY_SSL_CERT_OPTIONAL)
2238 mode = SSL_VERIFY_PEER;
2239 else if (n == PY_SSL_CERT_REQUIRED)
2240 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2241 else {
2242 PyErr_SetString(PyExc_ValueError,
2243 "invalid value for verify_mode");
2244 return -1;
2245 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002246 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2247 PyErr_SetString(PyExc_ValueError,
2248 "Cannot set verify_mode to CERT_NONE when "
2249 "check_hostname is enabled.");
2250 return -1;
2251 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002252 SSL_CTX_set_verify(self->ctx, mode, NULL);
2253 return 0;
2254}
2255
Christian Heimes2427b502013-11-23 11:24:32 +01002256#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002257static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002258get_verify_flags(PySSLContext *self, void *c)
2259{
2260 X509_STORE *store;
2261 unsigned long flags;
2262
2263 store = SSL_CTX_get_cert_store(self->ctx);
2264 flags = X509_VERIFY_PARAM_get_flags(store->param);
2265 return PyLong_FromUnsignedLong(flags);
2266}
2267
2268static int
2269set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2270{
2271 X509_STORE *store;
2272 unsigned long new_flags, flags, set, clear;
2273
2274 if (!PyArg_Parse(arg, "k", &new_flags))
2275 return -1;
2276 store = SSL_CTX_get_cert_store(self->ctx);
2277 flags = X509_VERIFY_PARAM_get_flags(store->param);
2278 clear = flags & ~new_flags;
2279 set = ~flags & new_flags;
2280 if (clear) {
2281 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2282 _setSSLError(NULL, 0, __FILE__, __LINE__);
2283 return -1;
2284 }
2285 }
2286 if (set) {
2287 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2288 _setSSLError(NULL, 0, __FILE__, __LINE__);
2289 return -1;
2290 }
2291 }
2292 return 0;
2293}
Christian Heimes2427b502013-11-23 11:24:32 +01002294#endif
Christian Heimes22587792013-11-21 23:56:13 +01002295
2296static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002297get_options(PySSLContext *self, void *c)
2298{
2299 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2300}
2301
2302static int
2303set_options(PySSLContext *self, PyObject *arg, void *c)
2304{
2305 long new_opts, opts, set, clear;
2306 if (!PyArg_Parse(arg, "l", &new_opts))
2307 return -1;
2308 opts = SSL_CTX_get_options(self->ctx);
2309 clear = opts & ~new_opts;
2310 set = ~opts & new_opts;
2311 if (clear) {
2312#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2313 SSL_CTX_clear_options(self->ctx, clear);
2314#else
2315 PyErr_SetString(PyExc_ValueError,
2316 "can't clear options before OpenSSL 0.9.8m");
2317 return -1;
2318#endif
2319 }
2320 if (set)
2321 SSL_CTX_set_options(self->ctx, set);
2322 return 0;
2323}
2324
Christian Heimes1aa9a752013-12-02 02:41:19 +01002325static PyObject *
2326get_check_hostname(PySSLContext *self, void *c)
2327{
2328 return PyBool_FromLong(self->check_hostname);
2329}
2330
2331static int
2332set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2333{
2334 int check_hostname;
2335 if (!PyArg_Parse(arg, "p", &check_hostname))
2336 return -1;
2337 if (check_hostname &&
2338 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2339 PyErr_SetString(PyExc_ValueError,
2340 "check_hostname needs a SSL context with either "
2341 "CERT_OPTIONAL or CERT_REQUIRED");
2342 return -1;
2343 }
2344 self->check_hostname = check_hostname;
2345 return 0;
2346}
2347
2348
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002349typedef struct {
2350 PyThreadState *thread_state;
2351 PyObject *callable;
2352 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002353 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002354 int error;
2355} _PySSLPasswordInfo;
2356
2357static int
2358_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2359 const char *bad_type_error)
2360{
2361 /* Set the password and size fields of a _PySSLPasswordInfo struct
2362 from a unicode, bytes, or byte array object.
2363 The password field will be dynamically allocated and must be freed
2364 by the caller */
2365 PyObject *password_bytes = NULL;
2366 const char *data = NULL;
2367 Py_ssize_t size;
2368
2369 if (PyUnicode_Check(password)) {
2370 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2371 if (!password_bytes) {
2372 goto error;
2373 }
2374 data = PyBytes_AS_STRING(password_bytes);
2375 size = PyBytes_GET_SIZE(password_bytes);
2376 } else if (PyBytes_Check(password)) {
2377 data = PyBytes_AS_STRING(password);
2378 size = PyBytes_GET_SIZE(password);
2379 } else if (PyByteArray_Check(password)) {
2380 data = PyByteArray_AS_STRING(password);
2381 size = PyByteArray_GET_SIZE(password);
2382 } else {
2383 PyErr_SetString(PyExc_TypeError, bad_type_error);
2384 goto error;
2385 }
2386
Victor Stinner9ee02032013-06-23 15:08:23 +02002387 if (size > (Py_ssize_t)INT_MAX) {
2388 PyErr_Format(PyExc_ValueError,
2389 "password cannot be longer than %d bytes", INT_MAX);
2390 goto error;
2391 }
2392
Victor Stinner11ebff22013-07-07 17:07:52 +02002393 PyMem_Free(pw_info->password);
2394 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002395 if (!pw_info->password) {
2396 PyErr_SetString(PyExc_MemoryError,
2397 "unable to allocate password buffer");
2398 goto error;
2399 }
2400 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002401 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002402
2403 Py_XDECREF(password_bytes);
2404 return 1;
2405
2406error:
2407 Py_XDECREF(password_bytes);
2408 return 0;
2409}
2410
2411static int
2412_password_callback(char *buf, int size, int rwflag, void *userdata)
2413{
2414 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2415 PyObject *fn_ret = NULL;
2416
2417 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2418
2419 if (pw_info->callable) {
2420 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2421 if (!fn_ret) {
2422 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2423 core python API, so we could use it to add a frame here */
2424 goto error;
2425 }
2426
2427 if (!_pwinfo_set(pw_info, fn_ret,
2428 "password callback must return a string")) {
2429 goto error;
2430 }
2431 Py_CLEAR(fn_ret);
2432 }
2433
2434 if (pw_info->size > size) {
2435 PyErr_Format(PyExc_ValueError,
2436 "password cannot be longer than %d bytes", size);
2437 goto error;
2438 }
2439
2440 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2441 memcpy(buf, pw_info->password, pw_info->size);
2442 return pw_info->size;
2443
2444error:
2445 Py_XDECREF(fn_ret);
2446 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2447 pw_info->error = 1;
2448 return -1;
2449}
2450
Antoine Pitroub5218772010-05-21 09:56:06 +00002451static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002452load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2453{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002454 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2455 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002456 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002457 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2458 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2459 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002460 int r;
2461
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002462 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002463 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002464 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002465 "O|OO:load_cert_chain", kwlist,
2466 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002467 return NULL;
2468 if (keyfile == Py_None)
2469 keyfile = NULL;
2470 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2471 PyErr_SetString(PyExc_TypeError,
2472 "certfile should be a valid filesystem path");
2473 return NULL;
2474 }
2475 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2476 PyErr_SetString(PyExc_TypeError,
2477 "keyfile should be a valid filesystem path");
2478 goto error;
2479 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002480 if (password && password != Py_None) {
2481 if (PyCallable_Check(password)) {
2482 pw_info.callable = password;
2483 } else if (!_pwinfo_set(&pw_info, password,
2484 "password should be a string or callable")) {
2485 goto error;
2486 }
2487 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2488 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2489 }
2490 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002491 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2492 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002493 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002494 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002495 if (pw_info.error) {
2496 ERR_clear_error();
2497 /* the password callback has already set the error information */
2498 }
2499 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002500 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002501 PyErr_SetFromErrno(PyExc_IOError);
2502 }
2503 else {
2504 _setSSLError(NULL, 0, __FILE__, __LINE__);
2505 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002506 goto error;
2507 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002508 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002509 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002510 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2511 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002512 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2513 Py_CLEAR(keyfile_bytes);
2514 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002515 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002516 if (pw_info.error) {
2517 ERR_clear_error();
2518 /* the password callback has already set the error information */
2519 }
2520 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002521 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002522 PyErr_SetFromErrno(PyExc_IOError);
2523 }
2524 else {
2525 _setSSLError(NULL, 0, __FILE__, __LINE__);
2526 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002527 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002528 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002529 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002530 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002531 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002532 if (r != 1) {
2533 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002534 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002535 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002536 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2537 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002538 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002539 Py_RETURN_NONE;
2540
2541error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002542 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2543 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002544 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002545 Py_XDECREF(keyfile_bytes);
2546 Py_XDECREF(certfile_bytes);
2547 return NULL;
2548}
2549
Christian Heimesefff7062013-11-21 03:35:02 +01002550/* internal helper function, returns -1 on error
2551 */
2552static int
2553_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2554 int filetype)
2555{
2556 BIO *biobuf = NULL;
2557 X509_STORE *store;
2558 int retval = 0, err, loaded = 0;
2559
2560 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2561
2562 if (len <= 0) {
2563 PyErr_SetString(PyExc_ValueError,
2564 "Empty certificate data");
2565 return -1;
2566 } else if (len > INT_MAX) {
2567 PyErr_SetString(PyExc_OverflowError,
2568 "Certificate data is too long.");
2569 return -1;
2570 }
2571
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002572 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002573 if (biobuf == NULL) {
2574 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2575 return -1;
2576 }
2577
2578 store = SSL_CTX_get_cert_store(self->ctx);
2579 assert(store != NULL);
2580
2581 while (1) {
2582 X509 *cert = NULL;
2583 int r;
2584
2585 if (filetype == SSL_FILETYPE_ASN1) {
2586 cert = d2i_X509_bio(biobuf, NULL);
2587 } else {
2588 cert = PEM_read_bio_X509(biobuf, NULL,
2589 self->ctx->default_passwd_callback,
2590 self->ctx->default_passwd_callback_userdata);
2591 }
2592 if (cert == NULL) {
2593 break;
2594 }
2595 r = X509_STORE_add_cert(store, cert);
2596 X509_free(cert);
2597 if (!r) {
2598 err = ERR_peek_last_error();
2599 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2600 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2601 /* cert already in hash table, not an error */
2602 ERR_clear_error();
2603 } else {
2604 break;
2605 }
2606 }
2607 loaded++;
2608 }
2609
2610 err = ERR_peek_last_error();
2611 if ((filetype == SSL_FILETYPE_ASN1) &&
2612 (loaded > 0) &&
2613 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2614 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2615 /* EOF ASN1 file, not an error */
2616 ERR_clear_error();
2617 retval = 0;
2618 } else if ((filetype == SSL_FILETYPE_PEM) &&
2619 (loaded > 0) &&
2620 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2621 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2622 /* EOF PEM file, not an error */
2623 ERR_clear_error();
2624 retval = 0;
2625 } else {
2626 _setSSLError(NULL, 0, __FILE__, __LINE__);
2627 retval = -1;
2628 }
2629
2630 BIO_free(biobuf);
2631 return retval;
2632}
2633
2634
Antoine Pitrou152efa22010-05-16 18:19:27 +00002635static PyObject *
2636load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2637{
Christian Heimesefff7062013-11-21 03:35:02 +01002638 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2639 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2641 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002642 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002643
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002644 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002645 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002646 "|OOO:load_verify_locations", kwlist,
2647 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002648 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002649
Antoine Pitrou152efa22010-05-16 18:19:27 +00002650 if (cafile == Py_None)
2651 cafile = NULL;
2652 if (capath == Py_None)
2653 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002654 if (cadata == Py_None)
2655 cadata = NULL;
2656
2657 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002658 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002659 "cafile, capath and cadata cannot be all omitted");
2660 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002661 }
2662 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2663 PyErr_SetString(PyExc_TypeError,
2664 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002665 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002666 }
2667 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668 PyErr_SetString(PyExc_TypeError,
2669 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002670 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002671 }
Christian Heimesefff7062013-11-21 03:35:02 +01002672
2673 /* validata cadata type and load cadata */
2674 if (cadata) {
2675 Py_buffer buf;
2676 PyObject *cadata_ascii = NULL;
2677
2678 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2679 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2680 PyBuffer_Release(&buf);
2681 PyErr_SetString(PyExc_TypeError,
2682 "cadata should be a contiguous buffer with "
2683 "a single dimension");
2684 goto error;
2685 }
2686 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2687 PyBuffer_Release(&buf);
2688 if (r == -1) {
2689 goto error;
2690 }
2691 } else {
2692 PyErr_Clear();
2693 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2694 if (cadata_ascii == NULL) {
2695 PyErr_SetString(PyExc_TypeError,
2696 "cadata should be a ASCII string or a "
2697 "bytes-like object");
2698 goto error;
2699 }
2700 r = _add_ca_certs(self,
2701 PyBytes_AS_STRING(cadata_ascii),
2702 PyBytes_GET_SIZE(cadata_ascii),
2703 SSL_FILETYPE_PEM);
2704 Py_DECREF(cadata_ascii);
2705 if (r == -1) {
2706 goto error;
2707 }
2708 }
2709 }
2710
2711 /* load cafile or capath */
2712 if (cafile || capath) {
2713 if (cafile)
2714 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2715 if (capath)
2716 capath_buf = PyBytes_AS_STRING(capath_bytes);
2717 PySSL_BEGIN_ALLOW_THREADS
2718 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2719 PySSL_END_ALLOW_THREADS
2720 if (r != 1) {
2721 ok = 0;
2722 if (errno != 0) {
2723 ERR_clear_error();
2724 PyErr_SetFromErrno(PyExc_IOError);
2725 }
2726 else {
2727 _setSSLError(NULL, 0, __FILE__, __LINE__);
2728 }
2729 goto error;
2730 }
2731 }
2732 goto end;
2733
2734 error:
2735 ok = 0;
2736 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002737 Py_XDECREF(cafile_bytes);
2738 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002739 if (ok) {
2740 Py_RETURN_NONE;
2741 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002742 return NULL;
2743 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002744}
2745
2746static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002747load_dh_params(PySSLContext *self, PyObject *filepath)
2748{
2749 FILE *f;
2750 DH *dh;
2751
Victor Stinnerdaf45552013-08-28 00:53:59 +02002752 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002753 if (f == NULL) {
2754 if (!PyErr_Occurred())
2755 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2756 return NULL;
2757 }
2758 errno = 0;
2759 PySSL_BEGIN_ALLOW_THREADS
2760 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002761 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002762 PySSL_END_ALLOW_THREADS
2763 if (dh == NULL) {
2764 if (errno != 0) {
2765 ERR_clear_error();
2766 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2767 }
2768 else {
2769 _setSSLError(NULL, 0, __FILE__, __LINE__);
2770 }
2771 return NULL;
2772 }
2773 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2774 _setSSLError(NULL, 0, __FILE__, __LINE__);
2775 DH_free(dh);
2776 Py_RETURN_NONE;
2777}
2778
2779static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002780context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2781{
Antoine Pitroud5323212010-10-22 18:19:07 +00002782 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002783 PySocketSockObject *sock;
2784 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002785 char *hostname = NULL;
2786 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002787
Antoine Pitroud5323212010-10-22 18:19:07 +00002788 /* server_hostname is either None (or absent), or to be encoded
2789 using the idna encoding. */
2790 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002791 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002792 &sock, &server_side,
2793 Py_TYPE(Py_None), &hostname_obj)) {
2794 PyErr_Clear();
2795 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2796 PySocketModule.Sock_Type,
2797 &sock, &server_side,
2798 "idna", &hostname))
2799 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002800 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002802 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002803 hostname);
2804 if (hostname != NULL)
2805 PyMem_Free(hostname);
2806 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807}
2808
Antoine Pitroub0182c82010-10-12 20:09:02 +00002809static PyObject *
2810session_stats(PySSLContext *self, PyObject *unused)
2811{
2812 int r;
2813 PyObject *value, *stats = PyDict_New();
2814 if (!stats)
2815 return NULL;
2816
2817#define ADD_STATS(SSL_NAME, KEY_NAME) \
2818 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2819 if (value == NULL) \
2820 goto error; \
2821 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2822 Py_DECREF(value); \
2823 if (r < 0) \
2824 goto error;
2825
2826 ADD_STATS(number, "number");
2827 ADD_STATS(connect, "connect");
2828 ADD_STATS(connect_good, "connect_good");
2829 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2830 ADD_STATS(accept, "accept");
2831 ADD_STATS(accept_good, "accept_good");
2832 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2833 ADD_STATS(accept, "accept");
2834 ADD_STATS(hits, "hits");
2835 ADD_STATS(misses, "misses");
2836 ADD_STATS(timeouts, "timeouts");
2837 ADD_STATS(cache_full, "cache_full");
2838
2839#undef ADD_STATS
2840
2841 return stats;
2842
2843error:
2844 Py_DECREF(stats);
2845 return NULL;
2846}
2847
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002848static PyObject *
2849set_default_verify_paths(PySSLContext *self, PyObject *unused)
2850{
2851 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2852 _setSSLError(NULL, 0, __FILE__, __LINE__);
2853 return NULL;
2854 }
2855 Py_RETURN_NONE;
2856}
2857
Antoine Pitrou501da612011-12-21 09:27:41 +01002858#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002859static PyObject *
2860set_ecdh_curve(PySSLContext *self, PyObject *name)
2861{
2862 PyObject *name_bytes;
2863 int nid;
2864 EC_KEY *key;
2865
2866 if (!PyUnicode_FSConverter(name, &name_bytes))
2867 return NULL;
2868 assert(PyBytes_Check(name_bytes));
2869 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2870 Py_DECREF(name_bytes);
2871 if (nid == 0) {
2872 PyErr_Format(PyExc_ValueError,
2873 "unknown elliptic curve name %R", name);
2874 return NULL;
2875 }
2876 key = EC_KEY_new_by_curve_name(nid);
2877 if (key == NULL) {
2878 _setSSLError(NULL, 0, __FILE__, __LINE__);
2879 return NULL;
2880 }
2881 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2882 EC_KEY_free(key);
2883 Py_RETURN_NONE;
2884}
Antoine Pitrou501da612011-12-21 09:27:41 +01002885#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002886
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002887#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002888static int
2889_servername_callback(SSL *s, int *al, void *args)
2890{
2891 int ret;
2892 PySSLContext *ssl_ctx = (PySSLContext *) args;
2893 PySSLSocket *ssl;
2894 PyObject *servername_o;
2895 PyObject *servername_idna;
2896 PyObject *result;
2897 /* The high-level ssl.SSLSocket object */
2898 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002899 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002900#ifdef WITH_THREAD
2901 PyGILState_STATE gstate = PyGILState_Ensure();
2902#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002903
2904 if (ssl_ctx->set_hostname == NULL) {
2905 /* remove race condition in this the call back while if removing the
2906 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002907#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002908 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002909#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002910 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002911 }
2912
2913 ssl = SSL_get_app_data(s);
2914 assert(PySSLSocket_Check(ssl));
2915 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2916 Py_INCREF(ssl_socket);
2917 if (ssl_socket == Py_None) {
2918 goto error;
2919 }
Victor Stinner7e001512013-06-25 00:44:31 +02002920
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002921 if (servername == NULL) {
2922 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2923 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002924 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002925 else {
2926 servername_o = PyBytes_FromString(servername);
2927 if (servername_o == NULL) {
2928 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2929 goto error;
2930 }
2931 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2932 if (servername_idna == NULL) {
2933 PyErr_WriteUnraisable(servername_o);
2934 Py_DECREF(servername_o);
2935 goto error;
2936 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002937 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002938 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2939 servername_idna, ssl_ctx, NULL);
2940 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002941 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002942 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002943
2944 if (result == NULL) {
2945 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2946 *al = SSL_AD_HANDSHAKE_FAILURE;
2947 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2948 }
2949 else {
2950 if (result != Py_None) {
2951 *al = (int) PyLong_AsLong(result);
2952 if (PyErr_Occurred()) {
2953 PyErr_WriteUnraisable(result);
2954 *al = SSL_AD_INTERNAL_ERROR;
2955 }
2956 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2957 }
2958 else {
2959 ret = SSL_TLSEXT_ERR_OK;
2960 }
2961 Py_DECREF(result);
2962 }
2963
Stefan Krah20d60802013-01-17 17:07:17 +01002964#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002965 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002966#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002967 return ret;
2968
2969error:
2970 Py_DECREF(ssl_socket);
2971 *al = SSL_AD_INTERNAL_ERROR;
2972 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002973#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002974 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002975#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002976 return ret;
2977}
Antoine Pitroua5963382013-03-30 16:39:00 +01002978#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002979
2980PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2981"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002982\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002983This sets a callback that will be called when a server name is provided by\n\
2984the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002985\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002986If the argument is None then the callback is disabled. The method is called\n\
2987with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002988See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002989
2990static PyObject *
2991set_servername_callback(PySSLContext *self, PyObject *args)
2992{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002993#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002994 PyObject *cb;
2995
2996 if (!PyArg_ParseTuple(args, "O", &cb))
2997 return NULL;
2998
2999 Py_CLEAR(self->set_hostname);
3000 if (cb == Py_None) {
3001 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3002 }
3003 else {
3004 if (!PyCallable_Check(cb)) {
3005 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3006 PyErr_SetString(PyExc_TypeError,
3007 "not a callable object");
3008 return NULL;
3009 }
3010 Py_INCREF(cb);
3011 self->set_hostname = cb;
3012 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3013 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3014 }
3015 Py_RETURN_NONE;
3016#else
3017 PyErr_SetString(PyExc_NotImplementedError,
3018 "The TLS extension servername callback, "
3019 "SSL_CTX_set_tlsext_servername_callback, "
3020 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003021 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003022#endif
3023}
3024
Christian Heimes9a5395a2013-06-17 15:44:12 +02003025PyDoc_STRVAR(PySSL_get_stats_doc,
3026"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3027\n\
3028Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3029CA extension and certificate revocation lists inside the context's cert\n\
3030store.\n\
3031NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3032been used at least once.");
3033
3034static PyObject *
3035cert_store_stats(PySSLContext *self)
3036{
3037 X509_STORE *store;
3038 X509_OBJECT *obj;
3039 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3040
3041 store = SSL_CTX_get_cert_store(self->ctx);
3042 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3043 obj = sk_X509_OBJECT_value(store->objs, i);
3044 switch (obj->type) {
3045 case X509_LU_X509:
3046 x509++;
3047 if (X509_check_ca(obj->data.x509)) {
3048 ca++;
3049 }
3050 break;
3051 case X509_LU_CRL:
3052 crl++;
3053 break;
3054 case X509_LU_PKEY:
3055 pkey++;
3056 break;
3057 default:
3058 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3059 * As far as I can tell they are internal states and never
3060 * stored in a cert store */
3061 break;
3062 }
3063 }
3064 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3065 "x509_ca", ca);
3066}
3067
3068PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003069"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003070\n\
3071Returns a list of dicts with information of loaded CA certs. If the\n\
3072optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3073NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3074been used at least once.");
3075
3076static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003077get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003078{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003079 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003080 X509_STORE *store;
3081 PyObject *ci = NULL, *rlist = NULL;
3082 int i;
3083 int binary_mode = 0;
3084
Christian Heimesf22e8e52013-11-22 02:22:51 +01003085 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3086 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003087 return NULL;
3088 }
3089
3090 if ((rlist = PyList_New(0)) == NULL) {
3091 return NULL;
3092 }
3093
3094 store = SSL_CTX_get_cert_store(self->ctx);
3095 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3096 X509_OBJECT *obj;
3097 X509 *cert;
3098
3099 obj = sk_X509_OBJECT_value(store->objs, i);
3100 if (obj->type != X509_LU_X509) {
3101 /* not a x509 cert */
3102 continue;
3103 }
3104 /* CA for any purpose */
3105 cert = obj->data.x509;
3106 if (!X509_check_ca(cert)) {
3107 continue;
3108 }
3109 if (binary_mode) {
3110 ci = _certificate_to_der(cert);
3111 } else {
3112 ci = _decode_certificate(cert);
3113 }
3114 if (ci == NULL) {
3115 goto error;
3116 }
3117 if (PyList_Append(rlist, ci) == -1) {
3118 goto error;
3119 }
3120 Py_CLEAR(ci);
3121 }
3122 return rlist;
3123
3124 error:
3125 Py_XDECREF(ci);
3126 Py_XDECREF(rlist);
3127 return NULL;
3128}
3129
3130
Antoine Pitrou152efa22010-05-16 18:19:27 +00003131static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003132 {"check_hostname", (getter) get_check_hostname,
3133 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003134 {"options", (getter) get_options,
3135 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003136#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003137 {"verify_flags", (getter) get_verify_flags,
3138 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003139#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003140 {"verify_mode", (getter) get_verify_mode,
3141 (setter) set_verify_mode, NULL},
3142 {NULL}, /* sentinel */
3143};
3144
3145static struct PyMethodDef context_methods[] = {
3146 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3147 METH_VARARGS | METH_KEYWORDS, NULL},
3148 {"set_ciphers", (PyCFunction) set_ciphers,
3149 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003150 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3151 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003152 {"load_cert_chain", (PyCFunction) load_cert_chain,
3153 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003154 {"load_dh_params", (PyCFunction) load_dh_params,
3155 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003156 {"load_verify_locations", (PyCFunction) load_verify_locations,
3157 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003158 {"session_stats", (PyCFunction) session_stats,
3159 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003160 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3161 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003162#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003163 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3164 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003165#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003166 {"set_servername_callback", (PyCFunction) set_servername_callback,
3167 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003168 {"cert_store_stats", (PyCFunction) cert_store_stats,
3169 METH_NOARGS, PySSL_get_stats_doc},
3170 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003171 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003172 {NULL, NULL} /* sentinel */
3173};
3174
3175static PyTypeObject PySSLContext_Type = {
3176 PyVarObject_HEAD_INIT(NULL, 0)
3177 "_ssl._SSLContext", /*tp_name*/
3178 sizeof(PySSLContext), /*tp_basicsize*/
3179 0, /*tp_itemsize*/
3180 (destructor)context_dealloc, /*tp_dealloc*/
3181 0, /*tp_print*/
3182 0, /*tp_getattr*/
3183 0, /*tp_setattr*/
3184 0, /*tp_reserved*/
3185 0, /*tp_repr*/
3186 0, /*tp_as_number*/
3187 0, /*tp_as_sequence*/
3188 0, /*tp_as_mapping*/
3189 0, /*tp_hash*/
3190 0, /*tp_call*/
3191 0, /*tp_str*/
3192 0, /*tp_getattro*/
3193 0, /*tp_setattro*/
3194 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003195 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003196 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003197 (traverseproc) context_traverse, /*tp_traverse*/
3198 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003199 0, /*tp_richcompare*/
3200 0, /*tp_weaklistoffset*/
3201 0, /*tp_iter*/
3202 0, /*tp_iternext*/
3203 context_methods, /*tp_methods*/
3204 0, /*tp_members*/
3205 context_getsetlist, /*tp_getset*/
3206 0, /*tp_base*/
3207 0, /*tp_dict*/
3208 0, /*tp_descr_get*/
3209 0, /*tp_descr_set*/
3210 0, /*tp_dictoffset*/
3211 0, /*tp_init*/
3212 0, /*tp_alloc*/
3213 context_new, /*tp_new*/
3214};
3215
3216
3217
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003218#ifdef HAVE_OPENSSL_RAND
3219
3220/* helper routines for seeding the SSL PRNG */
3221static PyObject *
3222PySSL_RAND_add(PyObject *self, PyObject *args)
3223{
3224 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003225 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003226 double entropy;
3227
3228 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003229 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003230 do {
3231 written = Py_MIN(len, INT_MAX);
3232 RAND_add(buf, (int)written, entropy);
3233 buf += written;
3234 len -= written;
3235 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003236 Py_INCREF(Py_None);
3237 return Py_None;
3238}
3239
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003240PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003241"RAND_add(string, entropy)\n\
3242\n\
3243Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003244bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003245
3246static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003247PySSL_RAND(int len, int pseudo)
3248{
3249 int ok;
3250 PyObject *bytes;
3251 unsigned long err;
3252 const char *errstr;
3253 PyObject *v;
3254
Victor Stinner1e81a392013-12-19 16:47:04 +01003255 if (len < 0) {
3256 PyErr_SetString(PyExc_ValueError, "num must be positive");
3257 return NULL;
3258 }
3259
Victor Stinner99c8b162011-05-24 12:05:19 +02003260 bytes = PyBytes_FromStringAndSize(NULL, len);
3261 if (bytes == NULL)
3262 return NULL;
3263 if (pseudo) {
3264 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3265 if (ok == 0 || ok == 1)
3266 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3267 }
3268 else {
3269 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3270 if (ok == 1)
3271 return bytes;
3272 }
3273 Py_DECREF(bytes);
3274
3275 err = ERR_get_error();
3276 errstr = ERR_reason_error_string(err);
3277 v = Py_BuildValue("(ks)", err, errstr);
3278 if (v != NULL) {
3279 PyErr_SetObject(PySSLErrorObject, v);
3280 Py_DECREF(v);
3281 }
3282 return NULL;
3283}
3284
3285static PyObject *
3286PySSL_RAND_bytes(PyObject *self, PyObject *args)
3287{
3288 int len;
3289 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3290 return NULL;
3291 return PySSL_RAND(len, 0);
3292}
3293
3294PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3295"RAND_bytes(n) -> bytes\n\
3296\n\
3297Generate n cryptographically strong pseudo-random bytes.");
3298
3299static PyObject *
3300PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3301{
3302 int len;
3303 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3304 return NULL;
3305 return PySSL_RAND(len, 1);
3306}
3307
3308PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3309"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3310\n\
3311Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3312generated are cryptographically strong.");
3313
3314static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003315PySSL_RAND_status(PyObject *self)
3316{
Christian Heimes217cfd12007-12-02 14:31:20 +00003317 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003318}
3319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003320PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003321"RAND_status() -> 0 or 1\n\
3322\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003323Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3324It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3325using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003326
Victor Stinnerfcfed192015-01-06 13:54:58 +01003327#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003328static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003329PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003330{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003331 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003332 int bytes;
3333
Jesus Ceac8754a12012-09-11 02:00:58 +02003334 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003335 PyUnicode_FSConverter, &path))
3336 return NULL;
3337
3338 bytes = RAND_egd(PyBytes_AsString(path));
3339 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003340 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003341 PyErr_SetString(PySSLErrorObject,
3342 "EGD connection failed or EGD did not return "
3343 "enough data to seed the PRNG");
3344 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003345 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003346 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003347}
3348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003349PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003350"RAND_egd(path) -> bytes\n\
3351\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003352Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3353Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003354fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerfcfed192015-01-06 13:54:58 +01003355#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003356
Christian Heimesf77b4b22013-08-21 13:26:05 +02003357#endif /* HAVE_OPENSSL_RAND */
3358
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003359
Christian Heimes6d7ad132013-06-09 18:02:55 +02003360PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3361"get_default_verify_paths() -> tuple\n\
3362\n\
3363Return search paths and environment vars that are used by SSLContext's\n\
3364set_default_verify_paths() to load default CAs. The values are\n\
3365'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3366
3367static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003368PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003369{
3370 PyObject *ofile_env = NULL;
3371 PyObject *ofile = NULL;
3372 PyObject *odir_env = NULL;
3373 PyObject *odir = NULL;
3374
3375#define convert(info, target) { \
3376 const char *tmp = (info); \
3377 target = NULL; \
3378 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3379 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3380 target = PyBytes_FromString(tmp); } \
3381 if (!target) goto error; \
3382 } while(0)
3383
3384 convert(X509_get_default_cert_file_env(), ofile_env);
3385 convert(X509_get_default_cert_file(), ofile);
3386 convert(X509_get_default_cert_dir_env(), odir_env);
3387 convert(X509_get_default_cert_dir(), odir);
3388#undef convert
3389
Christian Heimes200bb1b2013-06-14 15:14:29 +02003390 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003391
3392 error:
3393 Py_XDECREF(ofile_env);
3394 Py_XDECREF(ofile);
3395 Py_XDECREF(odir_env);
3396 Py_XDECREF(odir);
3397 return NULL;
3398}
3399
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003400static PyObject*
3401asn1obj2py(ASN1_OBJECT *obj)
3402{
3403 int nid;
3404 const char *ln, *sn;
3405 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003406 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003407
3408 nid = OBJ_obj2nid(obj);
3409 if (nid == NID_undef) {
3410 PyErr_Format(PyExc_ValueError, "Unknown object");
3411 return NULL;
3412 }
3413 sn = OBJ_nid2sn(nid);
3414 ln = OBJ_nid2ln(nid);
3415 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3416 if (buflen < 0) {
3417 _setSSLError(NULL, 0, __FILE__, __LINE__);
3418 return NULL;
3419 }
3420 if (buflen) {
3421 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3422 } else {
3423 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3424 }
3425}
3426
3427PyDoc_STRVAR(PySSL_txt2obj_doc,
3428"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3429\n\
3430Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3431objects are looked up by OID. With name=True short and long name are also\n\
3432matched.");
3433
3434static PyObject*
3435PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3436{
3437 char *kwlist[] = {"txt", "name", NULL};
3438 PyObject *result = NULL;
3439 char *txt;
3440 int name = 0;
3441 ASN1_OBJECT *obj;
3442
3443 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3444 kwlist, &txt, &name)) {
3445 return NULL;
3446 }
3447 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3448 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003449 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003450 return NULL;
3451 }
3452 result = asn1obj2py(obj);
3453 ASN1_OBJECT_free(obj);
3454 return result;
3455}
3456
3457PyDoc_STRVAR(PySSL_nid2obj_doc,
3458"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3459\n\
3460Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3461
3462static PyObject*
3463PySSL_nid2obj(PyObject *self, PyObject *args)
3464{
3465 PyObject *result = NULL;
3466 int nid;
3467 ASN1_OBJECT *obj;
3468
3469 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3470 return NULL;
3471 }
3472 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003473 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003474 return NULL;
3475 }
3476 obj = OBJ_nid2obj(nid);
3477 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003478 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003479 return NULL;
3480 }
3481 result = asn1obj2py(obj);
3482 ASN1_OBJECT_free(obj);
3483 return result;
3484}
3485
Christian Heimes46bebee2013-06-09 19:03:31 +02003486#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003487
3488static PyObject*
3489certEncodingType(DWORD encodingType)
3490{
3491 static PyObject *x509_asn = NULL;
3492 static PyObject *pkcs_7_asn = NULL;
3493
3494 if (x509_asn == NULL) {
3495 x509_asn = PyUnicode_InternFromString("x509_asn");
3496 if (x509_asn == NULL)
3497 return NULL;
3498 }
3499 if (pkcs_7_asn == NULL) {
3500 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3501 if (pkcs_7_asn == NULL)
3502 return NULL;
3503 }
3504 switch(encodingType) {
3505 case X509_ASN_ENCODING:
3506 Py_INCREF(x509_asn);
3507 return x509_asn;
3508 case PKCS_7_ASN_ENCODING:
3509 Py_INCREF(pkcs_7_asn);
3510 return pkcs_7_asn;
3511 default:
3512 return PyLong_FromLong(encodingType);
3513 }
3514}
3515
3516static PyObject*
3517parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3518{
3519 CERT_ENHKEY_USAGE *usage;
3520 DWORD size, error, i;
3521 PyObject *retval;
3522
3523 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3524 error = GetLastError();
3525 if (error == CRYPT_E_NOT_FOUND) {
3526 Py_RETURN_TRUE;
3527 }
3528 return PyErr_SetFromWindowsErr(error);
3529 }
3530
3531 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3532 if (usage == NULL) {
3533 return PyErr_NoMemory();
3534 }
3535
3536 /* Now get the actual enhanced usage property */
3537 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3538 PyMem_Free(usage);
3539 error = GetLastError();
3540 if (error == CRYPT_E_NOT_FOUND) {
3541 Py_RETURN_TRUE;
3542 }
3543 return PyErr_SetFromWindowsErr(error);
3544 }
3545 retval = PySet_New(NULL);
3546 if (retval == NULL) {
3547 goto error;
3548 }
3549 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3550 if (usage->rgpszUsageIdentifier[i]) {
3551 PyObject *oid;
3552 int err;
3553 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3554 if (oid == NULL) {
3555 Py_CLEAR(retval);
3556 goto error;
3557 }
3558 err = PySet_Add(retval, oid);
3559 Py_DECREF(oid);
3560 if (err == -1) {
3561 Py_CLEAR(retval);
3562 goto error;
3563 }
3564 }
3565 }
3566 error:
3567 PyMem_Free(usage);
3568 return retval;
3569}
3570
3571PyDoc_STRVAR(PySSL_enum_certificates_doc,
3572"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003573\n\
3574Retrieve certificates from Windows' cert store. store_name may be one of\n\
3575'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003576The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003577encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003578PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3579boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003580
Christian Heimes46bebee2013-06-09 19:03:31 +02003581static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003582PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003583{
Christian Heimes44109d72013-11-22 01:51:30 +01003584 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003585 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003586 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003587 PCCERT_CONTEXT pCertCtx = NULL;
3588 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003589 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003590
Christian Heimes44109d72013-11-22 01:51:30 +01003591 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3592 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003593 return NULL;
3594 }
Christian Heimes44109d72013-11-22 01:51:30 +01003595 result = PyList_New(0);
3596 if (result == NULL) {
3597 return NULL;
3598 }
3599 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3600 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003601 Py_DECREF(result);
3602 return PyErr_SetFromWindowsErr(GetLastError());
3603 }
3604
Christian Heimes44109d72013-11-22 01:51:30 +01003605 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3606 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3607 pCertCtx->cbCertEncoded);
3608 if (!cert) {
3609 Py_CLEAR(result);
3610 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003611 }
Christian Heimes44109d72013-11-22 01:51:30 +01003612 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3613 Py_CLEAR(result);
3614 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003615 }
Christian Heimes44109d72013-11-22 01:51:30 +01003616 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3617 if (keyusage == Py_True) {
3618 Py_DECREF(keyusage);
3619 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003620 }
Christian Heimes44109d72013-11-22 01:51:30 +01003621 if (keyusage == NULL) {
3622 Py_CLEAR(result);
3623 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003624 }
Christian Heimes44109d72013-11-22 01:51:30 +01003625 if ((tup = PyTuple_New(3)) == NULL) {
3626 Py_CLEAR(result);
3627 break;
3628 }
3629 PyTuple_SET_ITEM(tup, 0, cert);
3630 cert = NULL;
3631 PyTuple_SET_ITEM(tup, 1, enc);
3632 enc = NULL;
3633 PyTuple_SET_ITEM(tup, 2, keyusage);
3634 keyusage = NULL;
3635 if (PyList_Append(result, tup) < 0) {
3636 Py_CLEAR(result);
3637 break;
3638 }
3639 Py_CLEAR(tup);
3640 }
3641 if (pCertCtx) {
3642 /* loop ended with an error, need to clean up context manually */
3643 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003644 }
3645
3646 /* In error cases cert, enc and tup may not be NULL */
3647 Py_XDECREF(cert);
3648 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003649 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003650 Py_XDECREF(tup);
3651
3652 if (!CertCloseStore(hStore, 0)) {
3653 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003654 Py_XDECREF(result);
3655 return PyErr_SetFromWindowsErr(GetLastError());
3656 }
3657 return result;
3658}
3659
3660PyDoc_STRVAR(PySSL_enum_crls_doc,
3661"enum_crls(store_name) -> []\n\
3662\n\
3663Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3664'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3665The function returns a list of (bytes, encoding_type) tuples. The\n\
3666encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3667PKCS_7_ASN_ENCODING.");
3668
3669static PyObject *
3670PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3671{
3672 char *kwlist[] = {"store_name", NULL};
3673 char *store_name;
3674 HCERTSTORE hStore = NULL;
3675 PCCRL_CONTEXT pCrlCtx = NULL;
3676 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3677 PyObject *result = NULL;
3678
3679 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3680 kwlist, &store_name)) {
3681 return NULL;
3682 }
3683 result = PyList_New(0);
3684 if (result == NULL) {
3685 return NULL;
3686 }
3687 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3688 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003689 Py_DECREF(result);
3690 return PyErr_SetFromWindowsErr(GetLastError());
3691 }
Christian Heimes44109d72013-11-22 01:51:30 +01003692
3693 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3694 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3695 pCrlCtx->cbCrlEncoded);
3696 if (!crl) {
3697 Py_CLEAR(result);
3698 break;
3699 }
3700 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3701 Py_CLEAR(result);
3702 break;
3703 }
3704 if ((tup = PyTuple_New(2)) == NULL) {
3705 Py_CLEAR(result);
3706 break;
3707 }
3708 PyTuple_SET_ITEM(tup, 0, crl);
3709 crl = NULL;
3710 PyTuple_SET_ITEM(tup, 1, enc);
3711 enc = NULL;
3712
3713 if (PyList_Append(result, tup) < 0) {
3714 Py_CLEAR(result);
3715 break;
3716 }
3717 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003718 }
Christian Heimes44109d72013-11-22 01:51:30 +01003719 if (pCrlCtx) {
3720 /* loop ended with an error, need to clean up context manually */
3721 CertFreeCRLContext(pCrlCtx);
3722 }
3723
3724 /* In error cases cert, enc and tup may not be NULL */
3725 Py_XDECREF(crl);
3726 Py_XDECREF(enc);
3727 Py_XDECREF(tup);
3728
3729 if (!CertCloseStore(hStore, 0)) {
3730 /* This error case might shadow another exception.*/
3731 Py_XDECREF(result);
3732 return PyErr_SetFromWindowsErr(GetLastError());
3733 }
3734 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003735}
Christian Heimes44109d72013-11-22 01:51:30 +01003736
3737#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003738
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003739/* List of functions exported by this module. */
3740
3741static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003742 {"_test_decode_cert", PySSL_test_decode_certificate,
3743 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003744#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003745 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3746 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003747 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3748 PySSL_RAND_bytes_doc},
3749 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3750 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerfcfed192015-01-06 13:54:58 +01003751#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003752 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003753 PySSL_RAND_egd_doc},
Victor Stinnerfcfed192015-01-06 13:54:58 +01003754#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003755 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3756 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003757#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003758 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003759 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003760#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003761 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3762 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3763 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3764 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003765#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003766 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3767 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3768 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3769 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003770 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003771};
3772
3773
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003774#ifdef WITH_THREAD
3775
3776/* an implementation of OpenSSL threading operations in terms
3777 of the Python C thread library */
3778
3779static PyThread_type_lock *_ssl_locks = NULL;
3780
Christian Heimes4d98ca92013-08-19 17:36:29 +02003781#if OPENSSL_VERSION_NUMBER >= 0x10000000
3782/* use new CRYPTO_THREADID API. */
3783static void
3784_ssl_threadid_callback(CRYPTO_THREADID *id)
3785{
3786 CRYPTO_THREADID_set_numeric(id,
3787 (unsigned long)PyThread_get_thread_ident());
3788}
3789#else
3790/* deprecated CRYPTO_set_id_callback() API. */
3791static unsigned long
3792_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003793 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003794}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003795#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003796
Bill Janssen6e027db2007-11-15 22:23:56 +00003797static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003798 (int mode, int n, const char *file, int line) {
3799 /* this function is needed to perform locking on shared data
3800 structures. (Note that OpenSSL uses a number of global data
3801 structures that will be implicitly shared whenever multiple
3802 threads use OpenSSL.) Multi-threaded applications will
3803 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003805 locking_function() must be able to handle up to
3806 CRYPTO_num_locks() different mutex locks. It sets the n-th
3807 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003809 file and line are the file number of the function setting the
3810 lock. They can be useful for debugging.
3811 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003813 if ((_ssl_locks == NULL) ||
3814 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3815 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003817 if (mode & CRYPTO_LOCK) {
3818 PyThread_acquire_lock(_ssl_locks[n], 1);
3819 } else {
3820 PyThread_release_lock(_ssl_locks[n]);
3821 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003822}
3823
3824static int _setup_ssl_threads(void) {
3825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003826 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003828 if (_ssl_locks == NULL) {
3829 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003830 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3831 if (_ssl_locks == NULL) {
3832 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003833 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003834 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003835 memset(_ssl_locks, 0,
3836 sizeof(PyThread_type_lock) * _ssl_locks_count);
3837 for (i = 0; i < _ssl_locks_count; i++) {
3838 _ssl_locks[i] = PyThread_allocate_lock();
3839 if (_ssl_locks[i] == NULL) {
3840 unsigned int j;
3841 for (j = 0; j < i; j++) {
3842 PyThread_free_lock(_ssl_locks[j]);
3843 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003844 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003845 return 0;
3846 }
3847 }
3848 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003849#if OPENSSL_VERSION_NUMBER >= 0x10000000
3850 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3851#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003852 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003853#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003854 }
3855 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003856}
3857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003858#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003860PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003861"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003862for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003863
Martin v. Löwis1a214512008-06-11 05:26:20 +00003864
3865static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003866 PyModuleDef_HEAD_INIT,
3867 "_ssl",
3868 module_doc,
3869 -1,
3870 PySSL_methods,
3871 NULL,
3872 NULL,
3873 NULL,
3874 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003875};
3876
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003877
3878static void
3879parse_openssl_version(unsigned long libver,
3880 unsigned int *major, unsigned int *minor,
3881 unsigned int *fix, unsigned int *patch,
3882 unsigned int *status)
3883{
3884 *status = libver & 0xF;
3885 libver >>= 4;
3886 *patch = libver & 0xFF;
3887 libver >>= 8;
3888 *fix = libver & 0xFF;
3889 libver >>= 8;
3890 *minor = libver & 0xFF;
3891 libver >>= 8;
3892 *major = libver & 0xFF;
3893}
3894
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003895PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003896PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003897{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003898 PyObject *m, *d, *r;
3899 unsigned long libver;
3900 unsigned int major, minor, fix, patch, status;
3901 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003902 struct py_ssl_error_code *errcode;
3903 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003904
Antoine Pitrou152efa22010-05-16 18:19:27 +00003905 if (PyType_Ready(&PySSLContext_Type) < 0)
3906 return NULL;
3907 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003908 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003910 m = PyModule_Create(&_sslmodule);
3911 if (m == NULL)
3912 return NULL;
3913 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003915 /* Load _socket module and its C API */
3916 socket_api = PySocketModule_ImportModuleAndAPI();
3917 if (!socket_api)
3918 return NULL;
3919 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003921 /* Init OpenSSL */
3922 SSL_load_error_strings();
3923 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003924#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003925 /* note that this will start threading if not already started */
3926 if (!_setup_ssl_threads()) {
3927 return NULL;
3928 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003929#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003930 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003932 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003933 sslerror_type_slots[0].pfunc = PyExc_OSError;
3934 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003935 if (PySSLErrorObject == NULL)
3936 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003937
Antoine Pitrou41032a62011-10-27 23:56:55 +02003938 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3939 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3940 PySSLErrorObject, NULL);
3941 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3942 "ssl.SSLWantReadError", SSLWantReadError_doc,
3943 PySSLErrorObject, NULL);
3944 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3945 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3946 PySSLErrorObject, NULL);
3947 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3948 "ssl.SSLSyscallError", SSLSyscallError_doc,
3949 PySSLErrorObject, NULL);
3950 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3951 "ssl.SSLEOFError", SSLEOFError_doc,
3952 PySSLErrorObject, NULL);
3953 if (PySSLZeroReturnErrorObject == NULL
3954 || PySSLWantReadErrorObject == NULL
3955 || PySSLWantWriteErrorObject == NULL
3956 || PySSLSyscallErrorObject == NULL
3957 || PySSLEOFErrorObject == NULL)
3958 return NULL;
3959 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3960 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3961 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3962 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3963 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3964 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003965 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966 if (PyDict_SetItemString(d, "_SSLContext",
3967 (PyObject *)&PySSLContext_Type) != 0)
3968 return NULL;
3969 if (PyDict_SetItemString(d, "_SSLSocket",
3970 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003971 return NULL;
3972 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3973 PY_SSL_ERROR_ZERO_RETURN);
3974 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3975 PY_SSL_ERROR_WANT_READ);
3976 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3977 PY_SSL_ERROR_WANT_WRITE);
3978 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3979 PY_SSL_ERROR_WANT_X509_LOOKUP);
3980 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3981 PY_SSL_ERROR_SYSCALL);
3982 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3983 PY_SSL_ERROR_SSL);
3984 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3985 PY_SSL_ERROR_WANT_CONNECT);
3986 /* non ssl.h errorcodes */
3987 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3988 PY_SSL_ERROR_EOF);
3989 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3990 PY_SSL_ERROR_INVALID_ERROR_CODE);
3991 /* cert requirements */
3992 PyModule_AddIntConstant(m, "CERT_NONE",
3993 PY_SSL_CERT_NONE);
3994 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3995 PY_SSL_CERT_OPTIONAL);
3996 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3997 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01003998 /* CRL verification for verification_flags */
3999 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4000 0);
4001 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4002 X509_V_FLAG_CRL_CHECK);
4003 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4004 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4005 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4006 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004007#ifdef X509_V_FLAG_TRUSTED_FIRST
4008 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4009 X509_V_FLAG_TRUSTED_FIRST);
4010#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004011
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004012 /* Alert Descriptions from ssl.h */
4013 /* note RESERVED constants no longer intended for use have been removed */
4014 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4015
4016#define ADD_AD_CONSTANT(s) \
4017 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4018 SSL_AD_##s)
4019
4020 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4021 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4022 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4023 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4024 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4025 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4026 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4027 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4028 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4029 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4030 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4031 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4032 ADD_AD_CONSTANT(UNKNOWN_CA);
4033 ADD_AD_CONSTANT(ACCESS_DENIED);
4034 ADD_AD_CONSTANT(DECODE_ERROR);
4035 ADD_AD_CONSTANT(DECRYPT_ERROR);
4036 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4037 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4038 ADD_AD_CONSTANT(INTERNAL_ERROR);
4039 ADD_AD_CONSTANT(USER_CANCELLED);
4040 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004041 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004042#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4043 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4044#endif
4045#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4046 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4047#endif
4048#ifdef SSL_AD_UNRECOGNIZED_NAME
4049 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4050#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004051#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4052 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4053#endif
4054#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4055 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4056#endif
4057#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4058 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4059#endif
4060
4061#undef ADD_AD_CONSTANT
4062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004063 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004064#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004065 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4066 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004067#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004068#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004069 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4070 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004071#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004072 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4073 PY_SSL_VERSION_SSL23);
4074 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4075 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004076#if HAVE_TLSv1_2
4077 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4078 PY_SSL_VERSION_TLS1_1);
4079 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4080 PY_SSL_VERSION_TLS1_2);
4081#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004082
Antoine Pitroub5218772010-05-21 09:56:06 +00004083 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004084 PyModule_AddIntConstant(m, "OP_ALL",
4085 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004086 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4087 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4088 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004089#if HAVE_TLSv1_2
4090 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4091 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4092#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004093 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4094 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004095 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004096#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004097 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004098#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004099#ifdef SSL_OP_NO_COMPRESSION
4100 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4101 SSL_OP_NO_COMPRESSION);
4102#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004103
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004104#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004105 r = Py_True;
4106#else
4107 r = Py_False;
4108#endif
4109 Py_INCREF(r);
4110 PyModule_AddObject(m, "HAS_SNI", r);
4111
Antoine Pitroud6494802011-07-21 01:11:30 +02004112#if HAVE_OPENSSL_FINISHED
4113 r = Py_True;
4114#else
4115 r = Py_False;
4116#endif
4117 Py_INCREF(r);
4118 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4119
Antoine Pitrou501da612011-12-21 09:27:41 +01004120#ifdef OPENSSL_NO_ECDH
4121 r = Py_False;
4122#else
4123 r = Py_True;
4124#endif
4125 Py_INCREF(r);
4126 PyModule_AddObject(m, "HAS_ECDH", r);
4127
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004128#ifdef OPENSSL_NPN_NEGOTIATED
4129 r = Py_True;
4130#else
4131 r = Py_False;
4132#endif
4133 Py_INCREF(r);
4134 PyModule_AddObject(m, "HAS_NPN", r);
4135
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004136 /* Mappings for error codes */
4137 err_codes_to_names = PyDict_New();
4138 err_names_to_codes = PyDict_New();
4139 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4140 return NULL;
4141 errcode = error_codes;
4142 while (errcode->mnemonic != NULL) {
4143 PyObject *mnemo, *key;
4144 mnemo = PyUnicode_FromString(errcode->mnemonic);
4145 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4146 if (mnemo == NULL || key == NULL)
4147 return NULL;
4148 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4149 return NULL;
4150 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4151 return NULL;
4152 Py_DECREF(key);
4153 Py_DECREF(mnemo);
4154 errcode++;
4155 }
4156 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4157 return NULL;
4158 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4159 return NULL;
4160
4161 lib_codes_to_names = PyDict_New();
4162 if (lib_codes_to_names == NULL)
4163 return NULL;
4164 libcode = library_codes;
4165 while (libcode->library != NULL) {
4166 PyObject *mnemo, *key;
4167 key = PyLong_FromLong(libcode->code);
4168 mnemo = PyUnicode_FromString(libcode->library);
4169 if (key == NULL || mnemo == NULL)
4170 return NULL;
4171 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4172 return NULL;
4173 Py_DECREF(key);
4174 Py_DECREF(mnemo);
4175 libcode++;
4176 }
4177 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4178 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004180 /* OpenSSL version */
4181 /* SSLeay() gives us the version of the library linked against,
4182 which could be different from the headers version.
4183 */
4184 libver = SSLeay();
4185 r = PyLong_FromUnsignedLong(libver);
4186 if (r == NULL)
4187 return NULL;
4188 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4189 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004190 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004191 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4192 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4193 return NULL;
4194 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4195 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4196 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004197
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004198 libver = OPENSSL_VERSION_NUMBER;
4199 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4200 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4201 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4202 return NULL;
4203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004204 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004205}