blob: 5b85cc7272fa6864d31777f26d5d748f6baf8709 [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 # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000254#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200255#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200257
258/*
259 * SSL errors.
260 */
261
262PyDoc_STRVAR(SSLError_doc,
263"An error occurred in the SSL implementation.");
264
265PyDoc_STRVAR(SSLZeroReturnError_doc,
266"SSL/TLS session closed cleanly.");
267
268PyDoc_STRVAR(SSLWantReadError_doc,
269"Non-blocking SSL socket needs to read more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLWantWriteError_doc,
273"Non-blocking SSL socket needs to write more data\n"
274"before the requested operation can be completed.");
275
276PyDoc_STRVAR(SSLSyscallError_doc,
277"System error when attempting SSL operation.");
278
279PyDoc_STRVAR(SSLEOFError_doc,
280"SSL/TLS connection terminated abruptly.");
281
282static PyObject *
283SSLError_str(PyOSErrorObject *self)
284{
285 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
286 Py_INCREF(self->strerror);
287 return self->strerror;
288 }
289 else
290 return PyObject_Str(self->args);
291}
292
293static PyType_Slot sslerror_type_slots[] = {
294 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
295 {Py_tp_doc, SSLError_doc},
296 {Py_tp_str, SSLError_str},
297 {0, 0},
298};
299
300static PyType_Spec sslerror_type_spec = {
301 "ssl.SSLError",
302 sizeof(PyOSErrorObject),
303 0,
304 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
305 sslerror_type_slots
306};
307
308static void
309fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
310 int lineno, unsigned long errcode)
311{
312 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
313 PyObject *init_value, *msg, *key;
314 _Py_IDENTIFIER(reason);
315 _Py_IDENTIFIER(library);
316
317 if (errcode != 0) {
318 int lib, reason;
319
320 lib = ERR_GET_LIB(errcode);
321 reason = ERR_GET_REASON(errcode);
322 key = Py_BuildValue("ii", lib, reason);
323 if (key == NULL)
324 goto fail;
325 reason_obj = PyDict_GetItem(err_codes_to_names, key);
326 Py_DECREF(key);
327 if (reason_obj == NULL) {
328 /* XXX if reason < 100, it might reflect a library number (!!) */
329 PyErr_Clear();
330 }
331 key = PyLong_FromLong(lib);
332 if (key == NULL)
333 goto fail;
334 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
335 Py_DECREF(key);
336 if (lib_obj == NULL) {
337 PyErr_Clear();
338 }
339 if (errstr == NULL)
340 errstr = ERR_reason_error_string(errcode);
341 }
342 if (errstr == NULL)
343 errstr = "unknown error";
344
345 if (reason_obj && lib_obj)
346 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
347 lib_obj, reason_obj, errstr, lineno);
348 else if (lib_obj)
349 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
350 lib_obj, errstr, lineno);
351 else
352 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200353 if (msg == NULL)
354 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100355
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100357 if (init_value == NULL)
358 goto fail;
359
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200360 err_value = PyObject_CallObject(type, init_value);
361 Py_DECREF(init_value);
362 if (err_value == NULL)
363 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100364
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200365 if (reason_obj == NULL)
366 reason_obj = Py_None;
367 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
368 goto fail;
369 if (lib_obj == NULL)
370 lib_obj = Py_None;
371 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
372 goto fail;
373 PyErr_SetObject(type, err_value);
374fail:
375 Py_XDECREF(err_value);
376}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377
378static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000379PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200381 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 int err;
384 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200388 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 if (obj->ssl != NULL) {
391 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 switch (err) {
394 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 errstr = "TLS/SSL connection has been closed (EOF)";
396 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 p = PY_SSL_ERROR_ZERO_RETURN;
398 break;
399 case SSL_ERROR_WANT_READ:
400 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000402 p = PY_SSL_ERROR_WANT_READ;
403 break;
404 case SSL_ERROR_WANT_WRITE:
405 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200406 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 errstr = "The operation did not complete (write)";
408 break;
409 case SSL_ERROR_WANT_X509_LOOKUP:
410 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000411 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000412 break;
413 case SSL_ERROR_WANT_CONNECT:
414 p = PY_SSL_ERROR_WANT_CONNECT;
415 errstr = "The operation did not complete (connect)";
416 break;
417 case SSL_ERROR_SYSCALL:
418 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 if (e == 0) {
420 PySocketSockObject *s
421 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
422 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200424 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000428 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000429 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000431 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000434 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200435 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 }
438 } else {
439 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000440 }
441 break;
442 }
443 case SSL_ERROR_SSL:
444 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200446 if (e == 0)
447 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000448 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000449 break;
450 }
451 default:
452 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
453 errstr = "Invalid error code";
454 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000457 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459}
460
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461static PyObject *
462_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
463
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 else
467 errcode = 0;
468 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000469 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471}
472
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473/*
474 * SSL objects
475 */
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100478newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000479 enum py_ssl_server_or_client socket_type,
480 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100483 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200484 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
Antoine Pitrou152efa22010-05-16 18:19:27 +0000486 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 if (self == NULL)
488 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 self->peer_cert = NULL;
491 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100493 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200494 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200495 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100496 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 /* Make sure the SSL error state is initialized */
499 (void) ERR_get_state();
500 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000503 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100505 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100506 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000508#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000510#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200511 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000512
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100513#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000514 if (server_hostname != NULL)
515 SSL_set_tlsext_host_name(self->ssl, server_hostname);
516#endif
517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 /* If the socket is in non-blocking mode or timeout mode, set the BIO
519 * to non-blocking mode (blocking is the default)
520 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
523 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
524 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 PySSL_BEGIN_ALLOW_THREADS
527 if (socket_type == PY_SSL_CLIENT)
528 SSL_set_connect_state(self->ssl);
529 else
530 SSL_set_accept_state(self->ssl);
531 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000532
Antoine Pitroud6494802011-07-21 01:11:30 +0200533 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000534 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100535 if (self->Socket == NULL) {
536 Py_DECREF(self);
537 return NULL;
538 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000540}
541
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542/* SSL object methods */
543
Antoine Pitrou152efa22010-05-16 18:19:27 +0000544static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000545{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 int ret;
547 int err;
548 int sockstate, nonblocking;
549 PySocketSockObject *sock
550 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 if (((PyObject*)sock) == Py_None) {
553 _setSSLError("Underlying socket connection gone",
554 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
555 return NULL;
556 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000557 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000559 /* just in case the blocking state of the socket has been changed */
560 nonblocking = (sock->sock_timeout >= 0.0);
561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 /* Actually negotiate SSL connection */
565 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000567 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 ret = SSL_do_handshake(self->ssl);
569 err = SSL_get_error(self->ssl, ret);
570 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 if (PyErr_CheckSignals())
572 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 if (err == SSL_ERROR_WANT_READ) {
574 sockstate = check_socket_and_wait_for_timeout(sock, 0);
575 } else if (err == SSL_ERROR_WANT_WRITE) {
576 sockstate = check_socket_and_wait_for_timeout(sock, 1);
577 } else {
578 sockstate = SOCKET_OPERATION_OK;
579 }
580 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000581 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
585 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000586 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
589 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000590 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
593 break;
594 }
595 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000596 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 if (ret < 1)
598 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 if (self->peer_cert)
601 X509_free (self->peer_cert);
602 PySSL_BEGIN_ALLOW_THREADS
603 self->peer_cert = SSL_get_peer_certificate(self->ssl);
604 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200605 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606
607 Py_INCREF(Py_None);
608 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000609
610error:
611 Py_DECREF(sock);
612 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613}
614
Thomas Woutersed03b412007-08-28 21:37:11 +0000615static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 char namebuf[X509_NAME_MAXLEN];
619 int buflen;
620 PyObject *name_obj;
621 PyObject *value_obj;
622 PyObject *attr;
623 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
626 if (buflen < 0) {
627 _setSSLError(NULL, 0, __FILE__, __LINE__);
628 goto fail;
629 }
630 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
631 if (name_obj == NULL)
632 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
635 if (buflen < 0) {
636 _setSSLError(NULL, 0, __FILE__, __LINE__);
637 Py_DECREF(name_obj);
638 goto fail;
639 }
640 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000641 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 OPENSSL_free(valuebuf);
643 if (value_obj == NULL) {
644 Py_DECREF(name_obj);
645 goto fail;
646 }
647 attr = PyTuple_New(2);
648 if (attr == NULL) {
649 Py_DECREF(name_obj);
650 Py_DECREF(value_obj);
651 goto fail;
652 }
653 PyTuple_SET_ITEM(attr, 0, name_obj);
654 PyTuple_SET_ITEM(attr, 1, value_obj);
655 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000659}
660
661static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
665 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
666 PyObject *rdnt;
667 PyObject *attr = NULL; /* tuple to hold an attribute */
668 int entry_count = X509_NAME_entry_count(xname);
669 X509_NAME_ENTRY *entry;
670 ASN1_OBJECT *name;
671 ASN1_STRING *value;
672 int index_counter;
673 int rdn_level = -1;
674 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 dn = PyList_New(0);
677 if (dn == NULL)
678 return NULL;
679 /* now create another tuple to hold the top-level RDN */
680 rdn = PyList_New(0);
681 if (rdn == NULL)
682 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 for (index_counter = 0;
685 index_counter < entry_count;
686 index_counter++)
687 {
688 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 /* check to see if we've gotten to a new RDN */
691 if (rdn_level >= 0) {
692 if (rdn_level != entry->set) {
693 /* yes, new RDN */
694 /* add old RDN to DN */
695 rdnt = PyList_AsTuple(rdn);
696 Py_DECREF(rdn);
697 if (rdnt == NULL)
698 goto fail0;
699 retcode = PyList_Append(dn, rdnt);
700 Py_DECREF(rdnt);
701 if (retcode < 0)
702 goto fail0;
703 /* create new RDN */
704 rdn = PyList_New(0);
705 if (rdn == NULL)
706 goto fail0;
707 }
708 }
709 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 /* now add this attribute to the current RDN */
712 name = X509_NAME_ENTRY_get_object(entry);
713 value = X509_NAME_ENTRY_get_data(entry);
714 attr = _create_tuple_for_attribute(name, value);
715 /*
716 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
717 entry->set,
718 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
719 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
720 */
721 if (attr == NULL)
722 goto fail1;
723 retcode = PyList_Append(rdn, attr);
724 Py_DECREF(attr);
725 if (retcode < 0)
726 goto fail1;
727 }
728 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100729 if (rdn != NULL) {
730 if (PyList_GET_SIZE(rdn) > 0) {
731 rdnt = PyList_AsTuple(rdn);
732 Py_DECREF(rdn);
733 if (rdnt == NULL)
734 goto fail0;
735 retcode = PyList_Append(dn, rdnt);
736 Py_DECREF(rdnt);
737 if (retcode < 0)
738 goto fail0;
739 }
740 else {
741 Py_DECREF(rdn);
742 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* convert list to tuple */
746 rdnt = PyList_AsTuple(dn);
747 Py_DECREF(dn);
748 if (rdnt == NULL)
749 return NULL;
750 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
752 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754
755 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 Py_XDECREF(dn);
757 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758}
759
760static PyObject *
761_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 /* this code follows the procedure outlined in
764 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
765 function to extract the STACK_OF(GENERAL_NAME),
766 then iterates through the stack to add the
767 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 int i, j;
770 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200771 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 X509_EXTENSION *ext = NULL;
773 GENERAL_NAMES *names = NULL;
774 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000775 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 BIO *biobuf = NULL;
777 char buf[2048];
778 char *vptr;
779 int len;
780 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000781#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000783#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000785#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 if (certificate == NULL)
788 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 /* get a memory buffer */
791 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200793 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 while ((i = X509_get_ext_by_NID(
795 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 if (peer_alt_names == Py_None) {
798 peer_alt_names = PyList_New(0);
799 if (peer_alt_names == NULL)
800 goto fail;
801 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* now decode the altName */
804 ext = X509_get_ext(certificate, i);
805 if(!(method = X509V3_EXT_get(ext))) {
806 PyErr_SetString
807 (PySSLErrorObject,
808 ERRSTR("No method for internalizing subjectAltName!"));
809 goto fail;
810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 p = ext->value->data;
813 if (method->it)
814 names = (GENERAL_NAMES*)
815 (ASN1_item_d2i(NULL,
816 &p,
817 ext->value->length,
818 ASN1_ITEM_ptr(method->it)));
819 else
820 names = (GENERAL_NAMES*)
821 (method->d2i(NULL,
822 &p,
823 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200827 int gntype;
828 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200831 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200832 switch (gntype) {
833 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* we special-case DirName as a tuple of
835 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 t = PyTuple_New(2);
838 if (t == NULL) {
839 goto fail;
840 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 v = PyUnicode_FromString("DirName");
843 if (v == NULL) {
844 Py_DECREF(t);
845 goto fail;
846 }
847 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 v = _create_tuple_for_X509_NAME (name->d.dirn);
850 if (v == NULL) {
851 Py_DECREF(t);
852 goto fail;
853 }
854 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200855 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000856
Christian Heimes824f7f32013-08-17 00:54:47 +0200857 case GEN_EMAIL:
858 case GEN_DNS:
859 case GEN_URI:
860 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
861 correctly, CVE-2013-4238 */
862 t = PyTuple_New(2);
863 if (t == NULL)
864 goto fail;
865 switch (gntype) {
866 case GEN_EMAIL:
867 v = PyUnicode_FromString("email");
868 as = name->d.rfc822Name;
869 break;
870 case GEN_DNS:
871 v = PyUnicode_FromString("DNS");
872 as = name->d.dNSName;
873 break;
874 case GEN_URI:
875 v = PyUnicode_FromString("URI");
876 as = name->d.uniformResourceIdentifier;
877 break;
878 }
879 if (v == NULL) {
880 Py_DECREF(t);
881 goto fail;
882 }
883 PyTuple_SET_ITEM(t, 0, v);
884 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
885 ASN1_STRING_length(as));
886 if (v == NULL) {
887 Py_DECREF(t);
888 goto fail;
889 }
890 PyTuple_SET_ITEM(t, 1, v);
891 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Christian Heimes824f7f32013-08-17 00:54:47 +0200893 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 switch (gntype) {
896 /* check for new general name type */
897 case GEN_OTHERNAME:
898 case GEN_X400:
899 case GEN_EDIPARTY:
900 case GEN_IPADD:
901 case GEN_RID:
902 break;
903 default:
904 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
905 "Unknown general name type %d",
906 gntype) == -1) {
907 goto fail;
908 }
909 break;
910 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 (void) BIO_reset(biobuf);
912 GENERAL_NAME_print(biobuf, name);
913 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
914 if (len < 0) {
915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 goto fail;
917 }
918 vptr = strchr(buf, ':');
919 if (vptr == NULL)
920 goto fail;
921 t = PyTuple_New(2);
922 if (t == NULL)
923 goto fail;
924 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
925 if (v == NULL) {
926 Py_DECREF(t);
927 goto fail;
928 }
929 PyTuple_SET_ITEM(t, 0, v);
930 v = PyUnicode_FromStringAndSize((vptr + 1),
931 (len - (vptr - buf + 1)));
932 if (v == NULL) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 if (PyList_Append(peer_alt_names, t) < 0) {
943 Py_DECREF(t);
944 goto fail;
945 }
946 Py_DECREF(t);
947 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100948 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 }
950 BIO_free(biobuf);
951 if (peer_alt_names != Py_None) {
952 v = PyList_AsTuple(peer_alt_names);
953 Py_DECREF(peer_alt_names);
954 return v;
955 } else {
956 return peer_alt_names;
957 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000958
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
960 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 if (biobuf != NULL)
962 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 if (peer_alt_names != Py_None) {
965 Py_XDECREF(peer_alt_names);
966 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969}
970
971static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100972_get_aia_uri(X509 *certificate, int nid) {
973 PyObject *lst = NULL, *ostr = NULL;
974 int i, result;
975 AUTHORITY_INFO_ACCESS *info;
976
977 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
978 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
979 return Py_None;
980 }
981
982 if ((lst = PyList_New(0)) == NULL) {
983 goto fail;
984 }
985
986 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
987 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
988 ASN1_IA5STRING *uri;
989
990 if ((OBJ_obj2nid(ad->method) != nid) ||
991 (ad->location->type != GEN_URI)) {
992 continue;
993 }
994 uri = ad->location->d.uniformResourceIdentifier;
995 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
996 uri->length);
997 if (ostr == NULL) {
998 goto fail;
999 }
1000 result = PyList_Append(lst, ostr);
1001 Py_DECREF(ostr);
1002 if (result < 0) {
1003 goto fail;
1004 }
1005 }
1006 AUTHORITY_INFO_ACCESS_free(info);
1007
1008 /* convert to tuple or None */
1009 if (PyList_Size(lst) == 0) {
1010 Py_DECREF(lst);
1011 return Py_None;
1012 } else {
1013 PyObject *tup;
1014 tup = PyList_AsTuple(lst);
1015 Py_DECREF(lst);
1016 return tup;
1017 }
1018
1019 fail:
1020 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001021 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001022 return NULL;
1023}
1024
1025static PyObject *
1026_get_crl_dp(X509 *certificate) {
1027 STACK_OF(DIST_POINT) *dps;
1028 int i, j, result;
1029 PyObject *lst;
1030
Christian Heimes949ec142013-11-21 16:26:51 +01001031#if OPENSSL_VERSION_NUMBER < 0x10001000L
1032 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1033 NULL, NULL);
1034#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001035 /* Calls x509v3_cache_extensions and sets up crldp */
1036 X509_check_ca(certificate);
1037 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001038#endif
1039
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001040 if (dps == NULL) {
1041 return Py_None;
1042 }
1043
1044 if ((lst = PyList_New(0)) == NULL) {
1045 return NULL;
1046 }
1047
1048 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1049 DIST_POINT *dp;
1050 STACK_OF(GENERAL_NAME) *gns;
1051
1052 dp = sk_DIST_POINT_value(dps, i);
1053 gns = dp->distpoint->name.fullname;
1054
1055 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1056 GENERAL_NAME *gn;
1057 ASN1_IA5STRING *uri;
1058 PyObject *ouri;
1059
1060 gn = sk_GENERAL_NAME_value(gns, j);
1061 if (gn->type != GEN_URI) {
1062 continue;
1063 }
1064 uri = gn->d.uniformResourceIdentifier;
1065 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1066 uri->length);
1067 if (ouri == NULL) {
1068 Py_DECREF(lst);
1069 return NULL;
1070 }
1071 result = PyList_Append(lst, ouri);
1072 Py_DECREF(ouri);
1073 if (result < 0) {
1074 Py_DECREF(lst);
1075 return NULL;
1076 }
1077 }
1078 }
1079 /* convert to tuple or None */
1080 if (PyList_Size(lst) == 0) {
1081 Py_DECREF(lst);
1082 return Py_None;
1083 } else {
1084 PyObject *tup;
1085 tup = PyList_AsTuple(lst);
1086 Py_DECREF(lst);
1087 return tup;
1088 }
1089}
1090
1091static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001092_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 PyObject *retval = NULL;
1095 BIO *biobuf = NULL;
1096 PyObject *peer;
1097 PyObject *peer_alt_names = NULL;
1098 PyObject *issuer;
1099 PyObject *version;
1100 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001101 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 ASN1_INTEGER *serialNumber;
1103 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001104 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 ASN1_TIME *notBefore, *notAfter;
1106 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 retval = PyDict_New();
1109 if (retval == NULL)
1110 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 peer = _create_tuple_for_X509_NAME(
1113 X509_get_subject_name(certificate));
1114 if (peer == NULL)
1115 goto fail0;
1116 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1117 Py_DECREF(peer);
1118 goto fail0;
1119 }
1120 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001121
Antoine Pitroufb046912010-11-09 20:21:19 +00001122 issuer = _create_tuple_for_X509_NAME(
1123 X509_get_issuer_name(certificate));
1124 if (issuer == NULL)
1125 goto fail0;
1126 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001128 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001130 Py_DECREF(issuer);
1131
1132 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001133 if (version == NULL)
1134 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001135 if (PyDict_SetItemString(retval, "version", version) < 0) {
1136 Py_DECREF(version);
1137 goto fail0;
1138 }
1139 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 /* get a memory buffer */
1142 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001143
Antoine Pitroufb046912010-11-09 20:21:19 +00001144 (void) BIO_reset(biobuf);
1145 serialNumber = X509_get_serialNumber(certificate);
1146 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1147 i2a_ASN1_INTEGER(biobuf, serialNumber);
1148 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1149 if (len < 0) {
1150 _setSSLError(NULL, 0, __FILE__, __LINE__);
1151 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001153 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1154 if (sn_obj == NULL)
1155 goto fail1;
1156 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1157 Py_DECREF(sn_obj);
1158 goto fail1;
1159 }
1160 Py_DECREF(sn_obj);
1161
1162 (void) BIO_reset(biobuf);
1163 notBefore = X509_get_notBefore(certificate);
1164 ASN1_TIME_print(biobuf, notBefore);
1165 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1166 if (len < 0) {
1167 _setSSLError(NULL, 0, __FILE__, __LINE__);
1168 goto fail1;
1169 }
1170 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1171 if (pnotBefore == NULL)
1172 goto fail1;
1173 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1174 Py_DECREF(pnotBefore);
1175 goto fail1;
1176 }
1177 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 (void) BIO_reset(biobuf);
1180 notAfter = X509_get_notAfter(certificate);
1181 ASN1_TIME_print(biobuf, notAfter);
1182 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1183 if (len < 0) {
1184 _setSSLError(NULL, 0, __FILE__, __LINE__);
1185 goto fail1;
1186 }
1187 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1188 if (pnotAfter == NULL)
1189 goto fail1;
1190 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1191 Py_DECREF(pnotAfter);
1192 goto fail1;
1193 }
1194 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 peer_alt_names = _get_peer_alt_names(certificate);
1199 if (peer_alt_names == NULL)
1200 goto fail1;
1201 else if (peer_alt_names != Py_None) {
1202 if (PyDict_SetItemString(retval, "subjectAltName",
1203 peer_alt_names) < 0) {
1204 Py_DECREF(peer_alt_names);
1205 goto fail1;
1206 }
1207 Py_DECREF(peer_alt_names);
1208 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001209
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 /* Authority Information Access: OCSP URIs */
1211 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1212 if (obj == NULL) {
1213 goto fail1;
1214 } else if (obj != Py_None) {
1215 result = PyDict_SetItemString(retval, "OCSP", obj);
1216 Py_DECREF(obj);
1217 if (result < 0) {
1218 goto fail1;
1219 }
1220 }
1221
1222 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1223 if (obj == NULL) {
1224 goto fail1;
1225 } else if (obj != Py_None) {
1226 result = PyDict_SetItemString(retval, "caIssuers", obj);
1227 Py_DECREF(obj);
1228 if (result < 0) {
1229 goto fail1;
1230 }
1231 }
1232
1233 /* CDP (CRL distribution points) */
1234 obj = _get_crl_dp(certificate);
1235 if (obj == NULL) {
1236 goto fail1;
1237 } else if (obj != Py_None) {
1238 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1239 Py_DECREF(obj);
1240 if (result < 0) {
1241 goto fail1;
1242 }
1243 }
1244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 BIO_free(biobuf);
1246 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001247
1248 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 if (biobuf != NULL)
1250 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001251 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 Py_XDECREF(retval);
1253 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001254}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255
Christian Heimes9a5395a2013-06-17 15:44:12 +02001256static PyObject *
1257_certificate_to_der(X509 *certificate)
1258{
1259 unsigned char *bytes_buf = NULL;
1260 int len;
1261 PyObject *retval;
1262
1263 bytes_buf = NULL;
1264 len = i2d_X509(certificate, &bytes_buf);
1265 if (len < 0) {
1266 _setSSLError(NULL, 0, __FILE__, __LINE__);
1267 return NULL;
1268 }
1269 /* this is actually an immutable bytes sequence */
1270 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1271 OPENSSL_free(bytes_buf);
1272 return retval;
1273}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
1275static PyObject *
1276PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001279 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 X509 *x=NULL;
1281 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
Antoine Pitroufb046912010-11-09 20:21:19 +00001283 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1284 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1288 PyErr_SetString(PySSLErrorObject,
1289 "Can't malloc memory to read file");
1290 goto fail0;
1291 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001292
Victor Stinner3800e1e2010-05-16 21:23:48 +00001293 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 PyErr_SetString(PySSLErrorObject,
1295 "Can't open file");
1296 goto fail0;
1297 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1300 if (x == NULL) {
1301 PyErr_SetString(PySSLErrorObject,
1302 "Error decoding PEM-encoded file");
1303 goto fail0;
1304 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001305
Antoine Pitroufb046912010-11-09 20:21:19 +00001306 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001307 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
1309 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001310 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 if (cert != NULL) BIO_free(cert);
1312 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313}
1314
1315
1316static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001317PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001320 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Antoine Pitrou721738f2012-08-15 23:20:39 +02001322 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324
Antoine Pitrou20b85552013-09-29 19:50:53 +02001325 if (!self->handshake_done) {
1326 PyErr_SetString(PyExc_ValueError,
1327 "handshake not done yet");
1328 return NULL;
1329 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 if (!self->peer_cert)
1331 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitrou721738f2012-08-15 23:20:39 +02001333 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001335 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001337 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 if ((verification & SSL_VERIFY_PEER) == 0)
1339 return PyDict_New();
1340 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001341 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343}
1344
1345PyDoc_STRVAR(PySSL_peercert_doc,
1346"peer_certificate([der=False]) -> certificate\n\
1347\n\
1348Returns the certificate for the peer. If no certificate was provided,\n\
1349returns None. If a certificate was provided, but not validated, returns\n\
1350an empty dictionary. Otherwise returns a dict containing information\n\
1351about the peer certificate.\n\
1352\n\
1353If the optional argument is True, returns a DER-encoded copy of the\n\
1354peer certificate, or None if no certificate was provided. This will\n\
1355return the certificate even if it wasn't validated.");
1356
Antoine Pitrou152efa22010-05-16 18:19:27 +00001357static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001360 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 char *cipher_name;
1362 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001365 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 current = SSL_get_current_cipher(self->ssl);
1367 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001368 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 retval = PyTuple_New(3);
1371 if (retval == NULL)
1372 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 cipher_name = (char *) SSL_CIPHER_get_name(current);
1375 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001376 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 PyTuple_SET_ITEM(retval, 0, Py_None);
1378 } else {
1379 v = PyUnicode_FromString(cipher_name);
1380 if (v == NULL)
1381 goto fail0;
1382 PyTuple_SET_ITEM(retval, 0, v);
1383 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001384 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001386 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 PyTuple_SET_ITEM(retval, 1, Py_None);
1388 } else {
1389 v = PyUnicode_FromString(cipher_protocol);
1390 if (v == NULL)
1391 goto fail0;
1392 PyTuple_SET_ITEM(retval, 1, v);
1393 }
1394 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1395 if (v == NULL)
1396 goto fail0;
1397 PyTuple_SET_ITEM(retval, 2, v);
1398 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001399
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 Py_DECREF(retval);
1402 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403}
1404
Antoine Pitrou47e40422014-09-04 21:00:10 +02001405static PyObject *PySSL_version(PySSLSocket *self)
1406{
1407 const char *version;
1408
1409 if (self->ssl == NULL)
1410 Py_RETURN_NONE;
1411 version = SSL_get_version(self->ssl);
1412 if (!strcmp(version, "unknown"))
1413 Py_RETURN_NONE;
1414 return PyUnicode_FromString(version);
1415}
1416
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001417#ifdef OPENSSL_NPN_NEGOTIATED
1418static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1419 const unsigned char *out;
1420 unsigned int outlen;
1421
Victor Stinner4569cd52013-06-23 14:58:43 +02001422 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001423 &out, &outlen);
1424
1425 if (out == NULL)
1426 Py_RETURN_NONE;
1427 return PyUnicode_FromStringAndSize((char *) out, outlen);
1428}
1429#endif
1430
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001431static PyObject *PySSL_compression(PySSLSocket *self) {
1432#ifdef OPENSSL_NO_COMP
1433 Py_RETURN_NONE;
1434#else
1435 const COMP_METHOD *comp_method;
1436 const char *short_name;
1437
1438 if (self->ssl == NULL)
1439 Py_RETURN_NONE;
1440 comp_method = SSL_get_current_compression(self->ssl);
1441 if (comp_method == NULL || comp_method->type == NID_undef)
1442 Py_RETURN_NONE;
1443 short_name = OBJ_nid2sn(comp_method->type);
1444 if (short_name == NULL)
1445 Py_RETURN_NONE;
1446 return PyUnicode_DecodeFSDefault(short_name);
1447#endif
1448}
1449
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001450static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1451 Py_INCREF(self->ctx);
1452 return self->ctx;
1453}
1454
1455static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1456 void *closure) {
1457
1458 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001459#if !HAVE_SNI
1460 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1461 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001462 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001463#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001464 Py_INCREF(value);
1465 Py_DECREF(self->ctx);
1466 self->ctx = (PySSLContext *) value;
1467 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001468#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001469 } else {
1470 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1471 return -1;
1472 }
1473
1474 return 0;
1475}
1476
1477PyDoc_STRVAR(PySSL_set_context_doc,
1478"_setter_context(ctx)\n\
1479\
1480This changes the context associated with the SSLSocket. This is typically\n\
1481used from within a callback function set by the set_servername_callback\n\
1482on the SSLContext to change the certificate information associated with the\n\
1483SSLSocket before the cryptographic exchange handshake messages\n");
1484
1485
1486
Antoine Pitrou152efa22010-05-16 18:19:27 +00001487static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001488{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 if (self->peer_cert) /* Possible not to have one? */
1490 X509_free (self->peer_cert);
1491 if (self->ssl)
1492 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001494 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001496}
1497
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001498/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001499 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001500 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001501 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001502
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001503static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001504check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001505{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 fd_set fds;
1507 struct timeval tv;
1508 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1511 if (s->sock_timeout < 0.0)
1512 return SOCKET_IS_BLOCKING;
1513 else if (s->sock_timeout == 0.0)
1514 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 /* Guard against closed socket */
1517 if (s->sock_fd < 0)
1518 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 /* Prefer poll, if available, since you can poll() any fd
1521 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001522#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 {
1524 struct pollfd pollfd;
1525 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 pollfd.fd = s->sock_fd;
1528 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 /* s->sock_timeout is in seconds, timeout in ms */
1531 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1532 PySSL_BEGIN_ALLOW_THREADS
1533 rc = poll(&pollfd, 1, timeout);
1534 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 goto normal_return;
1537 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001538#endif
1539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001541 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 /* Construct the arguments to select */
1545 tv.tv_sec = (int)s->sock_timeout;
1546 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1547 FD_ZERO(&fds);
1548 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 /* See if the socket is ready */
1551 PySSL_BEGIN_ALLOW_THREADS
1552 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001553 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1554 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001556 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1557 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001559
Bill Janssen6e027db2007-11-15 22:23:56 +00001560#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001561normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001562#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1564 (when we are able to write or when there's something to read) */
1565 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001566}
1567
Antoine Pitrou152efa22010-05-16 18:19:27 +00001568static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001569{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 Py_buffer buf;
1571 int len;
1572 int sockstate;
1573 int err;
1574 int nonblocking;
1575 PySocketSockObject *sock
1576 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578 if (((PyObject*)sock) == Py_None) {
1579 _setSSLError("Underlying socket connection gone",
1580 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1581 return NULL;
1582 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001583 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001585 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1586 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001588 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589
Victor Stinner6efa9652013-06-25 00:42:31 +02001590 if (buf.len > INT_MAX) {
1591 PyErr_Format(PyExc_OverflowError,
1592 "string longer than %d bytes", INT_MAX);
1593 goto error;
1594 }
1595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001596 /* just in case the blocking state of the socket has been changed */
1597 nonblocking = (sock->sock_timeout >= 0.0);
1598 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1599 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1600
1601 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1602 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001603 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 "The write operation timed out");
1605 goto error;
1606 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1607 PyErr_SetString(PySSLErrorObject,
1608 "Underlying socket has been closed.");
1609 goto error;
1610 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1611 PyErr_SetString(PySSLErrorObject,
1612 "Underlying socket too large for select().");
1613 goto error;
1614 }
1615 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001617 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 err = SSL_get_error(self->ssl, len);
1619 PySSL_END_ALLOW_THREADS
1620 if (PyErr_CheckSignals()) {
1621 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001622 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001624 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001626 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 } else {
1628 sockstate = SOCKET_OPERATION_OK;
1629 }
1630 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001631 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 "The write operation timed out");
1633 goto error;
1634 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1635 PyErr_SetString(PySSLErrorObject,
1636 "Underlying socket has been closed.");
1637 goto error;
1638 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1639 break;
1640 }
1641 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001642
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001643 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 PyBuffer_Release(&buf);
1645 if (len > 0)
1646 return PyLong_FromLong(len);
1647 else
1648 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001649
1650error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001651 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 PyBuffer_Release(&buf);
1653 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001654}
1655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001656PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001657"write(s) -> len\n\
1658\n\
1659Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001660of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001661
Antoine Pitrou152efa22010-05-16 18:19:27 +00001662static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 PySSL_BEGIN_ALLOW_THREADS
1667 count = SSL_pending(self->ssl);
1668 PySSL_END_ALLOW_THREADS
1669 if (count < 0)
1670 return PySSL_SetError(self, count, __FILE__, __LINE__);
1671 else
1672 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001673}
1674
1675PyDoc_STRVAR(PySSL_SSLpending_doc,
1676"pending() -> count\n\
1677\n\
1678Returns the number of already decrypted bytes available for read,\n\
1679pending on the connection.\n");
1680
Antoine Pitrou152efa22010-05-16 18:19:27 +00001681static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001682{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 PyObject *dest = NULL;
1684 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001686 int len, count;
1687 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 int sockstate;
1689 int err;
1690 int nonblocking;
1691 PySocketSockObject *sock
1692 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 if (((PyObject*)sock) == Py_None) {
1695 _setSSLError("Underlying socket connection gone",
1696 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1697 return NULL;
1698 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001699 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001701 buf.obj = NULL;
1702 buf.buf = NULL;
1703 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001704 goto error;
1705
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001706 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1707 dest = PyBytes_FromStringAndSize(NULL, len);
1708 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001709 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001710 mem = PyBytes_AS_STRING(dest);
1711 }
1712 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001714 mem = buf.buf;
1715 if (len <= 0 || len > buf.len) {
1716 len = (int) buf.len;
1717 if (buf.len != len) {
1718 PyErr_SetString(PyExc_OverflowError,
1719 "maximum length can't fit in a C 'int'");
1720 goto error;
1721 }
1722 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 }
1724
1725 /* just in case the blocking state of the socket has been changed */
1726 nonblocking = (sock->sock_timeout >= 0.0);
1727 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1728 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1729
1730 /* first check if there are bytes ready to be read */
1731 PySSL_BEGIN_ALLOW_THREADS
1732 count = SSL_pending(self->ssl);
1733 PySSL_END_ALLOW_THREADS
1734
1735 if (!count) {
1736 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1737 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001738 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 "The read operation timed out");
1740 goto error;
1741 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1742 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001743 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001744 goto error;
1745 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1746 count = 0;
1747 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001748 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 }
1750 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 PySSL_BEGIN_ALLOW_THREADS
1752 count = SSL_read(self->ssl, mem, len);
1753 err = SSL_get_error(self->ssl, count);
1754 PySSL_END_ALLOW_THREADS
1755 if (PyErr_CheckSignals())
1756 goto error;
1757 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001758 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001760 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1762 (SSL_get_shutdown(self->ssl) ==
1763 SSL_RECEIVED_SHUTDOWN))
1764 {
1765 count = 0;
1766 goto done;
1767 } else {
1768 sockstate = SOCKET_OPERATION_OK;
1769 }
1770 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001771 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 "The read operation timed out");
1773 goto error;
1774 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1775 break;
1776 }
1777 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1778 if (count <= 0) {
1779 PySSL_SetError(self, count, __FILE__, __LINE__);
1780 goto error;
1781 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001782
1783done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001784 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001786 _PyBytes_Resize(&dest, count);
1787 return dest;
1788 }
1789 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 PyBuffer_Release(&buf);
1791 return PyLong_FromLong(count);
1792 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001793
1794error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001795 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001796 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001797 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001798 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001801}
1802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001803PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001804"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001805\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001806Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001807
Antoine Pitrou152efa22010-05-16 18:19:27 +00001808static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001809{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 int err, ssl_err, sockstate, nonblocking;
1811 int zeros = 0;
1812 PySocketSockObject *sock
1813 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 /* Guard against closed socket */
1816 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1817 _setSSLError("Underlying socket connection gone",
1818 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1819 return NULL;
1820 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001821 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822
1823 /* Just in case the blocking state of the socket has been changed */
1824 nonblocking = (sock->sock_timeout >= 0.0);
1825 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1826 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1827
1828 while (1) {
1829 PySSL_BEGIN_ALLOW_THREADS
1830 /* Disable read-ahead so that unwrap can work correctly.
1831 * Otherwise OpenSSL might read in too much data,
1832 * eating clear text data that happens to be
1833 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001834 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 * function is used and the shutdown_seen_zero != 0
1836 * condition is met.
1837 */
1838 if (self->shutdown_seen_zero)
1839 SSL_set_read_ahead(self->ssl, 0);
1840 err = SSL_shutdown(self->ssl);
1841 PySSL_END_ALLOW_THREADS
1842 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1843 if (err > 0)
1844 break;
1845 if (err == 0) {
1846 /* Don't loop endlessly; instead preserve legacy
1847 behaviour of trying SSL_shutdown() only twice.
1848 This looks necessary for OpenSSL < 0.9.8m */
1849 if (++zeros > 1)
1850 break;
1851 /* Shutdown was sent, now try receiving */
1852 self->shutdown_seen_zero = 1;
1853 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001854 }
1855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 /* Possibly retry shutdown until timeout or failure */
1857 ssl_err = SSL_get_error(self->ssl, err);
1858 if (ssl_err == SSL_ERROR_WANT_READ)
1859 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1860 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1861 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1862 else
1863 break;
1864 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1865 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001866 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 "The read operation timed out");
1868 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001869 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001871 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 }
1873 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1874 PyErr_SetString(PySSLErrorObject,
1875 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001876 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 }
1878 else if (sockstate != SOCKET_OPERATION_OK)
1879 /* Retain the SSL error code */
1880 break;
1881 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001882
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001883 if (err < 0) {
1884 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001887 else
1888 /* It's already INCREF'ed */
1889 return (PyObject *) sock;
1890
1891error:
1892 Py_DECREF(sock);
1893 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001894}
1895
1896PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1897"shutdown(s) -> socket\n\
1898\n\
1899Does the SSL shutdown handshake with the remote end, and returns\n\
1900the underlying socket object.");
1901
Antoine Pitroud6494802011-07-21 01:11:30 +02001902#if HAVE_OPENSSL_FINISHED
1903static PyObject *
1904PySSL_tls_unique_cb(PySSLSocket *self)
1905{
1906 PyObject *retval = NULL;
1907 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001908 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001909
1910 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1911 /* if session is resumed XOR we are the client */
1912 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1913 }
1914 else {
1915 /* if a new session XOR we are the server */
1916 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1917 }
1918
1919 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001920 if (len == 0)
1921 Py_RETURN_NONE;
1922
1923 retval = PyBytes_FromStringAndSize(buf, len);
1924
1925 return retval;
1926}
1927
1928PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1929"tls_unique_cb() -> bytes\n\
1930\n\
1931Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1932\n\
1933If the TLS handshake is not yet complete, None is returned");
1934
1935#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001936
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001937static PyGetSetDef ssl_getsetlist[] = {
1938 {"context", (getter) PySSL_get_context,
1939 (setter) PySSL_set_context, PySSL_set_context_doc},
1940 {NULL}, /* sentinel */
1941};
1942
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001943static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1945 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1946 PySSL_SSLwrite_doc},
1947 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1948 PySSL_SSLread_doc},
1949 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1950 PySSL_SSLpending_doc},
1951 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1952 PySSL_peercert_doc},
1953 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02001954 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001955#ifdef OPENSSL_NPN_NEGOTIATED
1956 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1957#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001958 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1960 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001961#if HAVE_OPENSSL_FINISHED
1962 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1963 PySSL_tls_unique_cb_doc},
1964#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001966};
1967
Antoine Pitrou152efa22010-05-16 18:19:27 +00001968static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001970 "_ssl._SSLSocket", /*tp_name*/
1971 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 0, /*tp_itemsize*/
1973 /* methods */
1974 (destructor)PySSL_dealloc, /*tp_dealloc*/
1975 0, /*tp_print*/
1976 0, /*tp_getattr*/
1977 0, /*tp_setattr*/
1978 0, /*tp_reserved*/
1979 0, /*tp_repr*/
1980 0, /*tp_as_number*/
1981 0, /*tp_as_sequence*/
1982 0, /*tp_as_mapping*/
1983 0, /*tp_hash*/
1984 0, /*tp_call*/
1985 0, /*tp_str*/
1986 0, /*tp_getattro*/
1987 0, /*tp_setattro*/
1988 0, /*tp_as_buffer*/
1989 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1990 0, /*tp_doc*/
1991 0, /*tp_traverse*/
1992 0, /*tp_clear*/
1993 0, /*tp_richcompare*/
1994 0, /*tp_weaklistoffset*/
1995 0, /*tp_iter*/
1996 0, /*tp_iternext*/
1997 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001998 0, /*tp_members*/
1999 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002000};
2001
Antoine Pitrou152efa22010-05-16 18:19:27 +00002002
2003/*
2004 * _SSLContext objects
2005 */
2006
2007static PyObject *
2008context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2009{
2010 char *kwlist[] = {"protocol", NULL};
2011 PySSLContext *self;
2012 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002013 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002014 SSL_CTX *ctx = NULL;
2015
2016 if (!PyArg_ParseTupleAndKeywords(
2017 args, kwds, "i:_SSLContext", kwlist,
2018 &proto_version))
2019 return NULL;
2020
2021 PySSL_BEGIN_ALLOW_THREADS
2022 if (proto_version == PY_SSL_VERSION_TLS1)
2023 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002024#if HAVE_TLSv1_2
2025 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2026 ctx = SSL_CTX_new(TLSv1_1_method());
2027 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2028 ctx = SSL_CTX_new(TLSv1_2_method());
2029#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002030 else if (proto_version == PY_SSL_VERSION_SSL3)
2031 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002032#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002033 else if (proto_version == PY_SSL_VERSION_SSL2)
2034 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002035#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002036 else if (proto_version == PY_SSL_VERSION_SSL23)
2037 ctx = SSL_CTX_new(SSLv23_method());
2038 else
2039 proto_version = -1;
2040 PySSL_END_ALLOW_THREADS
2041
2042 if (proto_version == -1) {
2043 PyErr_SetString(PyExc_ValueError,
2044 "invalid protocol version");
2045 return NULL;
2046 }
2047 if (ctx == NULL) {
2048 PyErr_SetString(PySSLErrorObject,
2049 "failed to allocate SSL context");
2050 return NULL;
2051 }
2052
2053 assert(type != NULL && type->tp_alloc != NULL);
2054 self = (PySSLContext *) type->tp_alloc(type, 0);
2055 if (self == NULL) {
2056 SSL_CTX_free(ctx);
2057 return NULL;
2058 }
2059 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002060#ifdef OPENSSL_NPN_NEGOTIATED
2061 self->npn_protocols = NULL;
2062#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002063#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002064 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002065#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002066 /* Don't check host name by default */
2067 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002068 /* Defaults */
2069 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002070 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2071 if (proto_version != PY_SSL_VERSION_SSL2)
2072 options |= SSL_OP_NO_SSLv2;
2073 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002074
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002075#ifndef OPENSSL_NO_ECDH
2076 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2077 prime256v1 by default. This is Apache mod_ssl's initialization
2078 policy, so we should be safe. */
2079#if defined(SSL_CTX_set_ecdh_auto)
2080 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2081#else
2082 {
2083 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2084 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2085 EC_KEY_free(key);
2086 }
2087#endif
2088#endif
2089
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002090#define SID_CTX "Python"
2091 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2092 sizeof(SID_CTX));
2093#undef SID_CTX
2094
Antoine Pitrou152efa22010-05-16 18:19:27 +00002095 return (PyObject *)self;
2096}
2097
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002098static int
2099context_traverse(PySSLContext *self, visitproc visit, void *arg)
2100{
2101#ifndef OPENSSL_NO_TLSEXT
2102 Py_VISIT(self->set_hostname);
2103#endif
2104 return 0;
2105}
2106
2107static int
2108context_clear(PySSLContext *self)
2109{
2110#ifndef OPENSSL_NO_TLSEXT
2111 Py_CLEAR(self->set_hostname);
2112#endif
2113 return 0;
2114}
2115
Antoine Pitrou152efa22010-05-16 18:19:27 +00002116static void
2117context_dealloc(PySSLContext *self)
2118{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002119 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002120 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002121#ifdef OPENSSL_NPN_NEGOTIATED
2122 PyMem_Free(self->npn_protocols);
2123#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124 Py_TYPE(self)->tp_free(self);
2125}
2126
2127static PyObject *
2128set_ciphers(PySSLContext *self, PyObject *args)
2129{
2130 int ret;
2131 const char *cipherlist;
2132
2133 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2134 return NULL;
2135 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2136 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002137 /* Clearing the error queue is necessary on some OpenSSL versions,
2138 otherwise the error will be reported again when another SSL call
2139 is done. */
2140 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002141 PyErr_SetString(PySSLErrorObject,
2142 "No cipher can be selected.");
2143 return NULL;
2144 }
2145 Py_RETURN_NONE;
2146}
2147
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002148#ifdef OPENSSL_NPN_NEGOTIATED
2149/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2150static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002151_advertiseNPN_cb(SSL *s,
2152 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002153 void *args)
2154{
2155 PySSLContext *ssl_ctx = (PySSLContext *) args;
2156
2157 if (ssl_ctx->npn_protocols == NULL) {
2158 *data = (unsigned char *) "";
2159 *len = 0;
2160 } else {
2161 *data = (unsigned char *) ssl_ctx->npn_protocols;
2162 *len = ssl_ctx->npn_protocols_len;
2163 }
2164
2165 return SSL_TLSEXT_ERR_OK;
2166}
2167/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2168static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002169_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002170 unsigned char **out, unsigned char *outlen,
2171 const unsigned char *server, unsigned int server_len,
2172 void *args)
2173{
2174 PySSLContext *ssl_ctx = (PySSLContext *) args;
2175
2176 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2177 int client_len;
2178
2179 if (client == NULL) {
2180 client = (unsigned char *) "";
2181 client_len = 0;
2182 } else {
2183 client_len = ssl_ctx->npn_protocols_len;
2184 }
2185
2186 SSL_select_next_proto(out, outlen,
2187 server, server_len,
2188 client, client_len);
2189
2190 return SSL_TLSEXT_ERR_OK;
2191}
2192#endif
2193
2194static PyObject *
2195_set_npn_protocols(PySSLContext *self, PyObject *args)
2196{
2197#ifdef OPENSSL_NPN_NEGOTIATED
2198 Py_buffer protos;
2199
2200 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2201 return NULL;
2202
Christian Heimes5cb31c92012-09-20 12:42:54 +02002203 if (self->npn_protocols != NULL) {
2204 PyMem_Free(self->npn_protocols);
2205 }
2206
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002207 self->npn_protocols = PyMem_Malloc(protos.len);
2208 if (self->npn_protocols == NULL) {
2209 PyBuffer_Release(&protos);
2210 return PyErr_NoMemory();
2211 }
2212 memcpy(self->npn_protocols, protos.buf, protos.len);
2213 self->npn_protocols_len = (int) protos.len;
2214
2215 /* set both server and client callbacks, because the context can
2216 * be used to create both types of sockets */
2217 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2218 _advertiseNPN_cb,
2219 self);
2220 SSL_CTX_set_next_proto_select_cb(self->ctx,
2221 _selectNPN_cb,
2222 self);
2223
2224 PyBuffer_Release(&protos);
2225 Py_RETURN_NONE;
2226#else
2227 PyErr_SetString(PyExc_NotImplementedError,
2228 "The NPN extension requires OpenSSL 1.0.1 or later.");
2229 return NULL;
2230#endif
2231}
2232
Antoine Pitrou152efa22010-05-16 18:19:27 +00002233static PyObject *
2234get_verify_mode(PySSLContext *self, void *c)
2235{
2236 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2237 case SSL_VERIFY_NONE:
2238 return PyLong_FromLong(PY_SSL_CERT_NONE);
2239 case SSL_VERIFY_PEER:
2240 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2241 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2242 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2243 }
2244 PyErr_SetString(PySSLErrorObject,
2245 "invalid return value from SSL_CTX_get_verify_mode");
2246 return NULL;
2247}
2248
2249static int
2250set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2251{
2252 int n, mode;
2253 if (!PyArg_Parse(arg, "i", &n))
2254 return -1;
2255 if (n == PY_SSL_CERT_NONE)
2256 mode = SSL_VERIFY_NONE;
2257 else if (n == PY_SSL_CERT_OPTIONAL)
2258 mode = SSL_VERIFY_PEER;
2259 else if (n == PY_SSL_CERT_REQUIRED)
2260 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2261 else {
2262 PyErr_SetString(PyExc_ValueError,
2263 "invalid value for verify_mode");
2264 return -1;
2265 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002266 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2267 PyErr_SetString(PyExc_ValueError,
2268 "Cannot set verify_mode to CERT_NONE when "
2269 "check_hostname is enabled.");
2270 return -1;
2271 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002272 SSL_CTX_set_verify(self->ctx, mode, NULL);
2273 return 0;
2274}
2275
Christian Heimes2427b502013-11-23 11:24:32 +01002276#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002277static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002278get_verify_flags(PySSLContext *self, void *c)
2279{
2280 X509_STORE *store;
2281 unsigned long flags;
2282
2283 store = SSL_CTX_get_cert_store(self->ctx);
2284 flags = X509_VERIFY_PARAM_get_flags(store->param);
2285 return PyLong_FromUnsignedLong(flags);
2286}
2287
2288static int
2289set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2290{
2291 X509_STORE *store;
2292 unsigned long new_flags, flags, set, clear;
2293
2294 if (!PyArg_Parse(arg, "k", &new_flags))
2295 return -1;
2296 store = SSL_CTX_get_cert_store(self->ctx);
2297 flags = X509_VERIFY_PARAM_get_flags(store->param);
2298 clear = flags & ~new_flags;
2299 set = ~flags & new_flags;
2300 if (clear) {
2301 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2302 _setSSLError(NULL, 0, __FILE__, __LINE__);
2303 return -1;
2304 }
2305 }
2306 if (set) {
2307 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2308 _setSSLError(NULL, 0, __FILE__, __LINE__);
2309 return -1;
2310 }
2311 }
2312 return 0;
2313}
Christian Heimes2427b502013-11-23 11:24:32 +01002314#endif
Christian Heimes22587792013-11-21 23:56:13 +01002315
2316static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002317get_options(PySSLContext *self, void *c)
2318{
2319 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2320}
2321
2322static int
2323set_options(PySSLContext *self, PyObject *arg, void *c)
2324{
2325 long new_opts, opts, set, clear;
2326 if (!PyArg_Parse(arg, "l", &new_opts))
2327 return -1;
2328 opts = SSL_CTX_get_options(self->ctx);
2329 clear = opts & ~new_opts;
2330 set = ~opts & new_opts;
2331 if (clear) {
2332#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2333 SSL_CTX_clear_options(self->ctx, clear);
2334#else
2335 PyErr_SetString(PyExc_ValueError,
2336 "can't clear options before OpenSSL 0.9.8m");
2337 return -1;
2338#endif
2339 }
2340 if (set)
2341 SSL_CTX_set_options(self->ctx, set);
2342 return 0;
2343}
2344
Christian Heimes1aa9a752013-12-02 02:41:19 +01002345static PyObject *
2346get_check_hostname(PySSLContext *self, void *c)
2347{
2348 return PyBool_FromLong(self->check_hostname);
2349}
2350
2351static int
2352set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2353{
2354 int check_hostname;
2355 if (!PyArg_Parse(arg, "p", &check_hostname))
2356 return -1;
2357 if (check_hostname &&
2358 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2359 PyErr_SetString(PyExc_ValueError,
2360 "check_hostname needs a SSL context with either "
2361 "CERT_OPTIONAL or CERT_REQUIRED");
2362 return -1;
2363 }
2364 self->check_hostname = check_hostname;
2365 return 0;
2366}
2367
2368
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002369typedef struct {
2370 PyThreadState *thread_state;
2371 PyObject *callable;
2372 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002373 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002374 int error;
2375} _PySSLPasswordInfo;
2376
2377static int
2378_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2379 const char *bad_type_error)
2380{
2381 /* Set the password and size fields of a _PySSLPasswordInfo struct
2382 from a unicode, bytes, or byte array object.
2383 The password field will be dynamically allocated and must be freed
2384 by the caller */
2385 PyObject *password_bytes = NULL;
2386 const char *data = NULL;
2387 Py_ssize_t size;
2388
2389 if (PyUnicode_Check(password)) {
2390 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2391 if (!password_bytes) {
2392 goto error;
2393 }
2394 data = PyBytes_AS_STRING(password_bytes);
2395 size = PyBytes_GET_SIZE(password_bytes);
2396 } else if (PyBytes_Check(password)) {
2397 data = PyBytes_AS_STRING(password);
2398 size = PyBytes_GET_SIZE(password);
2399 } else if (PyByteArray_Check(password)) {
2400 data = PyByteArray_AS_STRING(password);
2401 size = PyByteArray_GET_SIZE(password);
2402 } else {
2403 PyErr_SetString(PyExc_TypeError, bad_type_error);
2404 goto error;
2405 }
2406
Victor Stinner9ee02032013-06-23 15:08:23 +02002407 if (size > (Py_ssize_t)INT_MAX) {
2408 PyErr_Format(PyExc_ValueError,
2409 "password cannot be longer than %d bytes", INT_MAX);
2410 goto error;
2411 }
2412
Victor Stinner11ebff22013-07-07 17:07:52 +02002413 PyMem_Free(pw_info->password);
2414 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002415 if (!pw_info->password) {
2416 PyErr_SetString(PyExc_MemoryError,
2417 "unable to allocate password buffer");
2418 goto error;
2419 }
2420 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002421 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002422
2423 Py_XDECREF(password_bytes);
2424 return 1;
2425
2426error:
2427 Py_XDECREF(password_bytes);
2428 return 0;
2429}
2430
2431static int
2432_password_callback(char *buf, int size, int rwflag, void *userdata)
2433{
2434 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2435 PyObject *fn_ret = NULL;
2436
2437 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2438
2439 if (pw_info->callable) {
2440 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2441 if (!fn_ret) {
2442 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2443 core python API, so we could use it to add a frame here */
2444 goto error;
2445 }
2446
2447 if (!_pwinfo_set(pw_info, fn_ret,
2448 "password callback must return a string")) {
2449 goto error;
2450 }
2451 Py_CLEAR(fn_ret);
2452 }
2453
2454 if (pw_info->size > size) {
2455 PyErr_Format(PyExc_ValueError,
2456 "password cannot be longer than %d bytes", size);
2457 goto error;
2458 }
2459
2460 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2461 memcpy(buf, pw_info->password, pw_info->size);
2462 return pw_info->size;
2463
2464error:
2465 Py_XDECREF(fn_ret);
2466 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2467 pw_info->error = 1;
2468 return -1;
2469}
2470
Antoine Pitroub5218772010-05-21 09:56:06 +00002471static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002472load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2473{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002474 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2475 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002476 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002477 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2478 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2479 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002480 int r;
2481
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002482 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002483 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002484 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002485 "O|OO:load_cert_chain", kwlist,
2486 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002487 return NULL;
2488 if (keyfile == Py_None)
2489 keyfile = NULL;
2490 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2491 PyErr_SetString(PyExc_TypeError,
2492 "certfile should be a valid filesystem path");
2493 return NULL;
2494 }
2495 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2496 PyErr_SetString(PyExc_TypeError,
2497 "keyfile should be a valid filesystem path");
2498 goto error;
2499 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002500 if (password && password != Py_None) {
2501 if (PyCallable_Check(password)) {
2502 pw_info.callable = password;
2503 } else if (!_pwinfo_set(&pw_info, password,
2504 "password should be a string or callable")) {
2505 goto error;
2506 }
2507 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2508 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2509 }
2510 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002511 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2512 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002513 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002514 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002515 if (pw_info.error) {
2516 ERR_clear_error();
2517 /* the password callback has already set the error information */
2518 }
2519 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002520 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002521 PyErr_SetFromErrno(PyExc_IOError);
2522 }
2523 else {
2524 _setSSLError(NULL, 0, __FILE__, __LINE__);
2525 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002526 goto error;
2527 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002528 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002529 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002530 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2531 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002532 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2533 Py_CLEAR(keyfile_bytes);
2534 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002535 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002536 if (pw_info.error) {
2537 ERR_clear_error();
2538 /* the password callback has already set the error information */
2539 }
2540 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002541 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002542 PyErr_SetFromErrno(PyExc_IOError);
2543 }
2544 else {
2545 _setSSLError(NULL, 0, __FILE__, __LINE__);
2546 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002547 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002548 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002549 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002550 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002551 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002552 if (r != 1) {
2553 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002554 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002555 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002556 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2557 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002558 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002559 Py_RETURN_NONE;
2560
2561error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002562 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2563 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002564 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002565 Py_XDECREF(keyfile_bytes);
2566 Py_XDECREF(certfile_bytes);
2567 return NULL;
2568}
2569
Christian Heimesefff7062013-11-21 03:35:02 +01002570/* internal helper function, returns -1 on error
2571 */
2572static int
2573_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2574 int filetype)
2575{
2576 BIO *biobuf = NULL;
2577 X509_STORE *store;
2578 int retval = 0, err, loaded = 0;
2579
2580 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2581
2582 if (len <= 0) {
2583 PyErr_SetString(PyExc_ValueError,
2584 "Empty certificate data");
2585 return -1;
2586 } else if (len > INT_MAX) {
2587 PyErr_SetString(PyExc_OverflowError,
2588 "Certificate data is too long.");
2589 return -1;
2590 }
2591
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002592 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002593 if (biobuf == NULL) {
2594 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2595 return -1;
2596 }
2597
2598 store = SSL_CTX_get_cert_store(self->ctx);
2599 assert(store != NULL);
2600
2601 while (1) {
2602 X509 *cert = NULL;
2603 int r;
2604
2605 if (filetype == SSL_FILETYPE_ASN1) {
2606 cert = d2i_X509_bio(biobuf, NULL);
2607 } else {
2608 cert = PEM_read_bio_X509(biobuf, NULL,
2609 self->ctx->default_passwd_callback,
2610 self->ctx->default_passwd_callback_userdata);
2611 }
2612 if (cert == NULL) {
2613 break;
2614 }
2615 r = X509_STORE_add_cert(store, cert);
2616 X509_free(cert);
2617 if (!r) {
2618 err = ERR_peek_last_error();
2619 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2620 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2621 /* cert already in hash table, not an error */
2622 ERR_clear_error();
2623 } else {
2624 break;
2625 }
2626 }
2627 loaded++;
2628 }
2629
2630 err = ERR_peek_last_error();
2631 if ((filetype == SSL_FILETYPE_ASN1) &&
2632 (loaded > 0) &&
2633 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2634 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2635 /* EOF ASN1 file, not an error */
2636 ERR_clear_error();
2637 retval = 0;
2638 } else if ((filetype == SSL_FILETYPE_PEM) &&
2639 (loaded > 0) &&
2640 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2641 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2642 /* EOF PEM file, not an error */
2643 ERR_clear_error();
2644 retval = 0;
2645 } else {
2646 _setSSLError(NULL, 0, __FILE__, __LINE__);
2647 retval = -1;
2648 }
2649
2650 BIO_free(biobuf);
2651 return retval;
2652}
2653
2654
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655static PyObject *
2656load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2657{
Christian Heimesefff7062013-11-21 03:35:02 +01002658 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2659 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002660 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2661 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002662 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002663
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002664 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002665 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002666 "|OOO:load_verify_locations", kwlist,
2667 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002669
Antoine Pitrou152efa22010-05-16 18:19:27 +00002670 if (cafile == Py_None)
2671 cafile = NULL;
2672 if (capath == Py_None)
2673 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002674 if (cadata == Py_None)
2675 cadata = NULL;
2676
2677 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002678 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002679 "cafile, capath and cadata cannot be all omitted");
2680 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002681 }
2682 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2683 PyErr_SetString(PyExc_TypeError,
2684 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002685 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002686 }
2687 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002688 PyErr_SetString(PyExc_TypeError,
2689 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002690 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002691 }
Christian Heimesefff7062013-11-21 03:35:02 +01002692
2693 /* validata cadata type and load cadata */
2694 if (cadata) {
2695 Py_buffer buf;
2696 PyObject *cadata_ascii = NULL;
2697
2698 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2699 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2700 PyBuffer_Release(&buf);
2701 PyErr_SetString(PyExc_TypeError,
2702 "cadata should be a contiguous buffer with "
2703 "a single dimension");
2704 goto error;
2705 }
2706 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2707 PyBuffer_Release(&buf);
2708 if (r == -1) {
2709 goto error;
2710 }
2711 } else {
2712 PyErr_Clear();
2713 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2714 if (cadata_ascii == NULL) {
2715 PyErr_SetString(PyExc_TypeError,
2716 "cadata should be a ASCII string or a "
2717 "bytes-like object");
2718 goto error;
2719 }
2720 r = _add_ca_certs(self,
2721 PyBytes_AS_STRING(cadata_ascii),
2722 PyBytes_GET_SIZE(cadata_ascii),
2723 SSL_FILETYPE_PEM);
2724 Py_DECREF(cadata_ascii);
2725 if (r == -1) {
2726 goto error;
2727 }
2728 }
2729 }
2730
2731 /* load cafile or capath */
2732 if (cafile || capath) {
2733 if (cafile)
2734 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2735 if (capath)
2736 capath_buf = PyBytes_AS_STRING(capath_bytes);
2737 PySSL_BEGIN_ALLOW_THREADS
2738 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2739 PySSL_END_ALLOW_THREADS
2740 if (r != 1) {
2741 ok = 0;
2742 if (errno != 0) {
2743 ERR_clear_error();
2744 PyErr_SetFromErrno(PyExc_IOError);
2745 }
2746 else {
2747 _setSSLError(NULL, 0, __FILE__, __LINE__);
2748 }
2749 goto error;
2750 }
2751 }
2752 goto end;
2753
2754 error:
2755 ok = 0;
2756 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 Py_XDECREF(cafile_bytes);
2758 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002759 if (ok) {
2760 Py_RETURN_NONE;
2761 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762 return NULL;
2763 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002764}
2765
2766static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002767load_dh_params(PySSLContext *self, PyObject *filepath)
2768{
2769 FILE *f;
2770 DH *dh;
2771
Victor Stinnerdaf45552013-08-28 00:53:59 +02002772 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002773 if (f == NULL) {
2774 if (!PyErr_Occurred())
2775 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2776 return NULL;
2777 }
2778 errno = 0;
2779 PySSL_BEGIN_ALLOW_THREADS
2780 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002781 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002782 PySSL_END_ALLOW_THREADS
2783 if (dh == NULL) {
2784 if (errno != 0) {
2785 ERR_clear_error();
2786 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2787 }
2788 else {
2789 _setSSLError(NULL, 0, __FILE__, __LINE__);
2790 }
2791 return NULL;
2792 }
2793 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2794 _setSSLError(NULL, 0, __FILE__, __LINE__);
2795 DH_free(dh);
2796 Py_RETURN_NONE;
2797}
2798
2799static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2801{
Antoine Pitroud5323212010-10-22 18:19:07 +00002802 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002803 PySocketSockObject *sock;
2804 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002805 char *hostname = NULL;
2806 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807
Antoine Pitroud5323212010-10-22 18:19:07 +00002808 /* server_hostname is either None (or absent), or to be encoded
2809 using the idna encoding. */
2810 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002811 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002812 &sock, &server_side,
2813 Py_TYPE(Py_None), &hostname_obj)) {
2814 PyErr_Clear();
2815 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2816 PySocketModule.Sock_Type,
2817 &sock, &server_side,
2818 "idna", &hostname))
2819 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002820#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002821 PyMem_Free(hostname);
2822 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2823 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002824 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002825#endif
2826 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002828 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002829 hostname);
2830 if (hostname != NULL)
2831 PyMem_Free(hostname);
2832 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002833}
2834
Antoine Pitroub0182c82010-10-12 20:09:02 +00002835static PyObject *
2836session_stats(PySSLContext *self, PyObject *unused)
2837{
2838 int r;
2839 PyObject *value, *stats = PyDict_New();
2840 if (!stats)
2841 return NULL;
2842
2843#define ADD_STATS(SSL_NAME, KEY_NAME) \
2844 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2845 if (value == NULL) \
2846 goto error; \
2847 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2848 Py_DECREF(value); \
2849 if (r < 0) \
2850 goto error;
2851
2852 ADD_STATS(number, "number");
2853 ADD_STATS(connect, "connect");
2854 ADD_STATS(connect_good, "connect_good");
2855 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2856 ADD_STATS(accept, "accept");
2857 ADD_STATS(accept_good, "accept_good");
2858 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2859 ADD_STATS(accept, "accept");
2860 ADD_STATS(hits, "hits");
2861 ADD_STATS(misses, "misses");
2862 ADD_STATS(timeouts, "timeouts");
2863 ADD_STATS(cache_full, "cache_full");
2864
2865#undef ADD_STATS
2866
2867 return stats;
2868
2869error:
2870 Py_DECREF(stats);
2871 return NULL;
2872}
2873
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002874static PyObject *
2875set_default_verify_paths(PySSLContext *self, PyObject *unused)
2876{
2877 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2878 _setSSLError(NULL, 0, __FILE__, __LINE__);
2879 return NULL;
2880 }
2881 Py_RETURN_NONE;
2882}
2883
Antoine Pitrou501da612011-12-21 09:27:41 +01002884#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002885static PyObject *
2886set_ecdh_curve(PySSLContext *self, PyObject *name)
2887{
2888 PyObject *name_bytes;
2889 int nid;
2890 EC_KEY *key;
2891
2892 if (!PyUnicode_FSConverter(name, &name_bytes))
2893 return NULL;
2894 assert(PyBytes_Check(name_bytes));
2895 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2896 Py_DECREF(name_bytes);
2897 if (nid == 0) {
2898 PyErr_Format(PyExc_ValueError,
2899 "unknown elliptic curve name %R", name);
2900 return NULL;
2901 }
2902 key = EC_KEY_new_by_curve_name(nid);
2903 if (key == NULL) {
2904 _setSSLError(NULL, 0, __FILE__, __LINE__);
2905 return NULL;
2906 }
2907 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2908 EC_KEY_free(key);
2909 Py_RETURN_NONE;
2910}
Antoine Pitrou501da612011-12-21 09:27:41 +01002911#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002912
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002913#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002914static int
2915_servername_callback(SSL *s, int *al, void *args)
2916{
2917 int ret;
2918 PySSLContext *ssl_ctx = (PySSLContext *) args;
2919 PySSLSocket *ssl;
2920 PyObject *servername_o;
2921 PyObject *servername_idna;
2922 PyObject *result;
2923 /* The high-level ssl.SSLSocket object */
2924 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002925 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002926#ifdef WITH_THREAD
2927 PyGILState_STATE gstate = PyGILState_Ensure();
2928#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002929
2930 if (ssl_ctx->set_hostname == NULL) {
2931 /* remove race condition in this the call back while if removing the
2932 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002933#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002934 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002935#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002936 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002937 }
2938
2939 ssl = SSL_get_app_data(s);
2940 assert(PySSLSocket_Check(ssl));
2941 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2942 Py_INCREF(ssl_socket);
2943 if (ssl_socket == Py_None) {
2944 goto error;
2945 }
Victor Stinner7e001512013-06-25 00:44:31 +02002946
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002947 if (servername == NULL) {
2948 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2949 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002950 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002951 else {
2952 servername_o = PyBytes_FromString(servername);
2953 if (servername_o == NULL) {
2954 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2955 goto error;
2956 }
2957 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2958 if (servername_idna == NULL) {
2959 PyErr_WriteUnraisable(servername_o);
2960 Py_DECREF(servername_o);
2961 goto error;
2962 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002963 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002964 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2965 servername_idna, ssl_ctx, NULL);
2966 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002967 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002968 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002969
2970 if (result == NULL) {
2971 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2972 *al = SSL_AD_HANDSHAKE_FAILURE;
2973 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2974 }
2975 else {
2976 if (result != Py_None) {
2977 *al = (int) PyLong_AsLong(result);
2978 if (PyErr_Occurred()) {
2979 PyErr_WriteUnraisable(result);
2980 *al = SSL_AD_INTERNAL_ERROR;
2981 }
2982 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2983 }
2984 else {
2985 ret = SSL_TLSEXT_ERR_OK;
2986 }
2987 Py_DECREF(result);
2988 }
2989
Stefan Krah20d60802013-01-17 17:07:17 +01002990#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002991 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002992#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002993 return ret;
2994
2995error:
2996 Py_DECREF(ssl_socket);
2997 *al = SSL_AD_INTERNAL_ERROR;
2998 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002999#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003000 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003001#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003002 return ret;
3003}
Antoine Pitroua5963382013-03-30 16:39:00 +01003004#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003005
3006PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3007"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003008\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003009This sets a callback that will be called when a server name is provided by\n\
3010the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003011\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003012If the argument is None then the callback is disabled. The method is called\n\
3013with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003014See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003015
3016static PyObject *
3017set_servername_callback(PySSLContext *self, PyObject *args)
3018{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003019#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003020 PyObject *cb;
3021
3022 if (!PyArg_ParseTuple(args, "O", &cb))
3023 return NULL;
3024
3025 Py_CLEAR(self->set_hostname);
3026 if (cb == Py_None) {
3027 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3028 }
3029 else {
3030 if (!PyCallable_Check(cb)) {
3031 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3032 PyErr_SetString(PyExc_TypeError,
3033 "not a callable object");
3034 return NULL;
3035 }
3036 Py_INCREF(cb);
3037 self->set_hostname = cb;
3038 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3039 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3040 }
3041 Py_RETURN_NONE;
3042#else
3043 PyErr_SetString(PyExc_NotImplementedError,
3044 "The TLS extension servername callback, "
3045 "SSL_CTX_set_tlsext_servername_callback, "
3046 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003047 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003048#endif
3049}
3050
Christian Heimes9a5395a2013-06-17 15:44:12 +02003051PyDoc_STRVAR(PySSL_get_stats_doc,
3052"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3053\n\
3054Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3055CA extension and certificate revocation lists inside the context's cert\n\
3056store.\n\
3057NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3058been used at least once.");
3059
3060static PyObject *
3061cert_store_stats(PySSLContext *self)
3062{
3063 X509_STORE *store;
3064 X509_OBJECT *obj;
3065 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3066
3067 store = SSL_CTX_get_cert_store(self->ctx);
3068 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3069 obj = sk_X509_OBJECT_value(store->objs, i);
3070 switch (obj->type) {
3071 case X509_LU_X509:
3072 x509++;
3073 if (X509_check_ca(obj->data.x509)) {
3074 ca++;
3075 }
3076 break;
3077 case X509_LU_CRL:
3078 crl++;
3079 break;
3080 case X509_LU_PKEY:
3081 pkey++;
3082 break;
3083 default:
3084 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3085 * As far as I can tell they are internal states and never
3086 * stored in a cert store */
3087 break;
3088 }
3089 }
3090 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3091 "x509_ca", ca);
3092}
3093
3094PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003095"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003096\n\
3097Returns a list of dicts with information of loaded CA certs. If the\n\
3098optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3099NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3100been used at least once.");
3101
3102static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003103get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003104{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003105 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003106 X509_STORE *store;
3107 PyObject *ci = NULL, *rlist = NULL;
3108 int i;
3109 int binary_mode = 0;
3110
Christian Heimesf22e8e52013-11-22 02:22:51 +01003111 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3112 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003113 return NULL;
3114 }
3115
3116 if ((rlist = PyList_New(0)) == NULL) {
3117 return NULL;
3118 }
3119
3120 store = SSL_CTX_get_cert_store(self->ctx);
3121 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3122 X509_OBJECT *obj;
3123 X509 *cert;
3124
3125 obj = sk_X509_OBJECT_value(store->objs, i);
3126 if (obj->type != X509_LU_X509) {
3127 /* not a x509 cert */
3128 continue;
3129 }
3130 /* CA for any purpose */
3131 cert = obj->data.x509;
3132 if (!X509_check_ca(cert)) {
3133 continue;
3134 }
3135 if (binary_mode) {
3136 ci = _certificate_to_der(cert);
3137 } else {
3138 ci = _decode_certificate(cert);
3139 }
3140 if (ci == NULL) {
3141 goto error;
3142 }
3143 if (PyList_Append(rlist, ci) == -1) {
3144 goto error;
3145 }
3146 Py_CLEAR(ci);
3147 }
3148 return rlist;
3149
3150 error:
3151 Py_XDECREF(ci);
3152 Py_XDECREF(rlist);
3153 return NULL;
3154}
3155
3156
Antoine Pitrou152efa22010-05-16 18:19:27 +00003157static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003158 {"check_hostname", (getter) get_check_hostname,
3159 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003160 {"options", (getter) get_options,
3161 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003162#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003163 {"verify_flags", (getter) get_verify_flags,
3164 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003165#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003166 {"verify_mode", (getter) get_verify_mode,
3167 (setter) set_verify_mode, NULL},
3168 {NULL}, /* sentinel */
3169};
3170
3171static struct PyMethodDef context_methods[] = {
3172 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3173 METH_VARARGS | METH_KEYWORDS, NULL},
3174 {"set_ciphers", (PyCFunction) set_ciphers,
3175 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003176 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3177 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003178 {"load_cert_chain", (PyCFunction) load_cert_chain,
3179 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003180 {"load_dh_params", (PyCFunction) load_dh_params,
3181 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003182 {"load_verify_locations", (PyCFunction) load_verify_locations,
3183 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003184 {"session_stats", (PyCFunction) session_stats,
3185 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003186 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3187 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003188#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003189 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3190 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003191#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003192 {"set_servername_callback", (PyCFunction) set_servername_callback,
3193 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003194 {"cert_store_stats", (PyCFunction) cert_store_stats,
3195 METH_NOARGS, PySSL_get_stats_doc},
3196 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003197 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003198 {NULL, NULL} /* sentinel */
3199};
3200
3201static PyTypeObject PySSLContext_Type = {
3202 PyVarObject_HEAD_INIT(NULL, 0)
3203 "_ssl._SSLContext", /*tp_name*/
3204 sizeof(PySSLContext), /*tp_basicsize*/
3205 0, /*tp_itemsize*/
3206 (destructor)context_dealloc, /*tp_dealloc*/
3207 0, /*tp_print*/
3208 0, /*tp_getattr*/
3209 0, /*tp_setattr*/
3210 0, /*tp_reserved*/
3211 0, /*tp_repr*/
3212 0, /*tp_as_number*/
3213 0, /*tp_as_sequence*/
3214 0, /*tp_as_mapping*/
3215 0, /*tp_hash*/
3216 0, /*tp_call*/
3217 0, /*tp_str*/
3218 0, /*tp_getattro*/
3219 0, /*tp_setattro*/
3220 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003221 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003222 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003223 (traverseproc) context_traverse, /*tp_traverse*/
3224 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003225 0, /*tp_richcompare*/
3226 0, /*tp_weaklistoffset*/
3227 0, /*tp_iter*/
3228 0, /*tp_iternext*/
3229 context_methods, /*tp_methods*/
3230 0, /*tp_members*/
3231 context_getsetlist, /*tp_getset*/
3232 0, /*tp_base*/
3233 0, /*tp_dict*/
3234 0, /*tp_descr_get*/
3235 0, /*tp_descr_set*/
3236 0, /*tp_dictoffset*/
3237 0, /*tp_init*/
3238 0, /*tp_alloc*/
3239 context_new, /*tp_new*/
3240};
3241
3242
3243
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003244#ifdef HAVE_OPENSSL_RAND
3245
3246/* helper routines for seeding the SSL PRNG */
3247static PyObject *
3248PySSL_RAND_add(PyObject *self, PyObject *args)
3249{
3250 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003251 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003252 double entropy;
3253
3254 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003255 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003256 do {
3257 written = Py_MIN(len, INT_MAX);
3258 RAND_add(buf, (int)written, entropy);
3259 buf += written;
3260 len -= written;
3261 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003262 Py_INCREF(Py_None);
3263 return Py_None;
3264}
3265
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003266PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003267"RAND_add(string, entropy)\n\
3268\n\
3269Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003270bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003271
3272static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003273PySSL_RAND(int len, int pseudo)
3274{
3275 int ok;
3276 PyObject *bytes;
3277 unsigned long err;
3278 const char *errstr;
3279 PyObject *v;
3280
Victor Stinner1e81a392013-12-19 16:47:04 +01003281 if (len < 0) {
3282 PyErr_SetString(PyExc_ValueError, "num must be positive");
3283 return NULL;
3284 }
3285
Victor Stinner99c8b162011-05-24 12:05:19 +02003286 bytes = PyBytes_FromStringAndSize(NULL, len);
3287 if (bytes == NULL)
3288 return NULL;
3289 if (pseudo) {
3290 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3291 if (ok == 0 || ok == 1)
3292 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3293 }
3294 else {
3295 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3296 if (ok == 1)
3297 return bytes;
3298 }
3299 Py_DECREF(bytes);
3300
3301 err = ERR_get_error();
3302 errstr = ERR_reason_error_string(err);
3303 v = Py_BuildValue("(ks)", err, errstr);
3304 if (v != NULL) {
3305 PyErr_SetObject(PySSLErrorObject, v);
3306 Py_DECREF(v);
3307 }
3308 return NULL;
3309}
3310
3311static PyObject *
3312PySSL_RAND_bytes(PyObject *self, PyObject *args)
3313{
3314 int len;
3315 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3316 return NULL;
3317 return PySSL_RAND(len, 0);
3318}
3319
3320PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3321"RAND_bytes(n) -> bytes\n\
3322\n\
3323Generate n cryptographically strong pseudo-random bytes.");
3324
3325static PyObject *
3326PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3327{
3328 int len;
3329 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3330 return NULL;
3331 return PySSL_RAND(len, 1);
3332}
3333
3334PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3335"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3336\n\
3337Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3338generated are cryptographically strong.");
3339
3340static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003341PySSL_RAND_status(PyObject *self)
3342{
Christian Heimes217cfd12007-12-02 14:31:20 +00003343 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003344}
3345
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003346PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003347"RAND_status() -> 0 or 1\n\
3348\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003349Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3350It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3351using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003352
3353static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003354PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003355{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003356 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003357 int bytes;
3358
Jesus Ceac8754a12012-09-11 02:00:58 +02003359 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003360 PyUnicode_FSConverter, &path))
3361 return NULL;
3362
3363 bytes = RAND_egd(PyBytes_AsString(path));
3364 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003365 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003366 PyErr_SetString(PySSLErrorObject,
3367 "EGD connection failed or EGD did not return "
3368 "enough data to seed the PRNG");
3369 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003370 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003371 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003372}
3373
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003374PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003375"RAND_egd(path) -> bytes\n\
3376\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003377Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3378Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003379fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003380
Christian Heimesf77b4b22013-08-21 13:26:05 +02003381#endif /* HAVE_OPENSSL_RAND */
3382
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003383
Christian Heimes6d7ad132013-06-09 18:02:55 +02003384PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3385"get_default_verify_paths() -> tuple\n\
3386\n\
3387Return search paths and environment vars that are used by SSLContext's\n\
3388set_default_verify_paths() to load default CAs. The values are\n\
3389'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3390
3391static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003392PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003393{
3394 PyObject *ofile_env = NULL;
3395 PyObject *ofile = NULL;
3396 PyObject *odir_env = NULL;
3397 PyObject *odir = NULL;
3398
3399#define convert(info, target) { \
3400 const char *tmp = (info); \
3401 target = NULL; \
3402 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3403 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3404 target = PyBytes_FromString(tmp); } \
3405 if (!target) goto error; \
3406 } while(0)
3407
3408 convert(X509_get_default_cert_file_env(), ofile_env);
3409 convert(X509_get_default_cert_file(), ofile);
3410 convert(X509_get_default_cert_dir_env(), odir_env);
3411 convert(X509_get_default_cert_dir(), odir);
3412#undef convert
3413
Christian Heimes200bb1b2013-06-14 15:14:29 +02003414 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003415
3416 error:
3417 Py_XDECREF(ofile_env);
3418 Py_XDECREF(ofile);
3419 Py_XDECREF(odir_env);
3420 Py_XDECREF(odir);
3421 return NULL;
3422}
3423
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003424static PyObject*
3425asn1obj2py(ASN1_OBJECT *obj)
3426{
3427 int nid;
3428 const char *ln, *sn;
3429 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003430 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003431
3432 nid = OBJ_obj2nid(obj);
3433 if (nid == NID_undef) {
3434 PyErr_Format(PyExc_ValueError, "Unknown object");
3435 return NULL;
3436 }
3437 sn = OBJ_nid2sn(nid);
3438 ln = OBJ_nid2ln(nid);
3439 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3440 if (buflen < 0) {
3441 _setSSLError(NULL, 0, __FILE__, __LINE__);
3442 return NULL;
3443 }
3444 if (buflen) {
3445 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3446 } else {
3447 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3448 }
3449}
3450
3451PyDoc_STRVAR(PySSL_txt2obj_doc,
3452"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3453\n\
3454Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3455objects are looked up by OID. With name=True short and long name are also\n\
3456matched.");
3457
3458static PyObject*
3459PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3460{
3461 char *kwlist[] = {"txt", "name", NULL};
3462 PyObject *result = NULL;
3463 char *txt;
3464 int name = 0;
3465 ASN1_OBJECT *obj;
3466
3467 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3468 kwlist, &txt, &name)) {
3469 return NULL;
3470 }
3471 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3472 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003473 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003474 return NULL;
3475 }
3476 result = asn1obj2py(obj);
3477 ASN1_OBJECT_free(obj);
3478 return result;
3479}
3480
3481PyDoc_STRVAR(PySSL_nid2obj_doc,
3482"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3483\n\
3484Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3485
3486static PyObject*
3487PySSL_nid2obj(PyObject *self, PyObject *args)
3488{
3489 PyObject *result = NULL;
3490 int nid;
3491 ASN1_OBJECT *obj;
3492
3493 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3494 return NULL;
3495 }
3496 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003497 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003498 return NULL;
3499 }
3500 obj = OBJ_nid2obj(nid);
3501 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003502 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003503 return NULL;
3504 }
3505 result = asn1obj2py(obj);
3506 ASN1_OBJECT_free(obj);
3507 return result;
3508}
3509
Christian Heimes46bebee2013-06-09 19:03:31 +02003510#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003511
3512static PyObject*
3513certEncodingType(DWORD encodingType)
3514{
3515 static PyObject *x509_asn = NULL;
3516 static PyObject *pkcs_7_asn = NULL;
3517
3518 if (x509_asn == NULL) {
3519 x509_asn = PyUnicode_InternFromString("x509_asn");
3520 if (x509_asn == NULL)
3521 return NULL;
3522 }
3523 if (pkcs_7_asn == NULL) {
3524 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3525 if (pkcs_7_asn == NULL)
3526 return NULL;
3527 }
3528 switch(encodingType) {
3529 case X509_ASN_ENCODING:
3530 Py_INCREF(x509_asn);
3531 return x509_asn;
3532 case PKCS_7_ASN_ENCODING:
3533 Py_INCREF(pkcs_7_asn);
3534 return pkcs_7_asn;
3535 default:
3536 return PyLong_FromLong(encodingType);
3537 }
3538}
3539
3540static PyObject*
3541parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3542{
3543 CERT_ENHKEY_USAGE *usage;
3544 DWORD size, error, i;
3545 PyObject *retval;
3546
3547 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3548 error = GetLastError();
3549 if (error == CRYPT_E_NOT_FOUND) {
3550 Py_RETURN_TRUE;
3551 }
3552 return PyErr_SetFromWindowsErr(error);
3553 }
3554
3555 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3556 if (usage == NULL) {
3557 return PyErr_NoMemory();
3558 }
3559
3560 /* Now get the actual enhanced usage property */
3561 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3562 PyMem_Free(usage);
3563 error = GetLastError();
3564 if (error == CRYPT_E_NOT_FOUND) {
3565 Py_RETURN_TRUE;
3566 }
3567 return PyErr_SetFromWindowsErr(error);
3568 }
3569 retval = PySet_New(NULL);
3570 if (retval == NULL) {
3571 goto error;
3572 }
3573 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3574 if (usage->rgpszUsageIdentifier[i]) {
3575 PyObject *oid;
3576 int err;
3577 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3578 if (oid == NULL) {
3579 Py_CLEAR(retval);
3580 goto error;
3581 }
3582 err = PySet_Add(retval, oid);
3583 Py_DECREF(oid);
3584 if (err == -1) {
3585 Py_CLEAR(retval);
3586 goto error;
3587 }
3588 }
3589 }
3590 error:
3591 PyMem_Free(usage);
3592 return retval;
3593}
3594
3595PyDoc_STRVAR(PySSL_enum_certificates_doc,
3596"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003597\n\
3598Retrieve certificates from Windows' cert store. store_name may be one of\n\
3599'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003600The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003601encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003602PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3603boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003604
Christian Heimes46bebee2013-06-09 19:03:31 +02003605static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003606PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003607{
Christian Heimes44109d72013-11-22 01:51:30 +01003608 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003609 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003610 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003611 PCCERT_CONTEXT pCertCtx = NULL;
3612 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003613 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003614
Christian Heimes44109d72013-11-22 01:51:30 +01003615 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3616 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003617 return NULL;
3618 }
Christian Heimes44109d72013-11-22 01:51:30 +01003619 result = PyList_New(0);
3620 if (result == NULL) {
3621 return NULL;
3622 }
3623 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3624 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003625 Py_DECREF(result);
3626 return PyErr_SetFromWindowsErr(GetLastError());
3627 }
3628
Christian Heimes44109d72013-11-22 01:51:30 +01003629 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3630 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3631 pCertCtx->cbCertEncoded);
3632 if (!cert) {
3633 Py_CLEAR(result);
3634 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003635 }
Christian Heimes44109d72013-11-22 01:51:30 +01003636 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3637 Py_CLEAR(result);
3638 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003639 }
Christian Heimes44109d72013-11-22 01:51:30 +01003640 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3641 if (keyusage == Py_True) {
3642 Py_DECREF(keyusage);
3643 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003644 }
Christian Heimes44109d72013-11-22 01:51:30 +01003645 if (keyusage == NULL) {
3646 Py_CLEAR(result);
3647 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003648 }
Christian Heimes44109d72013-11-22 01:51:30 +01003649 if ((tup = PyTuple_New(3)) == NULL) {
3650 Py_CLEAR(result);
3651 break;
3652 }
3653 PyTuple_SET_ITEM(tup, 0, cert);
3654 cert = NULL;
3655 PyTuple_SET_ITEM(tup, 1, enc);
3656 enc = NULL;
3657 PyTuple_SET_ITEM(tup, 2, keyusage);
3658 keyusage = NULL;
3659 if (PyList_Append(result, tup) < 0) {
3660 Py_CLEAR(result);
3661 break;
3662 }
3663 Py_CLEAR(tup);
3664 }
3665 if (pCertCtx) {
3666 /* loop ended with an error, need to clean up context manually */
3667 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003668 }
3669
3670 /* In error cases cert, enc and tup may not be NULL */
3671 Py_XDECREF(cert);
3672 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003673 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003674 Py_XDECREF(tup);
3675
3676 if (!CertCloseStore(hStore, 0)) {
3677 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003678 Py_XDECREF(result);
3679 return PyErr_SetFromWindowsErr(GetLastError());
3680 }
3681 return result;
3682}
3683
3684PyDoc_STRVAR(PySSL_enum_crls_doc,
3685"enum_crls(store_name) -> []\n\
3686\n\
3687Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3688'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3689The function returns a list of (bytes, encoding_type) tuples. The\n\
3690encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3691PKCS_7_ASN_ENCODING.");
3692
3693static PyObject *
3694PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3695{
3696 char *kwlist[] = {"store_name", NULL};
3697 char *store_name;
3698 HCERTSTORE hStore = NULL;
3699 PCCRL_CONTEXT pCrlCtx = NULL;
3700 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3701 PyObject *result = NULL;
3702
3703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3704 kwlist, &store_name)) {
3705 return NULL;
3706 }
3707 result = PyList_New(0);
3708 if (result == NULL) {
3709 return NULL;
3710 }
3711 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3712 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003713 Py_DECREF(result);
3714 return PyErr_SetFromWindowsErr(GetLastError());
3715 }
Christian Heimes44109d72013-11-22 01:51:30 +01003716
3717 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3718 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3719 pCrlCtx->cbCrlEncoded);
3720 if (!crl) {
3721 Py_CLEAR(result);
3722 break;
3723 }
3724 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3725 Py_CLEAR(result);
3726 break;
3727 }
3728 if ((tup = PyTuple_New(2)) == NULL) {
3729 Py_CLEAR(result);
3730 break;
3731 }
3732 PyTuple_SET_ITEM(tup, 0, crl);
3733 crl = NULL;
3734 PyTuple_SET_ITEM(tup, 1, enc);
3735 enc = NULL;
3736
3737 if (PyList_Append(result, tup) < 0) {
3738 Py_CLEAR(result);
3739 break;
3740 }
3741 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003742 }
Christian Heimes44109d72013-11-22 01:51:30 +01003743 if (pCrlCtx) {
3744 /* loop ended with an error, need to clean up context manually */
3745 CertFreeCRLContext(pCrlCtx);
3746 }
3747
3748 /* In error cases cert, enc and tup may not be NULL */
3749 Py_XDECREF(crl);
3750 Py_XDECREF(enc);
3751 Py_XDECREF(tup);
3752
3753 if (!CertCloseStore(hStore, 0)) {
3754 /* This error case might shadow another exception.*/
3755 Py_XDECREF(result);
3756 return PyErr_SetFromWindowsErr(GetLastError());
3757 }
3758 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003759}
Christian Heimes44109d72013-11-22 01:51:30 +01003760
3761#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003762
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003763/* List of functions exported by this module. */
3764
3765static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003766 {"_test_decode_cert", PySSL_test_decode_certificate,
3767 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003768#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003769 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3770 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003771 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3772 PySSL_RAND_bytes_doc},
3773 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3774 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003775 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003776 PySSL_RAND_egd_doc},
3777 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3778 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003779#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003780 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003781 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003782#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003783 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3784 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3785 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3786 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003787#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003788 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3789 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3790 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3791 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003792 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003793};
3794
3795
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003796#ifdef WITH_THREAD
3797
3798/* an implementation of OpenSSL threading operations in terms
3799 of the Python C thread library */
3800
3801static PyThread_type_lock *_ssl_locks = NULL;
3802
Christian Heimes4d98ca92013-08-19 17:36:29 +02003803#if OPENSSL_VERSION_NUMBER >= 0x10000000
3804/* use new CRYPTO_THREADID API. */
3805static void
3806_ssl_threadid_callback(CRYPTO_THREADID *id)
3807{
3808 CRYPTO_THREADID_set_numeric(id,
3809 (unsigned long)PyThread_get_thread_ident());
3810}
3811#else
3812/* deprecated CRYPTO_set_id_callback() API. */
3813static unsigned long
3814_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003815 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003817#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003818
Bill Janssen6e027db2007-11-15 22:23:56 +00003819static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003820 (int mode, int n, const char *file, int line) {
3821 /* this function is needed to perform locking on shared data
3822 structures. (Note that OpenSSL uses a number of global data
3823 structures that will be implicitly shared whenever multiple
3824 threads use OpenSSL.) Multi-threaded applications will
3825 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003827 locking_function() must be able to handle up to
3828 CRYPTO_num_locks() different mutex locks. It sets the n-th
3829 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003831 file and line are the file number of the function setting the
3832 lock. They can be useful for debugging.
3833 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003835 if ((_ssl_locks == NULL) ||
3836 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3837 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003839 if (mode & CRYPTO_LOCK) {
3840 PyThread_acquire_lock(_ssl_locks[n], 1);
3841 } else {
3842 PyThread_release_lock(_ssl_locks[n]);
3843 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003844}
3845
3846static int _setup_ssl_threads(void) {
3847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003848 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003850 if (_ssl_locks == NULL) {
3851 _ssl_locks_count = CRYPTO_num_locks();
3852 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003853 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003854 if (_ssl_locks == NULL)
3855 return 0;
3856 memset(_ssl_locks, 0,
3857 sizeof(PyThread_type_lock) * _ssl_locks_count);
3858 for (i = 0; i < _ssl_locks_count; i++) {
3859 _ssl_locks[i] = PyThread_allocate_lock();
3860 if (_ssl_locks[i] == NULL) {
3861 unsigned int j;
3862 for (j = 0; j < i; j++) {
3863 PyThread_free_lock(_ssl_locks[j]);
3864 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003865 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003866 return 0;
3867 }
3868 }
3869 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003870#if OPENSSL_VERSION_NUMBER >= 0x10000000
3871 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3872#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003873 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003874#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003875 }
3876 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003877}
3878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003879#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003881PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003882"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003883for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003884
Martin v. Löwis1a214512008-06-11 05:26:20 +00003885
3886static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003887 PyModuleDef_HEAD_INIT,
3888 "_ssl",
3889 module_doc,
3890 -1,
3891 PySSL_methods,
3892 NULL,
3893 NULL,
3894 NULL,
3895 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003896};
3897
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003898
3899static void
3900parse_openssl_version(unsigned long libver,
3901 unsigned int *major, unsigned int *minor,
3902 unsigned int *fix, unsigned int *patch,
3903 unsigned int *status)
3904{
3905 *status = libver & 0xF;
3906 libver >>= 4;
3907 *patch = libver & 0xFF;
3908 libver >>= 8;
3909 *fix = libver & 0xFF;
3910 libver >>= 8;
3911 *minor = libver & 0xFF;
3912 libver >>= 8;
3913 *major = libver & 0xFF;
3914}
3915
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003916PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003917PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003918{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003919 PyObject *m, *d, *r;
3920 unsigned long libver;
3921 unsigned int major, minor, fix, patch, status;
3922 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003923 struct py_ssl_error_code *errcode;
3924 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003925
Antoine Pitrou152efa22010-05-16 18:19:27 +00003926 if (PyType_Ready(&PySSLContext_Type) < 0)
3927 return NULL;
3928 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003929 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003931 m = PyModule_Create(&_sslmodule);
3932 if (m == NULL)
3933 return NULL;
3934 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003936 /* Load _socket module and its C API */
3937 socket_api = PySocketModule_ImportModuleAndAPI();
3938 if (!socket_api)
3939 return NULL;
3940 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003942 /* Init OpenSSL */
3943 SSL_load_error_strings();
3944 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003945#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003946 /* note that this will start threading if not already started */
3947 if (!_setup_ssl_threads()) {
3948 return NULL;
3949 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003950#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003951 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003953 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003954 sslerror_type_slots[0].pfunc = PyExc_OSError;
3955 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003956 if (PySSLErrorObject == NULL)
3957 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003958
Antoine Pitrou41032a62011-10-27 23:56:55 +02003959 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3960 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3961 PySSLErrorObject, NULL);
3962 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3963 "ssl.SSLWantReadError", SSLWantReadError_doc,
3964 PySSLErrorObject, NULL);
3965 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3966 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3967 PySSLErrorObject, NULL);
3968 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3969 "ssl.SSLSyscallError", SSLSyscallError_doc,
3970 PySSLErrorObject, NULL);
3971 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3972 "ssl.SSLEOFError", SSLEOFError_doc,
3973 PySSLErrorObject, NULL);
3974 if (PySSLZeroReturnErrorObject == NULL
3975 || PySSLWantReadErrorObject == NULL
3976 || PySSLWantWriteErrorObject == NULL
3977 || PySSLSyscallErrorObject == NULL
3978 || PySSLEOFErrorObject == NULL)
3979 return NULL;
3980 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3981 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3982 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3983 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3984 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3985 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003986 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987 if (PyDict_SetItemString(d, "_SSLContext",
3988 (PyObject *)&PySSLContext_Type) != 0)
3989 return NULL;
3990 if (PyDict_SetItemString(d, "_SSLSocket",
3991 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003992 return NULL;
3993 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3994 PY_SSL_ERROR_ZERO_RETURN);
3995 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3996 PY_SSL_ERROR_WANT_READ);
3997 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3998 PY_SSL_ERROR_WANT_WRITE);
3999 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4000 PY_SSL_ERROR_WANT_X509_LOOKUP);
4001 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4002 PY_SSL_ERROR_SYSCALL);
4003 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4004 PY_SSL_ERROR_SSL);
4005 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4006 PY_SSL_ERROR_WANT_CONNECT);
4007 /* non ssl.h errorcodes */
4008 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4009 PY_SSL_ERROR_EOF);
4010 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4011 PY_SSL_ERROR_INVALID_ERROR_CODE);
4012 /* cert requirements */
4013 PyModule_AddIntConstant(m, "CERT_NONE",
4014 PY_SSL_CERT_NONE);
4015 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4016 PY_SSL_CERT_OPTIONAL);
4017 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4018 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004019 /* CRL verification for verification_flags */
4020 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4021 0);
4022 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4023 X509_V_FLAG_CRL_CHECK);
4024 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4025 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4026 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4027 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004028
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004029 /* Alert Descriptions from ssl.h */
4030 /* note RESERVED constants no longer intended for use have been removed */
4031 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4032
4033#define ADD_AD_CONSTANT(s) \
4034 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4035 SSL_AD_##s)
4036
4037 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4038 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4039 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4040 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4041 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4042 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4043 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4044 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4045 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4046 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4047 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4048 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4049 ADD_AD_CONSTANT(UNKNOWN_CA);
4050 ADD_AD_CONSTANT(ACCESS_DENIED);
4051 ADD_AD_CONSTANT(DECODE_ERROR);
4052 ADD_AD_CONSTANT(DECRYPT_ERROR);
4053 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4054 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4055 ADD_AD_CONSTANT(INTERNAL_ERROR);
4056 ADD_AD_CONSTANT(USER_CANCELLED);
4057 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004058 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004059#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4060 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4061#endif
4062#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4063 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4064#endif
4065#ifdef SSL_AD_UNRECOGNIZED_NAME
4066 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4067#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004068#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4069 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4070#endif
4071#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4072 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4073#endif
4074#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4075 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4076#endif
4077
4078#undef ADD_AD_CONSTANT
4079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004080 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004081#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004082 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4083 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004084#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004085 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4086 PY_SSL_VERSION_SSL3);
4087 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4088 PY_SSL_VERSION_SSL23);
4089 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4090 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004091#if HAVE_TLSv1_2
4092 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4093 PY_SSL_VERSION_TLS1_1);
4094 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4095 PY_SSL_VERSION_TLS1_2);
4096#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004097
Antoine Pitroub5218772010-05-21 09:56:06 +00004098 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004099 PyModule_AddIntConstant(m, "OP_ALL",
4100 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004101 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4102 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4103 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004104#if HAVE_TLSv1_2
4105 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4106 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4107#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004108 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4109 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004110 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004111#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004112 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004113#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004114#ifdef SSL_OP_NO_COMPRESSION
4115 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4116 SSL_OP_NO_COMPRESSION);
4117#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004118
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004119#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004120 r = Py_True;
4121#else
4122 r = Py_False;
4123#endif
4124 Py_INCREF(r);
4125 PyModule_AddObject(m, "HAS_SNI", r);
4126
Antoine Pitroud6494802011-07-21 01:11:30 +02004127#if HAVE_OPENSSL_FINISHED
4128 r = Py_True;
4129#else
4130 r = Py_False;
4131#endif
4132 Py_INCREF(r);
4133 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4134
Antoine Pitrou501da612011-12-21 09:27:41 +01004135#ifdef OPENSSL_NO_ECDH
4136 r = Py_False;
4137#else
4138 r = Py_True;
4139#endif
4140 Py_INCREF(r);
4141 PyModule_AddObject(m, "HAS_ECDH", r);
4142
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004143#ifdef OPENSSL_NPN_NEGOTIATED
4144 r = Py_True;
4145#else
4146 r = Py_False;
4147#endif
4148 Py_INCREF(r);
4149 PyModule_AddObject(m, "HAS_NPN", r);
4150
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004151 /* Mappings for error codes */
4152 err_codes_to_names = PyDict_New();
4153 err_names_to_codes = PyDict_New();
4154 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4155 return NULL;
4156 errcode = error_codes;
4157 while (errcode->mnemonic != NULL) {
4158 PyObject *mnemo, *key;
4159 mnemo = PyUnicode_FromString(errcode->mnemonic);
4160 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4161 if (mnemo == NULL || key == NULL)
4162 return NULL;
4163 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4164 return NULL;
4165 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4166 return NULL;
4167 Py_DECREF(key);
4168 Py_DECREF(mnemo);
4169 errcode++;
4170 }
4171 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4172 return NULL;
4173 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4174 return NULL;
4175
4176 lib_codes_to_names = PyDict_New();
4177 if (lib_codes_to_names == NULL)
4178 return NULL;
4179 libcode = library_codes;
4180 while (libcode->library != NULL) {
4181 PyObject *mnemo, *key;
4182 key = PyLong_FromLong(libcode->code);
4183 mnemo = PyUnicode_FromString(libcode->library);
4184 if (key == NULL || mnemo == NULL)
4185 return NULL;
4186 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4187 return NULL;
4188 Py_DECREF(key);
4189 Py_DECREF(mnemo);
4190 libcode++;
4191 }
4192 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4193 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004195 /* OpenSSL version */
4196 /* SSLeay() gives us the version of the library linked against,
4197 which could be different from the headers version.
4198 */
4199 libver = SSLeay();
4200 r = PyLong_FromUnsignedLong(libver);
4201 if (r == NULL)
4202 return NULL;
4203 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4204 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004205 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004206 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4207 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4208 return NULL;
4209 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4210 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4211 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004212
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004213 libver = OPENSSL_VERSION_NUMBER;
4214 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4215 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4216 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4217 return NULL;
4218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004219 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004220}