blob: d918671fc824191eab3fafa70379e12e8ee60ba9 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
58/* Include OpenSSL header files */
59#include "openssl/rsa.h"
60#include "openssl/crypto.h"
61#include "openssl/x509.h"
62#include "openssl/x509v3.h"
63#include "openssl/pem.h"
64#include "openssl/ssl.h"
65#include "openssl/err.h"
66#include "openssl/rand.h"
67
68/* SSL error object */
69static PyObject *PySSLErrorObject;
70static PyObject *PySSLZeroReturnErrorObject;
71static PyObject *PySSLWantReadErrorObject;
72static PyObject *PySSLWantWriteErrorObject;
73static PyObject *PySSLSyscallErrorObject;
74static PyObject *PySSLEOFErrorObject;
75
76/* Error mappings */
77static PyObject *err_codes_to_names;
78static PyObject *err_names_to_codes;
79static PyObject *lib_codes_to_names;
80
81struct py_ssl_error_code {
82 const char *mnemonic;
83 int library, reason;
84};
85struct py_ssl_library_code {
86 const char *library;
87 int code;
88};
89
90/* Include generated data (error codes) */
91#include "_ssl_data.h"
92
93/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
94 http://www.openssl.org/news/changelog.html
95 */
96#if OPENSSL_VERSION_NUMBER >= 0x10001000L
97# define HAVE_TLSv1_2 1
98#else
99# define HAVE_TLSv1_2 0
100#endif
101
Christian Heimes470fba12013-11-28 15:12:15 +0100102/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100103 * This includes the SSL_set_SSL_CTX() function.
104 */
105#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
106# define HAVE_SNI 1
107#else
108# define HAVE_SNI 0
109#endif
110
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000111enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000112 /* these mirror ssl.h */
113 PY_SSL_ERROR_NONE,
114 PY_SSL_ERROR_SSL,
115 PY_SSL_ERROR_WANT_READ,
116 PY_SSL_ERROR_WANT_WRITE,
117 PY_SSL_ERROR_WANT_X509_LOOKUP,
118 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
119 PY_SSL_ERROR_ZERO_RETURN,
120 PY_SSL_ERROR_WANT_CONNECT,
121 /* start of non ssl.h errorcodes */
122 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
123 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
124 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000125};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000126
Thomas Woutersed03b412007-08-28 21:37:11 +0000127enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000128 PY_SSL_CLIENT,
129 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000130};
131
132enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000133 PY_SSL_CERT_NONE,
134 PY_SSL_CERT_OPTIONAL,
135 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000136};
137
138enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200140 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000141 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142#if HAVE_TLSv1_2
143 PY_SSL_VERSION_TLS1,
144 PY_SSL_VERSION_TLS1_1,
145 PY_SSL_VERSION_TLS1_2
146#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100149};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200150
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151#ifdef WITH_THREAD
152
153/* serves as a flag to see whether we've initialized the SSL thread support. */
154/* 0 means no, greater than 0 means yes */
155
156static unsigned int _ssl_locks_count = 0;
157
158#endif /* def WITH_THREAD */
159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160/* SSL socket object */
161
162#define X509_NAME_MAXLEN 256
163
164/* RAND_* APIs got added to OpenSSL in 0.9.5 */
165#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
166# define HAVE_OPENSSL_RAND 1
167#else
168# undef HAVE_OPENSSL_RAND
169#endif
170
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000171/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
172 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
173 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
174#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000175# define HAVE_SSL_CTX_CLEAR_OPTIONS
176#else
177# undef HAVE_SSL_CTX_CLEAR_OPTIONS
178#endif
179
Antoine Pitroud6494802011-07-21 01:11:30 +0200180/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
181 * older SSL, but let's be safe */
182#define PySSL_CB_MAXLEN 128
183
184/* SSL_get_finished got added to OpenSSL in 0.9.5 */
185#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
186# define HAVE_OPENSSL_FINISHED 1
187#else
188# define HAVE_OPENSSL_FINISHED 0
189#endif
190
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100191/* ECDH support got added to OpenSSL in 0.9.8 */
192#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
193# define OPENSSL_NO_ECDH
194#endif
195
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100196/* compression support got added to OpenSSL in 0.9.8 */
197#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
198# define OPENSSL_NO_COMP
199#endif
200
Christian Heimes2427b502013-11-23 11:24:32 +0100201/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
202#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
203# define HAVE_OPENSSL_VERIFY_PARAM
204#endif
205
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100206
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000207typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000208 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100210#ifdef OPENSSL_NPN_NEGOTIATED
211 char *npn_protocols;
212 int npn_protocols_len;
213#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100214#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200215 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100216#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100217 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000218} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000219
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220typedef struct {
221 PyObject_HEAD
222 PyObject *Socket; /* weakref to socket on which we're layered */
223 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100224 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200226 char shutdown_seen_zero;
227 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200228 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000230
Antoine Pitrou152efa22010-05-16 18:19:27 +0000231static PyTypeObject PySSLContext_Type;
232static PyTypeObject PySSLSocket_Type;
233
234static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
235static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000236static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000237 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000238static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
239static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000240
Antoine Pitrou152efa22010-05-16 18:19:27 +0000241#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
242#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000243
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000244typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000245 SOCKET_IS_NONBLOCKING,
246 SOCKET_IS_BLOCKING,
247 SOCKET_HAS_TIMED_OUT,
248 SOCKET_HAS_BEEN_CLOSED,
249 SOCKET_TOO_LARGE_FOR_SELECT,
250 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000251} timeout_state;
252
Thomas Woutersed03b412007-08-28 21:37:11 +0000253/* Wrap error strings with filename and line # */
254#define STRINGIFY1(x) #x
255#define STRINGIFY2(x) STRINGIFY1(x)
256#define ERRSTR1(x,y,z) (x ":" y ": " z)
257#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
258
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200259
260/*
261 * SSL errors.
262 */
263
264PyDoc_STRVAR(SSLError_doc,
265"An error occurred in the SSL implementation.");
266
267PyDoc_STRVAR(SSLZeroReturnError_doc,
268"SSL/TLS session closed cleanly.");
269
270PyDoc_STRVAR(SSLWantReadError_doc,
271"Non-blocking SSL socket needs to read more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLWantWriteError_doc,
275"Non-blocking SSL socket needs to write more data\n"
276"before the requested operation can be completed.");
277
278PyDoc_STRVAR(SSLSyscallError_doc,
279"System error when attempting SSL operation.");
280
281PyDoc_STRVAR(SSLEOFError_doc,
282"SSL/TLS connection terminated abruptly.");
283
284static PyObject *
285SSLError_str(PyOSErrorObject *self)
286{
287 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
288 Py_INCREF(self->strerror);
289 return self->strerror;
290 }
291 else
292 return PyObject_Str(self->args);
293}
294
295static PyType_Slot sslerror_type_slots[] = {
296 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
297 {Py_tp_doc, SSLError_doc},
298 {Py_tp_str, SSLError_str},
299 {0, 0},
300};
301
302static PyType_Spec sslerror_type_spec = {
303 "ssl.SSLError",
304 sizeof(PyOSErrorObject),
305 0,
306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
307 sslerror_type_slots
308};
309
310static void
311fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
312 int lineno, unsigned long errcode)
313{
314 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
315 PyObject *init_value, *msg, *key;
316 _Py_IDENTIFIER(reason);
317 _Py_IDENTIFIER(library);
318
319 if (errcode != 0) {
320 int lib, reason;
321
322 lib = ERR_GET_LIB(errcode);
323 reason = ERR_GET_REASON(errcode);
324 key = Py_BuildValue("ii", lib, reason);
325 if (key == NULL)
326 goto fail;
327 reason_obj = PyDict_GetItem(err_codes_to_names, key);
328 Py_DECREF(key);
329 if (reason_obj == NULL) {
330 /* XXX if reason < 100, it might reflect a library number (!!) */
331 PyErr_Clear();
332 }
333 key = PyLong_FromLong(lib);
334 if (key == NULL)
335 goto fail;
336 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
337 Py_DECREF(key);
338 if (lib_obj == NULL) {
339 PyErr_Clear();
340 }
341 if (errstr == NULL)
342 errstr = ERR_reason_error_string(errcode);
343 }
344 if (errstr == NULL)
345 errstr = "unknown error";
346
347 if (reason_obj && lib_obj)
348 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
349 lib_obj, reason_obj, errstr, lineno);
350 else if (lib_obj)
351 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
352 lib_obj, errstr, lineno);
353 else
354 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355 if (msg == NULL)
356 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100357
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200358 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100359 if (init_value == NULL)
360 goto fail;
361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 err_value = PyObject_CallObject(type, init_value);
363 Py_DECREF(init_value);
364 if (err_value == NULL)
365 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100366
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 if (reason_obj == NULL)
368 reason_obj = Py_None;
369 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
370 goto fail;
371 if (lib_obj == NULL)
372 lib_obj = Py_None;
373 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
374 goto fail;
375 PyErr_SetObject(type, err_value);
376fail:
377 Py_XDECREF(err_value);
378}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
380static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200383 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 int err;
386 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200390 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 if (obj->ssl != NULL) {
393 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 switch (err) {
396 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 errstr = "TLS/SSL connection has been closed (EOF)";
398 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 p = PY_SSL_ERROR_ZERO_RETURN;
400 break;
401 case SSL_ERROR_WANT_READ:
402 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200403 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 p = PY_SSL_ERROR_WANT_READ;
405 break;
406 case SSL_ERROR_WANT_WRITE:
407 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200408 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 errstr = "The operation did not complete (write)";
410 break;
411 case SSL_ERROR_WANT_X509_LOOKUP:
412 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000413 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 break;
415 case SSL_ERROR_WANT_CONNECT:
416 p = PY_SSL_ERROR_WANT_CONNECT;
417 errstr = "The operation did not complete (connect)";
418 break;
419 case SSL_ERROR_SYSCALL:
420 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 if (e == 0) {
422 PySocketSockObject *s
423 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
424 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200426 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000430 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000431 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000433 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200434 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200437 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000438 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 }
440 } else {
441 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 }
443 break;
444 }
445 case SSL_ERROR_SSL:
446 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448 if (e == 0)
449 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000450 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 break;
452 }
453 default:
454 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
455 errstr = "Invalid error code";
456 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000459 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000461}
462
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463static PyObject *
464_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 else
469 errcode = 0;
470 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000471 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000472 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473}
474
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200475/*
476 * SSL objects
477 */
478
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100480newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000481 enum py_ssl_server_or_client socket_type,
482 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100485 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200486 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000487
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 if (self == NULL)
490 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 self->peer_cert = NULL;
493 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100495 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200496 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200497 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100498 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 /* Make sure the SSL error state is initialized */
501 (void) ERR_get_state();
502 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000506 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100507 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100508 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200509 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000510#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200511 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000512#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200513 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000514
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100515#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000516 if (server_hostname != NULL)
517 SSL_set_tlsext_host_name(self->ssl, server_hostname);
518#endif
519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 /* If the socket is in non-blocking mode or timeout mode, set the BIO
521 * to non-blocking mode (blocking is the default)
522 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000523 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
525 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
526 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000528 PySSL_BEGIN_ALLOW_THREADS
529 if (socket_type == PY_SSL_CLIENT)
530 SSL_set_connect_state(self->ssl);
531 else
532 SSL_set_accept_state(self->ssl);
533 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000534
Antoine Pitroud6494802011-07-21 01:11:30 +0200535 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000536 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100537 if (self->Socket == NULL) {
538 Py_DECREF(self);
539 return NULL;
540 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542}
543
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000544/* SSL object methods */
545
Antoine Pitrou152efa22010-05-16 18:19:27 +0000546static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000547{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 int ret;
549 int err;
550 int sockstate, nonblocking;
551 PySocketSockObject *sock
552 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 if (((PyObject*)sock) == Py_None) {
555 _setSSLError("Underlying socket connection gone",
556 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
557 return NULL;
558 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000559 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 /* just in case the blocking state of the socket has been changed */
562 nonblocking = (sock->sock_timeout >= 0.0);
563 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
564 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 /* Actually negotiate SSL connection */
567 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000569 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 ret = SSL_do_handshake(self->ssl);
571 err = SSL_get_error(self->ssl, ret);
572 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000573 if (PyErr_CheckSignals())
574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 if (err == SSL_ERROR_WANT_READ) {
576 sockstate = check_socket_and_wait_for_timeout(sock, 0);
577 } else if (err == SSL_ERROR_WANT_WRITE) {
578 sockstate = check_socket_and_wait_for_timeout(sock, 1);
579 } else {
580 sockstate = SOCKET_OPERATION_OK;
581 }
582 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000583 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000584 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000585 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
587 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000588 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000589 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
591 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000592 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000593 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
595 break;
596 }
597 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000598 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 if (ret < 1)
600 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 if (self->peer_cert)
603 X509_free (self->peer_cert);
604 PySSL_BEGIN_ALLOW_THREADS
605 self->peer_cert = SSL_get_peer_certificate(self->ssl);
606 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200607 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608
609 Py_INCREF(Py_None);
610 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000611
612error:
613 Py_DECREF(sock);
614 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000615}
616
Thomas Woutersed03b412007-08-28 21:37:11 +0000617static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 char namebuf[X509_NAME_MAXLEN];
621 int buflen;
622 PyObject *name_obj;
623 PyObject *value_obj;
624 PyObject *attr;
625 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
628 if (buflen < 0) {
629 _setSSLError(NULL, 0, __FILE__, __LINE__);
630 goto fail;
631 }
632 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
633 if (name_obj == NULL)
634 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
637 if (buflen < 0) {
638 _setSSLError(NULL, 0, __FILE__, __LINE__);
639 Py_DECREF(name_obj);
640 goto fail;
641 }
642 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000643 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 OPENSSL_free(valuebuf);
645 if (value_obj == NULL) {
646 Py_DECREF(name_obj);
647 goto fail;
648 }
649 attr = PyTuple_New(2);
650 if (attr == NULL) {
651 Py_DECREF(name_obj);
652 Py_DECREF(value_obj);
653 goto fail;
654 }
655 PyTuple_SET_ITEM(attr, 0, name_obj);
656 PyTuple_SET_ITEM(attr, 1, value_obj);
657 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000658
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000661}
662
663static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000665{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
667 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
668 PyObject *rdnt;
669 PyObject *attr = NULL; /* tuple to hold an attribute */
670 int entry_count = X509_NAME_entry_count(xname);
671 X509_NAME_ENTRY *entry;
672 ASN1_OBJECT *name;
673 ASN1_STRING *value;
674 int index_counter;
675 int rdn_level = -1;
676 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 dn = PyList_New(0);
679 if (dn == NULL)
680 return NULL;
681 /* now create another tuple to hold the top-level RDN */
682 rdn = PyList_New(0);
683 if (rdn == NULL)
684 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 for (index_counter = 0;
687 index_counter < entry_count;
688 index_counter++)
689 {
690 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 /* check to see if we've gotten to a new RDN */
693 if (rdn_level >= 0) {
694 if (rdn_level != entry->set) {
695 /* yes, new RDN */
696 /* add old RDN to DN */
697 rdnt = PyList_AsTuple(rdn);
698 Py_DECREF(rdn);
699 if (rdnt == NULL)
700 goto fail0;
701 retcode = PyList_Append(dn, rdnt);
702 Py_DECREF(rdnt);
703 if (retcode < 0)
704 goto fail0;
705 /* create new RDN */
706 rdn = PyList_New(0);
707 if (rdn == NULL)
708 goto fail0;
709 }
710 }
711 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 /* now add this attribute to the current RDN */
714 name = X509_NAME_ENTRY_get_object(entry);
715 value = X509_NAME_ENTRY_get_data(entry);
716 attr = _create_tuple_for_attribute(name, value);
717 /*
718 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
719 entry->set,
720 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
721 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
722 */
723 if (attr == NULL)
724 goto fail1;
725 retcode = PyList_Append(rdn, attr);
726 Py_DECREF(attr);
727 if (retcode < 0)
728 goto fail1;
729 }
730 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100731 if (rdn != NULL) {
732 if (PyList_GET_SIZE(rdn) > 0) {
733 rdnt = PyList_AsTuple(rdn);
734 Py_DECREF(rdn);
735 if (rdnt == NULL)
736 goto fail0;
737 retcode = PyList_Append(dn, rdnt);
738 Py_DECREF(rdnt);
739 if (retcode < 0)
740 goto fail0;
741 }
742 else {
743 Py_DECREF(rdn);
744 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 /* convert list to tuple */
748 rdnt = PyList_AsTuple(dn);
749 Py_DECREF(dn);
750 if (rdnt == NULL)
751 return NULL;
752 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753
754 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
757 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 Py_XDECREF(dn);
759 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760}
761
762static PyObject *
763_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 /* this code follows the procedure outlined in
766 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
767 function to extract the STACK_OF(GENERAL_NAME),
768 then iterates through the stack to add the
769 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 int i, j;
772 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200773 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 X509_EXTENSION *ext = NULL;
775 GENERAL_NAMES *names = NULL;
776 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000777 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 BIO *biobuf = NULL;
779 char buf[2048];
780 char *vptr;
781 int len;
782 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000783#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000785#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000787#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 if (certificate == NULL)
790 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 /* get a memory buffer */
793 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200795 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 while ((i = X509_get_ext_by_NID(
797 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 if (peer_alt_names == Py_None) {
800 peer_alt_names = PyList_New(0);
801 if (peer_alt_names == NULL)
802 goto fail;
803 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 /* now decode the altName */
806 ext = X509_get_ext(certificate, i);
807 if(!(method = X509V3_EXT_get(ext))) {
808 PyErr_SetString
809 (PySSLErrorObject,
810 ERRSTR("No method for internalizing subjectAltName!"));
811 goto fail;
812 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 p = ext->value->data;
815 if (method->it)
816 names = (GENERAL_NAMES*)
817 (ASN1_item_d2i(NULL,
818 &p,
819 ext->value->length,
820 ASN1_ITEM_ptr(method->it)));
821 else
822 names = (GENERAL_NAMES*)
823 (method->d2i(NULL,
824 &p,
825 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200829 int gntype;
830 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200833 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200834 switch (gntype) {
835 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 /* we special-case DirName as a tuple of
837 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 t = PyTuple_New(2);
840 if (t == NULL) {
841 goto fail;
842 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 v = PyUnicode_FromString("DirName");
845 if (v == NULL) {
846 Py_DECREF(t);
847 goto fail;
848 }
849 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 v = _create_tuple_for_X509_NAME (name->d.dirn);
852 if (v == NULL) {
853 Py_DECREF(t);
854 goto fail;
855 }
856 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200857 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000858
Christian Heimes824f7f32013-08-17 00:54:47 +0200859 case GEN_EMAIL:
860 case GEN_DNS:
861 case GEN_URI:
862 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
863 correctly, CVE-2013-4238 */
864 t = PyTuple_New(2);
865 if (t == NULL)
866 goto fail;
867 switch (gntype) {
868 case GEN_EMAIL:
869 v = PyUnicode_FromString("email");
870 as = name->d.rfc822Name;
871 break;
872 case GEN_DNS:
873 v = PyUnicode_FromString("DNS");
874 as = name->d.dNSName;
875 break;
876 case GEN_URI:
877 v = PyUnicode_FromString("URI");
878 as = name->d.uniformResourceIdentifier;
879 break;
880 }
881 if (v == NULL) {
882 Py_DECREF(t);
883 goto fail;
884 }
885 PyTuple_SET_ITEM(t, 0, v);
886 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
887 ASN1_STRING_length(as));
888 if (v == NULL) {
889 Py_DECREF(t);
890 goto fail;
891 }
892 PyTuple_SET_ITEM(t, 1, v);
893 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Christian Heimes824f7f32013-08-17 00:54:47 +0200895 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200897 switch (gntype) {
898 /* check for new general name type */
899 case GEN_OTHERNAME:
900 case GEN_X400:
901 case GEN_EDIPARTY:
902 case GEN_IPADD:
903 case GEN_RID:
904 break;
905 default:
906 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
907 "Unknown general name type %d",
908 gntype) == -1) {
909 goto fail;
910 }
911 break;
912 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 (void) BIO_reset(biobuf);
914 GENERAL_NAME_print(biobuf, name);
915 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
916 if (len < 0) {
917 _setSSLError(NULL, 0, __FILE__, __LINE__);
918 goto fail;
919 }
920 vptr = strchr(buf, ':');
921 if (vptr == NULL)
922 goto fail;
923 t = PyTuple_New(2);
924 if (t == NULL)
925 goto fail;
926 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
927 if (v == NULL) {
928 Py_DECREF(t);
929 goto fail;
930 }
931 PyTuple_SET_ITEM(t, 0, v);
932 v = PyUnicode_FromStringAndSize((vptr + 1),
933 (len - (vptr - buf + 1)));
934 if (v == NULL) {
935 Py_DECREF(t);
936 goto fail;
937 }
938 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200939 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 if (PyList_Append(peer_alt_names, t) < 0) {
945 Py_DECREF(t);
946 goto fail;
947 }
948 Py_DECREF(t);
949 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100950 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 }
952 BIO_free(biobuf);
953 if (peer_alt_names != Py_None) {
954 v = PyList_AsTuple(peer_alt_names);
955 Py_DECREF(peer_alt_names);
956 return v;
957 } else {
958 return peer_alt_names;
959 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000960
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961
962 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 if (biobuf != NULL)
964 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 if (peer_alt_names != Py_None) {
967 Py_XDECREF(peer_alt_names);
968 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971}
972
973static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100974_get_aia_uri(X509 *certificate, int nid) {
975 PyObject *lst = NULL, *ostr = NULL;
976 int i, result;
977 AUTHORITY_INFO_ACCESS *info;
978
979 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -0800980 if (info == NULL)
981 return Py_None;
982 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
983 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100984 return Py_None;
985 }
986
987 if ((lst = PyList_New(0)) == NULL) {
988 goto fail;
989 }
990
991 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
992 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
993 ASN1_IA5STRING *uri;
994
995 if ((OBJ_obj2nid(ad->method) != nid) ||
996 (ad->location->type != GEN_URI)) {
997 continue;
998 }
999 uri = ad->location->d.uniformResourceIdentifier;
1000 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1001 uri->length);
1002 if (ostr == NULL) {
1003 goto fail;
1004 }
1005 result = PyList_Append(lst, ostr);
1006 Py_DECREF(ostr);
1007 if (result < 0) {
1008 goto fail;
1009 }
1010 }
1011 AUTHORITY_INFO_ACCESS_free(info);
1012
1013 /* convert to tuple or None */
1014 if (PyList_Size(lst) == 0) {
1015 Py_DECREF(lst);
1016 return Py_None;
1017 } else {
1018 PyObject *tup;
1019 tup = PyList_AsTuple(lst);
1020 Py_DECREF(lst);
1021 return tup;
1022 }
1023
1024 fail:
1025 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001026 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001027 return NULL;
1028}
1029
1030static PyObject *
1031_get_crl_dp(X509 *certificate) {
1032 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001033 int i, j;
1034 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001035
Christian Heimes949ec142013-11-21 16:26:51 +01001036#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001037 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001038#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001039 /* Calls x509v3_cache_extensions and sets up crldp */
1040 X509_check_ca(certificate);
1041 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001042#endif
1043
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001044 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001045 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001046
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001047 lst = PyList_New(0);
1048 if (lst == NULL)
1049 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001050
1051 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1052 DIST_POINT *dp;
1053 STACK_OF(GENERAL_NAME) *gns;
1054
1055 dp = sk_DIST_POINT_value(dps, i);
1056 gns = dp->distpoint->name.fullname;
1057
1058 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1059 GENERAL_NAME *gn;
1060 ASN1_IA5STRING *uri;
1061 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001062 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001063
1064 gn = sk_GENERAL_NAME_value(gns, j);
1065 if (gn->type != GEN_URI) {
1066 continue;
1067 }
1068 uri = gn->d.uniformResourceIdentifier;
1069 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1070 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001071 if (ouri == NULL)
1072 goto done;
1073
1074 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001075 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001076 if (err < 0)
1077 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001078 }
1079 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001080
1081 /* Convert to tuple. */
1082 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1083
1084 done:
1085 Py_XDECREF(lst);
1086#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001087 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001088#endif
1089 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001090}
1091
1092static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001093_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 PyObject *retval = NULL;
1096 BIO *biobuf = NULL;
1097 PyObject *peer;
1098 PyObject *peer_alt_names = NULL;
1099 PyObject *issuer;
1100 PyObject *version;
1101 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001102 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 ASN1_INTEGER *serialNumber;
1104 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001105 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 ASN1_TIME *notBefore, *notAfter;
1107 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 retval = PyDict_New();
1110 if (retval == NULL)
1111 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 peer = _create_tuple_for_X509_NAME(
1114 X509_get_subject_name(certificate));
1115 if (peer == NULL)
1116 goto fail0;
1117 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1118 Py_DECREF(peer);
1119 goto fail0;
1120 }
1121 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001122
Antoine Pitroufb046912010-11-09 20:21:19 +00001123 issuer = _create_tuple_for_X509_NAME(
1124 X509_get_issuer_name(certificate));
1125 if (issuer == NULL)
1126 goto fail0;
1127 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001129 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001131 Py_DECREF(issuer);
1132
1133 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001134 if (version == NULL)
1135 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001136 if (PyDict_SetItemString(retval, "version", version) < 0) {
1137 Py_DECREF(version);
1138 goto fail0;
1139 }
1140 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 /* get a memory buffer */
1143 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001144
Antoine Pitroufb046912010-11-09 20:21:19 +00001145 (void) BIO_reset(biobuf);
1146 serialNumber = X509_get_serialNumber(certificate);
1147 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1148 i2a_ASN1_INTEGER(biobuf, serialNumber);
1149 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1150 if (len < 0) {
1151 _setSSLError(NULL, 0, __FILE__, __LINE__);
1152 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001154 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1155 if (sn_obj == NULL)
1156 goto fail1;
1157 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1158 Py_DECREF(sn_obj);
1159 goto fail1;
1160 }
1161 Py_DECREF(sn_obj);
1162
1163 (void) BIO_reset(biobuf);
1164 notBefore = X509_get_notBefore(certificate);
1165 ASN1_TIME_print(biobuf, notBefore);
1166 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1167 if (len < 0) {
1168 _setSSLError(NULL, 0, __FILE__, __LINE__);
1169 goto fail1;
1170 }
1171 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1172 if (pnotBefore == NULL)
1173 goto fail1;
1174 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1175 Py_DECREF(pnotBefore);
1176 goto fail1;
1177 }
1178 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 (void) BIO_reset(biobuf);
1181 notAfter = X509_get_notAfter(certificate);
1182 ASN1_TIME_print(biobuf, notAfter);
1183 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1184 if (len < 0) {
1185 _setSSLError(NULL, 0, __FILE__, __LINE__);
1186 goto fail1;
1187 }
1188 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1189 if (pnotAfter == NULL)
1190 goto fail1;
1191 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1192 Py_DECREF(pnotAfter);
1193 goto fail1;
1194 }
1195 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 peer_alt_names = _get_peer_alt_names(certificate);
1200 if (peer_alt_names == NULL)
1201 goto fail1;
1202 else if (peer_alt_names != Py_None) {
1203 if (PyDict_SetItemString(retval, "subjectAltName",
1204 peer_alt_names) < 0) {
1205 Py_DECREF(peer_alt_names);
1206 goto fail1;
1207 }
1208 Py_DECREF(peer_alt_names);
1209 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001210
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001211 /* Authority Information Access: OCSP URIs */
1212 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1213 if (obj == NULL) {
1214 goto fail1;
1215 } else if (obj != Py_None) {
1216 result = PyDict_SetItemString(retval, "OCSP", obj);
1217 Py_DECREF(obj);
1218 if (result < 0) {
1219 goto fail1;
1220 }
1221 }
1222
1223 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1224 if (obj == NULL) {
1225 goto fail1;
1226 } else if (obj != Py_None) {
1227 result = PyDict_SetItemString(retval, "caIssuers", obj);
1228 Py_DECREF(obj);
1229 if (result < 0) {
1230 goto fail1;
1231 }
1232 }
1233
1234 /* CDP (CRL distribution points) */
1235 obj = _get_crl_dp(certificate);
1236 if (obj == NULL) {
1237 goto fail1;
1238 } else if (obj != Py_None) {
1239 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1240 Py_DECREF(obj);
1241 if (result < 0) {
1242 goto fail1;
1243 }
1244 }
1245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 BIO_free(biobuf);
1247 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001248
1249 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 if (biobuf != NULL)
1251 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001252 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 Py_XDECREF(retval);
1254 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001255}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001256
Christian Heimes9a5395a2013-06-17 15:44:12 +02001257static PyObject *
1258_certificate_to_der(X509 *certificate)
1259{
1260 unsigned char *bytes_buf = NULL;
1261 int len;
1262 PyObject *retval;
1263
1264 bytes_buf = NULL;
1265 len = i2d_X509(certificate, &bytes_buf);
1266 if (len < 0) {
1267 _setSSLError(NULL, 0, __FILE__, __LINE__);
1268 return NULL;
1269 }
1270 /* this is actually an immutable bytes sequence */
1271 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1272 OPENSSL_free(bytes_buf);
1273 return retval;
1274}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
1276static PyObject *
1277PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001280 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 X509 *x=NULL;
1282 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001283
Antoine Pitroufb046912010-11-09 20:21:19 +00001284 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1285 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1289 PyErr_SetString(PySSLErrorObject,
1290 "Can't malloc memory to read file");
1291 goto fail0;
1292 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001293
Victor Stinner3800e1e2010-05-16 21:23:48 +00001294 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 PyErr_SetString(PySSLErrorObject,
1296 "Can't open file");
1297 goto fail0;
1298 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1301 if (x == NULL) {
1302 PyErr_SetString(PySSLErrorObject,
1303 "Error decoding PEM-encoded file");
1304 goto fail0;
1305 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
Antoine Pitroufb046912010-11-09 20:21:19 +00001307 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001308 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
1310 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001311 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (cert != NULL) BIO_free(cert);
1313 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314}
1315
1316
1317static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001318PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001321 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Antoine Pitrou721738f2012-08-15 23:20:39 +02001323 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325
Antoine Pitrou20b85552013-09-29 19:50:53 +02001326 if (!self->handshake_done) {
1327 PyErr_SetString(PyExc_ValueError,
1328 "handshake not done yet");
1329 return NULL;
1330 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 if (!self->peer_cert)
1332 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001333
Antoine Pitrou721738f2012-08-15 23:20:39 +02001334 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001336 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001338 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 if ((verification & SSL_VERIFY_PEER) == 0)
1340 return PyDict_New();
1341 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001342 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344}
1345
1346PyDoc_STRVAR(PySSL_peercert_doc,
1347"peer_certificate([der=False]) -> certificate\n\
1348\n\
1349Returns the certificate for the peer. If no certificate was provided,\n\
1350returns None. If a certificate was provided, but not validated, returns\n\
1351an empty dictionary. Otherwise returns a dict containing information\n\
1352about the peer certificate.\n\
1353\n\
1354If the optional argument is True, returns a DER-encoded copy of the\n\
1355peer certificate, or None if no certificate was provided. This will\n\
1356return the certificate even if it wasn't validated.");
1357
Antoine Pitrou152efa22010-05-16 18:19:27 +00001358static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001361 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 char *cipher_name;
1363 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001366 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 current = SSL_get_current_cipher(self->ssl);
1368 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001369 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 retval = PyTuple_New(3);
1372 if (retval == NULL)
1373 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 cipher_name = (char *) SSL_CIPHER_get_name(current);
1376 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001377 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 PyTuple_SET_ITEM(retval, 0, Py_None);
1379 } else {
1380 v = PyUnicode_FromString(cipher_name);
1381 if (v == NULL)
1382 goto fail0;
1383 PyTuple_SET_ITEM(retval, 0, v);
1384 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001385 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001386 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001387 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 PyTuple_SET_ITEM(retval, 1, Py_None);
1389 } else {
1390 v = PyUnicode_FromString(cipher_protocol);
1391 if (v == NULL)
1392 goto fail0;
1393 PyTuple_SET_ITEM(retval, 1, v);
1394 }
1395 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1396 if (v == NULL)
1397 goto fail0;
1398 PyTuple_SET_ITEM(retval, 2, v);
1399 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001400
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 Py_DECREF(retval);
1403 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404}
1405
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001406#ifdef OPENSSL_NPN_NEGOTIATED
1407static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1408 const unsigned char *out;
1409 unsigned int outlen;
1410
Victor Stinner4569cd52013-06-23 14:58:43 +02001411 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001412 &out, &outlen);
1413
1414 if (out == NULL)
1415 Py_RETURN_NONE;
1416 return PyUnicode_FromStringAndSize((char *) out, outlen);
1417}
1418#endif
1419
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001420static PyObject *PySSL_compression(PySSLSocket *self) {
1421#ifdef OPENSSL_NO_COMP
1422 Py_RETURN_NONE;
1423#else
1424 const COMP_METHOD *comp_method;
1425 const char *short_name;
1426
1427 if (self->ssl == NULL)
1428 Py_RETURN_NONE;
1429 comp_method = SSL_get_current_compression(self->ssl);
1430 if (comp_method == NULL || comp_method->type == NID_undef)
1431 Py_RETURN_NONE;
1432 short_name = OBJ_nid2sn(comp_method->type);
1433 if (short_name == NULL)
1434 Py_RETURN_NONE;
1435 return PyUnicode_DecodeFSDefault(short_name);
1436#endif
1437}
1438
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001439static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1440 Py_INCREF(self->ctx);
1441 return self->ctx;
1442}
1443
1444static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1445 void *closure) {
1446
1447 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001448#if !HAVE_SNI
1449 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1450 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001451 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001452#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001453 Py_INCREF(value);
1454 Py_DECREF(self->ctx);
1455 self->ctx = (PySSLContext *) value;
1456 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001457#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001458 } else {
1459 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1460 return -1;
1461 }
1462
1463 return 0;
1464}
1465
1466PyDoc_STRVAR(PySSL_set_context_doc,
1467"_setter_context(ctx)\n\
1468\
1469This changes the context associated with the SSLSocket. This is typically\n\
1470used from within a callback function set by the set_servername_callback\n\
1471on the SSLContext to change the certificate information associated with the\n\
1472SSLSocket before the cryptographic exchange handshake messages\n");
1473
1474
1475
Antoine Pitrou152efa22010-05-16 18:19:27 +00001476static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001477{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 if (self->peer_cert) /* Possible not to have one? */
1479 X509_free (self->peer_cert);
1480 if (self->ssl)
1481 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001483 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485}
1486
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001488 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001489 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001490 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001491
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001492static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001493check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001494{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 fd_set fds;
1496 struct timeval tv;
1497 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1500 if (s->sock_timeout < 0.0)
1501 return SOCKET_IS_BLOCKING;
1502 else if (s->sock_timeout == 0.0)
1503 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 /* Guard against closed socket */
1506 if (s->sock_fd < 0)
1507 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 /* Prefer poll, if available, since you can poll() any fd
1510 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001511#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 {
1513 struct pollfd pollfd;
1514 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 pollfd.fd = s->sock_fd;
1517 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 /* s->sock_timeout is in seconds, timeout in ms */
1520 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1521 PySSL_BEGIN_ALLOW_THREADS
1522 rc = poll(&pollfd, 1, timeout);
1523 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 goto normal_return;
1526 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001527#endif
1528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001530 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 /* Construct the arguments to select */
1534 tv.tv_sec = (int)s->sock_timeout;
1535 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1536 FD_ZERO(&fds);
1537 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 /* See if the socket is ready */
1540 PySSL_BEGIN_ALLOW_THREADS
1541 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001542 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1543 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001545 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1546 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001548
Bill Janssen6e027db2007-11-15 22:23:56 +00001549#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001551#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1553 (when we are able to write or when there's something to read) */
1554 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001555}
1556
Antoine Pitrou152efa22010-05-16 18:19:27 +00001557static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001558{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 Py_buffer buf;
1560 int len;
1561 int sockstate;
1562 int err;
1563 int nonblocking;
1564 PySocketSockObject *sock
1565 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 if (((PyObject*)sock) == Py_None) {
1568 _setSSLError("Underlying socket connection gone",
1569 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1570 return NULL;
1571 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001572 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001574 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1575 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578
Victor Stinner6efa9652013-06-25 00:42:31 +02001579 if (buf.len > INT_MAX) {
1580 PyErr_Format(PyExc_OverflowError,
1581 "string longer than %d bytes", INT_MAX);
1582 goto error;
1583 }
1584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 /* just in case the blocking state of the socket has been changed */
1586 nonblocking = (sock->sock_timeout >= 0.0);
1587 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1588 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1589
1590 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1591 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001592 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 "The write operation timed out");
1594 goto error;
1595 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1596 PyErr_SetString(PySSLErrorObject,
1597 "Underlying socket has been closed.");
1598 goto error;
1599 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1600 PyErr_SetString(PySSLErrorObject,
1601 "Underlying socket too large for select().");
1602 goto error;
1603 }
1604 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001606 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 err = SSL_get_error(self->ssl, len);
1608 PySSL_END_ALLOW_THREADS
1609 if (PyErr_CheckSignals()) {
1610 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001611 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001613 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001615 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 } else {
1617 sockstate = SOCKET_OPERATION_OK;
1618 }
1619 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001620 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 "The write operation timed out");
1622 goto error;
1623 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1624 PyErr_SetString(PySSLErrorObject,
1625 "Underlying socket has been closed.");
1626 goto error;
1627 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1628 break;
1629 }
1630 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001632 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 PyBuffer_Release(&buf);
1634 if (len > 0)
1635 return PyLong_FromLong(len);
1636 else
1637 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001638
1639error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001640 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 PyBuffer_Release(&buf);
1642 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001643}
1644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001645PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001646"write(s) -> len\n\
1647\n\
1648Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001649of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001650
Antoine Pitrou152efa22010-05-16 18:19:27 +00001651static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001652{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001653 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 PySSL_BEGIN_ALLOW_THREADS
1656 count = SSL_pending(self->ssl);
1657 PySSL_END_ALLOW_THREADS
1658 if (count < 0)
1659 return PySSL_SetError(self, count, __FILE__, __LINE__);
1660 else
1661 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001662}
1663
1664PyDoc_STRVAR(PySSL_SSLpending_doc,
1665"pending() -> count\n\
1666\n\
1667Returns the number of already decrypted bytes available for read,\n\
1668pending on the connection.\n");
1669
Antoine Pitrou152efa22010-05-16 18:19:27 +00001670static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001671{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyObject *dest = NULL;
1673 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001675 int len, count;
1676 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 int sockstate;
1678 int err;
1679 int nonblocking;
1680 PySocketSockObject *sock
1681 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 if (((PyObject*)sock) == Py_None) {
1684 _setSSLError("Underlying socket connection gone",
1685 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1686 return NULL;
1687 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001688 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001690 buf.obj = NULL;
1691 buf.buf = NULL;
1692 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001693 goto error;
1694
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001695 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1696 dest = PyBytes_FromStringAndSize(NULL, len);
1697 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001698 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001699 mem = PyBytes_AS_STRING(dest);
1700 }
1701 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001703 mem = buf.buf;
1704 if (len <= 0 || len > buf.len) {
1705 len = (int) buf.len;
1706 if (buf.len != len) {
1707 PyErr_SetString(PyExc_OverflowError,
1708 "maximum length can't fit in a C 'int'");
1709 goto error;
1710 }
1711 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 }
1713
1714 /* just in case the blocking state of the socket has been changed */
1715 nonblocking = (sock->sock_timeout >= 0.0);
1716 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1717 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 PySSL_BEGIN_ALLOW_THREADS
1721 count = SSL_read(self->ssl, mem, len);
1722 err = SSL_get_error(self->ssl, count);
1723 PySSL_END_ALLOW_THREADS
1724 if (PyErr_CheckSignals())
1725 goto error;
1726 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001727 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001729 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1731 (SSL_get_shutdown(self->ssl) ==
1732 SSL_RECEIVED_SHUTDOWN))
1733 {
1734 count = 0;
1735 goto done;
1736 } else {
1737 sockstate = SOCKET_OPERATION_OK;
1738 }
1739 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001740 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 "The read operation timed out");
1742 goto error;
1743 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1744 break;
1745 }
1746 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1747 if (count <= 0) {
1748 PySSL_SetError(self, count, __FILE__, __LINE__);
1749 goto error;
1750 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001751
1752done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001753 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001754 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001755 _PyBytes_Resize(&dest, count);
1756 return dest;
1757 }
1758 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 PyBuffer_Release(&buf);
1760 return PyLong_FromLong(count);
1761 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001762
1763error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001764 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001765 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001766 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001767 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001769 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001770}
1771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001772PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001773"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001774\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001775Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001776
Antoine Pitrou152efa22010-05-16 18:19:27 +00001777static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001778{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 int err, ssl_err, sockstate, nonblocking;
1780 int zeros = 0;
1781 PySocketSockObject *sock
1782 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 /* Guard against closed socket */
1785 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1786 _setSSLError("Underlying socket connection gone",
1787 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1788 return NULL;
1789 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001790 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791
1792 /* Just in case the blocking state of the socket has been changed */
1793 nonblocking = (sock->sock_timeout >= 0.0);
1794 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1795 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1796
1797 while (1) {
1798 PySSL_BEGIN_ALLOW_THREADS
1799 /* Disable read-ahead so that unwrap can work correctly.
1800 * Otherwise OpenSSL might read in too much data,
1801 * eating clear text data that happens to be
1802 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001803 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 * function is used and the shutdown_seen_zero != 0
1805 * condition is met.
1806 */
1807 if (self->shutdown_seen_zero)
1808 SSL_set_read_ahead(self->ssl, 0);
1809 err = SSL_shutdown(self->ssl);
1810 PySSL_END_ALLOW_THREADS
1811 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1812 if (err > 0)
1813 break;
1814 if (err == 0) {
1815 /* Don't loop endlessly; instead preserve legacy
1816 behaviour of trying SSL_shutdown() only twice.
1817 This looks necessary for OpenSSL < 0.9.8m */
1818 if (++zeros > 1)
1819 break;
1820 /* Shutdown was sent, now try receiving */
1821 self->shutdown_seen_zero = 1;
1822 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001823 }
1824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 /* Possibly retry shutdown until timeout or failure */
1826 ssl_err = SSL_get_error(self->ssl, err);
1827 if (ssl_err == SSL_ERROR_WANT_READ)
1828 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1829 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1830 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1831 else
1832 break;
1833 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1834 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001835 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 "The read operation timed out");
1837 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001838 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001840 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 }
1842 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1843 PyErr_SetString(PySSLErrorObject,
1844 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001845 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 }
1847 else if (sockstate != SOCKET_OPERATION_OK)
1848 /* Retain the SSL error code */
1849 break;
1850 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001851
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001852 if (err < 0) {
1853 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001856 else
1857 /* It's already INCREF'ed */
1858 return (PyObject *) sock;
1859
1860error:
1861 Py_DECREF(sock);
1862 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001863}
1864
1865PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1866"shutdown(s) -> socket\n\
1867\n\
1868Does the SSL shutdown handshake with the remote end, and returns\n\
1869the underlying socket object.");
1870
Antoine Pitroud6494802011-07-21 01:11:30 +02001871#if HAVE_OPENSSL_FINISHED
1872static PyObject *
1873PySSL_tls_unique_cb(PySSLSocket *self)
1874{
1875 PyObject *retval = NULL;
1876 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001877 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001878
1879 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1880 /* if session is resumed XOR we are the client */
1881 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1882 }
1883 else {
1884 /* if a new session XOR we are the server */
1885 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1886 }
1887
1888 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001889 if (len == 0)
1890 Py_RETURN_NONE;
1891
1892 retval = PyBytes_FromStringAndSize(buf, len);
1893
1894 return retval;
1895}
1896
1897PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1898"tls_unique_cb() -> bytes\n\
1899\n\
1900Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1901\n\
1902If the TLS handshake is not yet complete, None is returned");
1903
1904#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001905
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001906static PyGetSetDef ssl_getsetlist[] = {
1907 {"context", (getter) PySSL_get_context,
1908 (setter) PySSL_set_context, PySSL_set_context_doc},
1909 {NULL}, /* sentinel */
1910};
1911
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001912static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1914 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1915 PySSL_SSLwrite_doc},
1916 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1917 PySSL_SSLread_doc},
1918 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1919 PySSL_SSLpending_doc},
1920 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1921 PySSL_peercert_doc},
1922 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001923#ifdef OPENSSL_NPN_NEGOTIATED
1924 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1925#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001926 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1928 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001929#if HAVE_OPENSSL_FINISHED
1930 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1931 PySSL_tls_unique_cb_doc},
1932#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001934};
1935
Antoine Pitrou152efa22010-05-16 18:19:27 +00001936static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001937 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001938 "_ssl._SSLSocket", /*tp_name*/
1939 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 0, /*tp_itemsize*/
1941 /* methods */
1942 (destructor)PySSL_dealloc, /*tp_dealloc*/
1943 0, /*tp_print*/
1944 0, /*tp_getattr*/
1945 0, /*tp_setattr*/
1946 0, /*tp_reserved*/
1947 0, /*tp_repr*/
1948 0, /*tp_as_number*/
1949 0, /*tp_as_sequence*/
1950 0, /*tp_as_mapping*/
1951 0, /*tp_hash*/
1952 0, /*tp_call*/
1953 0, /*tp_str*/
1954 0, /*tp_getattro*/
1955 0, /*tp_setattro*/
1956 0, /*tp_as_buffer*/
1957 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1958 0, /*tp_doc*/
1959 0, /*tp_traverse*/
1960 0, /*tp_clear*/
1961 0, /*tp_richcompare*/
1962 0, /*tp_weaklistoffset*/
1963 0, /*tp_iter*/
1964 0, /*tp_iternext*/
1965 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001966 0, /*tp_members*/
1967 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001968};
1969
Antoine Pitrou152efa22010-05-16 18:19:27 +00001970
1971/*
1972 * _SSLContext objects
1973 */
1974
1975static PyObject *
1976context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1977{
1978 char *kwlist[] = {"protocol", NULL};
1979 PySSLContext *self;
1980 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001981 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001982 SSL_CTX *ctx = NULL;
1983
1984 if (!PyArg_ParseTupleAndKeywords(
1985 args, kwds, "i:_SSLContext", kwlist,
1986 &proto_version))
1987 return NULL;
1988
1989 PySSL_BEGIN_ALLOW_THREADS
1990 if (proto_version == PY_SSL_VERSION_TLS1)
1991 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001992#if HAVE_TLSv1_2
1993 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1994 ctx = SSL_CTX_new(TLSv1_1_method());
1995 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1996 ctx = SSL_CTX_new(TLSv1_2_method());
1997#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05001998#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00001999 else if (proto_version == PY_SSL_VERSION_SSL3)
2000 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002001#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002002#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002003 else if (proto_version == PY_SSL_VERSION_SSL2)
2004 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002005#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002006 else if (proto_version == PY_SSL_VERSION_SSL23)
2007 ctx = SSL_CTX_new(SSLv23_method());
2008 else
2009 proto_version = -1;
2010 PySSL_END_ALLOW_THREADS
2011
2012 if (proto_version == -1) {
2013 PyErr_SetString(PyExc_ValueError,
2014 "invalid protocol version");
2015 return NULL;
2016 }
2017 if (ctx == NULL) {
2018 PyErr_SetString(PySSLErrorObject,
2019 "failed to allocate SSL context");
2020 return NULL;
2021 }
2022
2023 assert(type != NULL && type->tp_alloc != NULL);
2024 self = (PySSLContext *) type->tp_alloc(type, 0);
2025 if (self == NULL) {
2026 SSL_CTX_free(ctx);
2027 return NULL;
2028 }
2029 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002030#ifdef OPENSSL_NPN_NEGOTIATED
2031 self->npn_protocols = NULL;
2032#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002033#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002034 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002035#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002036 /* Don't check host name by default */
2037 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002038 /* Defaults */
2039 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002040 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2041 if (proto_version != PY_SSL_VERSION_SSL2)
2042 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002043 if (proto_version != PY_SSL_VERSION_SSL3)
2044 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002045 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002046
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002047#ifndef OPENSSL_NO_ECDH
2048 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2049 prime256v1 by default. This is Apache mod_ssl's initialization
2050 policy, so we should be safe. */
2051#if defined(SSL_CTX_set_ecdh_auto)
2052 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2053#else
2054 {
2055 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2056 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2057 EC_KEY_free(key);
2058 }
2059#endif
2060#endif
2061
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002062#define SID_CTX "Python"
2063 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2064 sizeof(SID_CTX));
2065#undef SID_CTX
2066
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002067#ifdef X509_V_FLAG_TRUSTED_FIRST
2068 {
2069 /* Improve trust chain building when cross-signed intermediate
2070 certificates are present. See https://bugs.python.org/issue23476. */
2071 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2072 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2073 }
2074#endif
2075
Antoine Pitrou152efa22010-05-16 18:19:27 +00002076 return (PyObject *)self;
2077}
2078
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002079static int
2080context_traverse(PySSLContext *self, visitproc visit, void *arg)
2081{
2082#ifndef OPENSSL_NO_TLSEXT
2083 Py_VISIT(self->set_hostname);
2084#endif
2085 return 0;
2086}
2087
2088static int
2089context_clear(PySSLContext *self)
2090{
2091#ifndef OPENSSL_NO_TLSEXT
2092 Py_CLEAR(self->set_hostname);
2093#endif
2094 return 0;
2095}
2096
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097static void
2098context_dealloc(PySSLContext *self)
2099{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002100 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002101 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002102#ifdef OPENSSL_NPN_NEGOTIATED
2103 PyMem_Free(self->npn_protocols);
2104#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002105 Py_TYPE(self)->tp_free(self);
2106}
2107
2108static PyObject *
2109set_ciphers(PySSLContext *self, PyObject *args)
2110{
2111 int ret;
2112 const char *cipherlist;
2113
2114 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2115 return NULL;
2116 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2117 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002118 /* Clearing the error queue is necessary on some OpenSSL versions,
2119 otherwise the error will be reported again when another SSL call
2120 is done. */
2121 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002122 PyErr_SetString(PySSLErrorObject,
2123 "No cipher can be selected.");
2124 return NULL;
2125 }
2126 Py_RETURN_NONE;
2127}
2128
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002129#ifdef OPENSSL_NPN_NEGOTIATED
2130/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2131static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002132_advertiseNPN_cb(SSL *s,
2133 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002134 void *args)
2135{
2136 PySSLContext *ssl_ctx = (PySSLContext *) args;
2137
2138 if (ssl_ctx->npn_protocols == NULL) {
2139 *data = (unsigned char *) "";
2140 *len = 0;
2141 } else {
2142 *data = (unsigned char *) ssl_ctx->npn_protocols;
2143 *len = ssl_ctx->npn_protocols_len;
2144 }
2145
2146 return SSL_TLSEXT_ERR_OK;
2147}
2148/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2149static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002150_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002151 unsigned char **out, unsigned char *outlen,
2152 const unsigned char *server, unsigned int server_len,
2153 void *args)
2154{
2155 PySSLContext *ssl_ctx = (PySSLContext *) args;
2156
2157 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2158 int client_len;
2159
2160 if (client == NULL) {
2161 client = (unsigned char *) "";
2162 client_len = 0;
2163 } else {
2164 client_len = ssl_ctx->npn_protocols_len;
2165 }
2166
2167 SSL_select_next_proto(out, outlen,
2168 server, server_len,
2169 client, client_len);
2170
2171 return SSL_TLSEXT_ERR_OK;
2172}
2173#endif
2174
2175static PyObject *
2176_set_npn_protocols(PySSLContext *self, PyObject *args)
2177{
2178#ifdef OPENSSL_NPN_NEGOTIATED
2179 Py_buffer protos;
2180
2181 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2182 return NULL;
2183
Christian Heimes5cb31c92012-09-20 12:42:54 +02002184 if (self->npn_protocols != NULL) {
2185 PyMem_Free(self->npn_protocols);
2186 }
2187
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002188 self->npn_protocols = PyMem_Malloc(protos.len);
2189 if (self->npn_protocols == NULL) {
2190 PyBuffer_Release(&protos);
2191 return PyErr_NoMemory();
2192 }
2193 memcpy(self->npn_protocols, protos.buf, protos.len);
2194 self->npn_protocols_len = (int) protos.len;
2195
2196 /* set both server and client callbacks, because the context can
2197 * be used to create both types of sockets */
2198 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2199 _advertiseNPN_cb,
2200 self);
2201 SSL_CTX_set_next_proto_select_cb(self->ctx,
2202 _selectNPN_cb,
2203 self);
2204
2205 PyBuffer_Release(&protos);
2206 Py_RETURN_NONE;
2207#else
2208 PyErr_SetString(PyExc_NotImplementedError,
2209 "The NPN extension requires OpenSSL 1.0.1 or later.");
2210 return NULL;
2211#endif
2212}
2213
Antoine Pitrou152efa22010-05-16 18:19:27 +00002214static PyObject *
2215get_verify_mode(PySSLContext *self, void *c)
2216{
2217 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2218 case SSL_VERIFY_NONE:
2219 return PyLong_FromLong(PY_SSL_CERT_NONE);
2220 case SSL_VERIFY_PEER:
2221 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2222 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2223 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2224 }
2225 PyErr_SetString(PySSLErrorObject,
2226 "invalid return value from SSL_CTX_get_verify_mode");
2227 return NULL;
2228}
2229
2230static int
2231set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2232{
2233 int n, mode;
2234 if (!PyArg_Parse(arg, "i", &n))
2235 return -1;
2236 if (n == PY_SSL_CERT_NONE)
2237 mode = SSL_VERIFY_NONE;
2238 else if (n == PY_SSL_CERT_OPTIONAL)
2239 mode = SSL_VERIFY_PEER;
2240 else if (n == PY_SSL_CERT_REQUIRED)
2241 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2242 else {
2243 PyErr_SetString(PyExc_ValueError,
2244 "invalid value for verify_mode");
2245 return -1;
2246 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002247 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2248 PyErr_SetString(PyExc_ValueError,
2249 "Cannot set verify_mode to CERT_NONE when "
2250 "check_hostname is enabled.");
2251 return -1;
2252 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002253 SSL_CTX_set_verify(self->ctx, mode, NULL);
2254 return 0;
2255}
2256
Christian Heimes2427b502013-11-23 11:24:32 +01002257#ifdef HAVE_OPENSSL_VERIFY_PARAM
Antoine Pitrou152efa22010-05-16 18:19:27 +00002258static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002259get_verify_flags(PySSLContext *self, void *c)
2260{
2261 X509_STORE *store;
2262 unsigned long flags;
2263
2264 store = SSL_CTX_get_cert_store(self->ctx);
2265 flags = X509_VERIFY_PARAM_get_flags(store->param);
2266 return PyLong_FromUnsignedLong(flags);
2267}
2268
2269static int
2270set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2271{
2272 X509_STORE *store;
2273 unsigned long new_flags, flags, set, clear;
2274
2275 if (!PyArg_Parse(arg, "k", &new_flags))
2276 return -1;
2277 store = SSL_CTX_get_cert_store(self->ctx);
2278 flags = X509_VERIFY_PARAM_get_flags(store->param);
2279 clear = flags & ~new_flags;
2280 set = ~flags & new_flags;
2281 if (clear) {
2282 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2283 _setSSLError(NULL, 0, __FILE__, __LINE__);
2284 return -1;
2285 }
2286 }
2287 if (set) {
2288 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2289 _setSSLError(NULL, 0, __FILE__, __LINE__);
2290 return -1;
2291 }
2292 }
2293 return 0;
2294}
Christian Heimes2427b502013-11-23 11:24:32 +01002295#endif
Christian Heimes22587792013-11-21 23:56:13 +01002296
2297static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002298get_options(PySSLContext *self, void *c)
2299{
2300 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2301}
2302
2303static int
2304set_options(PySSLContext *self, PyObject *arg, void *c)
2305{
2306 long new_opts, opts, set, clear;
2307 if (!PyArg_Parse(arg, "l", &new_opts))
2308 return -1;
2309 opts = SSL_CTX_get_options(self->ctx);
2310 clear = opts & ~new_opts;
2311 set = ~opts & new_opts;
2312 if (clear) {
2313#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2314 SSL_CTX_clear_options(self->ctx, clear);
2315#else
2316 PyErr_SetString(PyExc_ValueError,
2317 "can't clear options before OpenSSL 0.9.8m");
2318 return -1;
2319#endif
2320 }
2321 if (set)
2322 SSL_CTX_set_options(self->ctx, set);
2323 return 0;
2324}
2325
Christian Heimes1aa9a752013-12-02 02:41:19 +01002326static PyObject *
2327get_check_hostname(PySSLContext *self, void *c)
2328{
2329 return PyBool_FromLong(self->check_hostname);
2330}
2331
2332static int
2333set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2334{
2335 int check_hostname;
2336 if (!PyArg_Parse(arg, "p", &check_hostname))
2337 return -1;
2338 if (check_hostname &&
2339 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2340 PyErr_SetString(PyExc_ValueError,
2341 "check_hostname needs a SSL context with either "
2342 "CERT_OPTIONAL or CERT_REQUIRED");
2343 return -1;
2344 }
2345 self->check_hostname = check_hostname;
2346 return 0;
2347}
2348
2349
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002350typedef struct {
2351 PyThreadState *thread_state;
2352 PyObject *callable;
2353 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002354 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002355 int error;
2356} _PySSLPasswordInfo;
2357
2358static int
2359_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2360 const char *bad_type_error)
2361{
2362 /* Set the password and size fields of a _PySSLPasswordInfo struct
2363 from a unicode, bytes, or byte array object.
2364 The password field will be dynamically allocated and must be freed
2365 by the caller */
2366 PyObject *password_bytes = NULL;
2367 const char *data = NULL;
2368 Py_ssize_t size;
2369
2370 if (PyUnicode_Check(password)) {
2371 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2372 if (!password_bytes) {
2373 goto error;
2374 }
2375 data = PyBytes_AS_STRING(password_bytes);
2376 size = PyBytes_GET_SIZE(password_bytes);
2377 } else if (PyBytes_Check(password)) {
2378 data = PyBytes_AS_STRING(password);
2379 size = PyBytes_GET_SIZE(password);
2380 } else if (PyByteArray_Check(password)) {
2381 data = PyByteArray_AS_STRING(password);
2382 size = PyByteArray_GET_SIZE(password);
2383 } else {
2384 PyErr_SetString(PyExc_TypeError, bad_type_error);
2385 goto error;
2386 }
2387
Victor Stinner9ee02032013-06-23 15:08:23 +02002388 if (size > (Py_ssize_t)INT_MAX) {
2389 PyErr_Format(PyExc_ValueError,
2390 "password cannot be longer than %d bytes", INT_MAX);
2391 goto error;
2392 }
2393
Victor Stinner11ebff22013-07-07 17:07:52 +02002394 PyMem_Free(pw_info->password);
2395 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002396 if (!pw_info->password) {
2397 PyErr_SetString(PyExc_MemoryError,
2398 "unable to allocate password buffer");
2399 goto error;
2400 }
2401 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002402 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002403
2404 Py_XDECREF(password_bytes);
2405 return 1;
2406
2407error:
2408 Py_XDECREF(password_bytes);
2409 return 0;
2410}
2411
2412static int
2413_password_callback(char *buf, int size, int rwflag, void *userdata)
2414{
2415 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2416 PyObject *fn_ret = NULL;
2417
2418 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2419
2420 if (pw_info->callable) {
2421 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2422 if (!fn_ret) {
2423 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2424 core python API, so we could use it to add a frame here */
2425 goto error;
2426 }
2427
2428 if (!_pwinfo_set(pw_info, fn_ret,
2429 "password callback must return a string")) {
2430 goto error;
2431 }
2432 Py_CLEAR(fn_ret);
2433 }
2434
2435 if (pw_info->size > size) {
2436 PyErr_Format(PyExc_ValueError,
2437 "password cannot be longer than %d bytes", size);
2438 goto error;
2439 }
2440
2441 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2442 memcpy(buf, pw_info->password, pw_info->size);
2443 return pw_info->size;
2444
2445error:
2446 Py_XDECREF(fn_ret);
2447 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2448 pw_info->error = 1;
2449 return -1;
2450}
2451
Antoine Pitroub5218772010-05-21 09:56:06 +00002452static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002453load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2454{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002455 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2456 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002457 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002458 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2459 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2460 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002461 int r;
2462
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002463 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002464 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002465 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002466 "O|OO:load_cert_chain", kwlist,
2467 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002468 return NULL;
2469 if (keyfile == Py_None)
2470 keyfile = NULL;
2471 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2472 PyErr_SetString(PyExc_TypeError,
2473 "certfile should be a valid filesystem path");
2474 return NULL;
2475 }
2476 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2477 PyErr_SetString(PyExc_TypeError,
2478 "keyfile should be a valid filesystem path");
2479 goto error;
2480 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002481 if (password && password != Py_None) {
2482 if (PyCallable_Check(password)) {
2483 pw_info.callable = password;
2484 } else if (!_pwinfo_set(&pw_info, password,
2485 "password should be a string or callable")) {
2486 goto error;
2487 }
2488 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2489 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2490 }
2491 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002492 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2493 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002494 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002495 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002496 if (pw_info.error) {
2497 ERR_clear_error();
2498 /* the password callback has already set the error information */
2499 }
2500 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002501 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002502 PyErr_SetFromErrno(PyExc_IOError);
2503 }
2504 else {
2505 _setSSLError(NULL, 0, __FILE__, __LINE__);
2506 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002507 goto error;
2508 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002509 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002510 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002511 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2512 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002513 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2514 Py_CLEAR(keyfile_bytes);
2515 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002516 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002517 if (pw_info.error) {
2518 ERR_clear_error();
2519 /* the password callback has already set the error information */
2520 }
2521 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002522 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002523 PyErr_SetFromErrno(PyExc_IOError);
2524 }
2525 else {
2526 _setSSLError(NULL, 0, __FILE__, __LINE__);
2527 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002528 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002529 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002530 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002531 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002532 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002533 if (r != 1) {
2534 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002535 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002536 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002537 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2538 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002539 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002540 Py_RETURN_NONE;
2541
2542error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002543 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2544 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002545 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002546 Py_XDECREF(keyfile_bytes);
2547 Py_XDECREF(certfile_bytes);
2548 return NULL;
2549}
2550
Christian Heimesefff7062013-11-21 03:35:02 +01002551/* internal helper function, returns -1 on error
2552 */
2553static int
2554_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2555 int filetype)
2556{
2557 BIO *biobuf = NULL;
2558 X509_STORE *store;
2559 int retval = 0, err, loaded = 0;
2560
2561 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2562
2563 if (len <= 0) {
2564 PyErr_SetString(PyExc_ValueError,
2565 "Empty certificate data");
2566 return -1;
2567 } else if (len > INT_MAX) {
2568 PyErr_SetString(PyExc_OverflowError,
2569 "Certificate data is too long.");
2570 return -1;
2571 }
2572
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002573 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002574 if (biobuf == NULL) {
2575 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2576 return -1;
2577 }
2578
2579 store = SSL_CTX_get_cert_store(self->ctx);
2580 assert(store != NULL);
2581
2582 while (1) {
2583 X509 *cert = NULL;
2584 int r;
2585
2586 if (filetype == SSL_FILETYPE_ASN1) {
2587 cert = d2i_X509_bio(biobuf, NULL);
2588 } else {
2589 cert = PEM_read_bio_X509(biobuf, NULL,
2590 self->ctx->default_passwd_callback,
2591 self->ctx->default_passwd_callback_userdata);
2592 }
2593 if (cert == NULL) {
2594 break;
2595 }
2596 r = X509_STORE_add_cert(store, cert);
2597 X509_free(cert);
2598 if (!r) {
2599 err = ERR_peek_last_error();
2600 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2601 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2602 /* cert already in hash table, not an error */
2603 ERR_clear_error();
2604 } else {
2605 break;
2606 }
2607 }
2608 loaded++;
2609 }
2610
2611 err = ERR_peek_last_error();
2612 if ((filetype == SSL_FILETYPE_ASN1) &&
2613 (loaded > 0) &&
2614 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2615 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2616 /* EOF ASN1 file, not an error */
2617 ERR_clear_error();
2618 retval = 0;
2619 } else if ((filetype == SSL_FILETYPE_PEM) &&
2620 (loaded > 0) &&
2621 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2622 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2623 /* EOF PEM file, not an error */
2624 ERR_clear_error();
2625 retval = 0;
2626 } else {
2627 _setSSLError(NULL, 0, __FILE__, __LINE__);
2628 retval = -1;
2629 }
2630
2631 BIO_free(biobuf);
2632 return retval;
2633}
2634
2635
Antoine Pitrou152efa22010-05-16 18:19:27 +00002636static PyObject *
2637load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2638{
Christian Heimesefff7062013-11-21 03:35:02 +01002639 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2640 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002641 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2642 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002643 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002644
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002645 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002646 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002647 "|OOO:load_verify_locations", kwlist,
2648 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002649 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002650
Antoine Pitrou152efa22010-05-16 18:19:27 +00002651 if (cafile == Py_None)
2652 cafile = NULL;
2653 if (capath == Py_None)
2654 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002655 if (cadata == Py_None)
2656 cadata = NULL;
2657
2658 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002659 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002660 "cafile, capath and cadata cannot be all omitted");
2661 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662 }
2663 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2664 PyErr_SetString(PyExc_TypeError,
2665 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002666 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002667 }
2668 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002669 PyErr_SetString(PyExc_TypeError,
2670 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002671 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002672 }
Christian Heimesefff7062013-11-21 03:35:02 +01002673
2674 /* validata cadata type and load cadata */
2675 if (cadata) {
2676 Py_buffer buf;
2677 PyObject *cadata_ascii = NULL;
2678
2679 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2680 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2681 PyBuffer_Release(&buf);
2682 PyErr_SetString(PyExc_TypeError,
2683 "cadata should be a contiguous buffer with "
2684 "a single dimension");
2685 goto error;
2686 }
2687 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2688 PyBuffer_Release(&buf);
2689 if (r == -1) {
2690 goto error;
2691 }
2692 } else {
2693 PyErr_Clear();
2694 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2695 if (cadata_ascii == NULL) {
2696 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02002697 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01002698 "bytes-like object");
2699 goto error;
2700 }
2701 r = _add_ca_certs(self,
2702 PyBytes_AS_STRING(cadata_ascii),
2703 PyBytes_GET_SIZE(cadata_ascii),
2704 SSL_FILETYPE_PEM);
2705 Py_DECREF(cadata_ascii);
2706 if (r == -1) {
2707 goto error;
2708 }
2709 }
2710 }
2711
2712 /* load cafile or capath */
2713 if (cafile || capath) {
2714 if (cafile)
2715 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2716 if (capath)
2717 capath_buf = PyBytes_AS_STRING(capath_bytes);
2718 PySSL_BEGIN_ALLOW_THREADS
2719 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2720 PySSL_END_ALLOW_THREADS
2721 if (r != 1) {
2722 ok = 0;
2723 if (errno != 0) {
2724 ERR_clear_error();
2725 PyErr_SetFromErrno(PyExc_IOError);
2726 }
2727 else {
2728 _setSSLError(NULL, 0, __FILE__, __LINE__);
2729 }
2730 goto error;
2731 }
2732 }
2733 goto end;
2734
2735 error:
2736 ok = 0;
2737 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002738 Py_XDECREF(cafile_bytes);
2739 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002740 if (ok) {
2741 Py_RETURN_NONE;
2742 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002743 return NULL;
2744 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745}
2746
2747static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002748load_dh_params(PySSLContext *self, PyObject *filepath)
2749{
2750 FILE *f;
2751 DH *dh;
2752
Victor Stinnerdaf45552013-08-28 00:53:59 +02002753 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002754 if (f == NULL) {
2755 if (!PyErr_Occurred())
2756 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2757 return NULL;
2758 }
2759 errno = 0;
2760 PySSL_BEGIN_ALLOW_THREADS
2761 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002762 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002763 PySSL_END_ALLOW_THREADS
2764 if (dh == NULL) {
2765 if (errno != 0) {
2766 ERR_clear_error();
2767 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2768 }
2769 else {
2770 _setSSLError(NULL, 0, __FILE__, __LINE__);
2771 }
2772 return NULL;
2773 }
2774 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2775 _setSSLError(NULL, 0, __FILE__, __LINE__);
2776 DH_free(dh);
2777 Py_RETURN_NONE;
2778}
2779
2780static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002781context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2782{
Antoine Pitroud5323212010-10-22 18:19:07 +00002783 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002784 PySocketSockObject *sock;
2785 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002786 char *hostname = NULL;
2787 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788
Antoine Pitroud5323212010-10-22 18:19:07 +00002789 /* server_hostname is either None (or absent), or to be encoded
2790 using the idna encoding. */
2791 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002793 &sock, &server_side,
2794 Py_TYPE(Py_None), &hostname_obj)) {
2795 PyErr_Clear();
2796 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2797 PySocketModule.Sock_Type,
2798 &sock, &server_side,
2799 "idna", &hostname))
2800 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002801 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002802
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002803 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002804 hostname);
2805 if (hostname != NULL)
2806 PyMem_Free(hostname);
2807 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808}
2809
Antoine Pitroub0182c82010-10-12 20:09:02 +00002810static PyObject *
2811session_stats(PySSLContext *self, PyObject *unused)
2812{
2813 int r;
2814 PyObject *value, *stats = PyDict_New();
2815 if (!stats)
2816 return NULL;
2817
2818#define ADD_STATS(SSL_NAME, KEY_NAME) \
2819 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2820 if (value == NULL) \
2821 goto error; \
2822 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2823 Py_DECREF(value); \
2824 if (r < 0) \
2825 goto error;
2826
2827 ADD_STATS(number, "number");
2828 ADD_STATS(connect, "connect");
2829 ADD_STATS(connect_good, "connect_good");
2830 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2831 ADD_STATS(accept, "accept");
2832 ADD_STATS(accept_good, "accept_good");
2833 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2834 ADD_STATS(accept, "accept");
2835 ADD_STATS(hits, "hits");
2836 ADD_STATS(misses, "misses");
2837 ADD_STATS(timeouts, "timeouts");
2838 ADD_STATS(cache_full, "cache_full");
2839
2840#undef ADD_STATS
2841
2842 return stats;
2843
2844error:
2845 Py_DECREF(stats);
2846 return NULL;
2847}
2848
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002849static PyObject *
2850set_default_verify_paths(PySSLContext *self, PyObject *unused)
2851{
2852 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2853 _setSSLError(NULL, 0, __FILE__, __LINE__);
2854 return NULL;
2855 }
2856 Py_RETURN_NONE;
2857}
2858
Antoine Pitrou501da612011-12-21 09:27:41 +01002859#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002860static PyObject *
2861set_ecdh_curve(PySSLContext *self, PyObject *name)
2862{
2863 PyObject *name_bytes;
2864 int nid;
2865 EC_KEY *key;
2866
2867 if (!PyUnicode_FSConverter(name, &name_bytes))
2868 return NULL;
2869 assert(PyBytes_Check(name_bytes));
2870 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2871 Py_DECREF(name_bytes);
2872 if (nid == 0) {
2873 PyErr_Format(PyExc_ValueError,
2874 "unknown elliptic curve name %R", name);
2875 return NULL;
2876 }
2877 key = EC_KEY_new_by_curve_name(nid);
2878 if (key == NULL) {
2879 _setSSLError(NULL, 0, __FILE__, __LINE__);
2880 return NULL;
2881 }
2882 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2883 EC_KEY_free(key);
2884 Py_RETURN_NONE;
2885}
Antoine Pitrou501da612011-12-21 09:27:41 +01002886#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002887
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002888#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002889static int
2890_servername_callback(SSL *s, int *al, void *args)
2891{
2892 int ret;
2893 PySSLContext *ssl_ctx = (PySSLContext *) args;
2894 PySSLSocket *ssl;
2895 PyObject *servername_o;
2896 PyObject *servername_idna;
2897 PyObject *result;
2898 /* The high-level ssl.SSLSocket object */
2899 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002900 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002901#ifdef WITH_THREAD
2902 PyGILState_STATE gstate = PyGILState_Ensure();
2903#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002904
2905 if (ssl_ctx->set_hostname == NULL) {
2906 /* remove race condition in this the call back while if removing the
2907 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002908#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002909 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002910#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002911 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002912 }
2913
2914 ssl = SSL_get_app_data(s);
2915 assert(PySSLSocket_Check(ssl));
2916 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2917 Py_INCREF(ssl_socket);
2918 if (ssl_socket == Py_None) {
2919 goto error;
2920 }
Victor Stinner7e001512013-06-25 00:44:31 +02002921
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002922 if (servername == NULL) {
2923 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2924 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002925 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002926 else {
2927 servername_o = PyBytes_FromString(servername);
2928 if (servername_o == NULL) {
2929 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2930 goto error;
2931 }
2932 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2933 if (servername_idna == NULL) {
2934 PyErr_WriteUnraisable(servername_o);
2935 Py_DECREF(servername_o);
2936 goto error;
2937 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002938 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002939 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2940 servername_idna, ssl_ctx, NULL);
2941 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002942 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002943 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002944
2945 if (result == NULL) {
2946 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2947 *al = SSL_AD_HANDSHAKE_FAILURE;
2948 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2949 }
2950 else {
2951 if (result != Py_None) {
2952 *al = (int) PyLong_AsLong(result);
2953 if (PyErr_Occurred()) {
2954 PyErr_WriteUnraisable(result);
2955 *al = SSL_AD_INTERNAL_ERROR;
2956 }
2957 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2958 }
2959 else {
2960 ret = SSL_TLSEXT_ERR_OK;
2961 }
2962 Py_DECREF(result);
2963 }
2964
Stefan Krah20d60802013-01-17 17:07:17 +01002965#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002966 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002967#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002968 return ret;
2969
2970error:
2971 Py_DECREF(ssl_socket);
2972 *al = SSL_AD_INTERNAL_ERROR;
2973 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002974#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002975 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002976#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002977 return ret;
2978}
Antoine Pitroua5963382013-03-30 16:39:00 +01002979#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002980
2981PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2982"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002983\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002984This sets a callback that will be called when a server name is provided by\n\
2985the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002986\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002987If the argument is None then the callback is disabled. The method is called\n\
2988with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002989See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002990
2991static PyObject *
2992set_servername_callback(PySSLContext *self, PyObject *args)
2993{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002994#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002995 PyObject *cb;
2996
2997 if (!PyArg_ParseTuple(args, "O", &cb))
2998 return NULL;
2999
3000 Py_CLEAR(self->set_hostname);
3001 if (cb == Py_None) {
3002 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3003 }
3004 else {
3005 if (!PyCallable_Check(cb)) {
3006 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3007 PyErr_SetString(PyExc_TypeError,
3008 "not a callable object");
3009 return NULL;
3010 }
3011 Py_INCREF(cb);
3012 self->set_hostname = cb;
3013 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3014 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3015 }
3016 Py_RETURN_NONE;
3017#else
3018 PyErr_SetString(PyExc_NotImplementedError,
3019 "The TLS extension servername callback, "
3020 "SSL_CTX_set_tlsext_servername_callback, "
3021 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003022 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003023#endif
3024}
3025
Christian Heimes9a5395a2013-06-17 15:44:12 +02003026PyDoc_STRVAR(PySSL_get_stats_doc,
3027"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3028\n\
3029Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3030CA extension and certificate revocation lists inside the context's cert\n\
3031store.\n\
3032NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3033been used at least once.");
3034
3035static PyObject *
3036cert_store_stats(PySSLContext *self)
3037{
3038 X509_STORE *store;
3039 X509_OBJECT *obj;
3040 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3041
3042 store = SSL_CTX_get_cert_store(self->ctx);
3043 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3044 obj = sk_X509_OBJECT_value(store->objs, i);
3045 switch (obj->type) {
3046 case X509_LU_X509:
3047 x509++;
3048 if (X509_check_ca(obj->data.x509)) {
3049 ca++;
3050 }
3051 break;
3052 case X509_LU_CRL:
3053 crl++;
3054 break;
3055 case X509_LU_PKEY:
3056 pkey++;
3057 break;
3058 default:
3059 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3060 * As far as I can tell they are internal states and never
3061 * stored in a cert store */
3062 break;
3063 }
3064 }
3065 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3066 "x509_ca", ca);
3067}
3068
3069PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003070"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003071\n\
3072Returns a list of dicts with information of loaded CA certs. If the\n\
3073optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3074NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3075been used at least once.");
3076
3077static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003078get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003079{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003080 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003081 X509_STORE *store;
3082 PyObject *ci = NULL, *rlist = NULL;
3083 int i;
3084 int binary_mode = 0;
3085
Christian Heimesf22e8e52013-11-22 02:22:51 +01003086 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3087 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003088 return NULL;
3089 }
3090
3091 if ((rlist = PyList_New(0)) == NULL) {
3092 return NULL;
3093 }
3094
3095 store = SSL_CTX_get_cert_store(self->ctx);
3096 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3097 X509_OBJECT *obj;
3098 X509 *cert;
3099
3100 obj = sk_X509_OBJECT_value(store->objs, i);
3101 if (obj->type != X509_LU_X509) {
3102 /* not a x509 cert */
3103 continue;
3104 }
3105 /* CA for any purpose */
3106 cert = obj->data.x509;
3107 if (!X509_check_ca(cert)) {
3108 continue;
3109 }
3110 if (binary_mode) {
3111 ci = _certificate_to_der(cert);
3112 } else {
3113 ci = _decode_certificate(cert);
3114 }
3115 if (ci == NULL) {
3116 goto error;
3117 }
3118 if (PyList_Append(rlist, ci) == -1) {
3119 goto error;
3120 }
3121 Py_CLEAR(ci);
3122 }
3123 return rlist;
3124
3125 error:
3126 Py_XDECREF(ci);
3127 Py_XDECREF(rlist);
3128 return NULL;
3129}
3130
3131
Antoine Pitrou152efa22010-05-16 18:19:27 +00003132static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003133 {"check_hostname", (getter) get_check_hostname,
3134 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003135 {"options", (getter) get_options,
3136 (setter) set_options, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003137#ifdef HAVE_OPENSSL_VERIFY_PARAM
Christian Heimes22587792013-11-21 23:56:13 +01003138 {"verify_flags", (getter) get_verify_flags,
3139 (setter) set_verify_flags, NULL},
Christian Heimes2427b502013-11-23 11:24:32 +01003140#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003141 {"verify_mode", (getter) get_verify_mode,
3142 (setter) set_verify_mode, NULL},
3143 {NULL}, /* sentinel */
3144};
3145
3146static struct PyMethodDef context_methods[] = {
3147 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3148 METH_VARARGS | METH_KEYWORDS, NULL},
3149 {"set_ciphers", (PyCFunction) set_ciphers,
3150 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003151 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3152 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003153 {"load_cert_chain", (PyCFunction) load_cert_chain,
3154 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003155 {"load_dh_params", (PyCFunction) load_dh_params,
3156 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003157 {"load_verify_locations", (PyCFunction) load_verify_locations,
3158 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003159 {"session_stats", (PyCFunction) session_stats,
3160 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003161 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3162 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003163#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003164 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3165 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003166#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003167 {"set_servername_callback", (PyCFunction) set_servername_callback,
3168 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003169 {"cert_store_stats", (PyCFunction) cert_store_stats,
3170 METH_NOARGS, PySSL_get_stats_doc},
3171 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003172 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003173 {NULL, NULL} /* sentinel */
3174};
3175
3176static PyTypeObject PySSLContext_Type = {
3177 PyVarObject_HEAD_INIT(NULL, 0)
3178 "_ssl._SSLContext", /*tp_name*/
3179 sizeof(PySSLContext), /*tp_basicsize*/
3180 0, /*tp_itemsize*/
3181 (destructor)context_dealloc, /*tp_dealloc*/
3182 0, /*tp_print*/
3183 0, /*tp_getattr*/
3184 0, /*tp_setattr*/
3185 0, /*tp_reserved*/
3186 0, /*tp_repr*/
3187 0, /*tp_as_number*/
3188 0, /*tp_as_sequence*/
3189 0, /*tp_as_mapping*/
3190 0, /*tp_hash*/
3191 0, /*tp_call*/
3192 0, /*tp_str*/
3193 0, /*tp_getattro*/
3194 0, /*tp_setattro*/
3195 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003196 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003197 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003198 (traverseproc) context_traverse, /*tp_traverse*/
3199 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003200 0, /*tp_richcompare*/
3201 0, /*tp_weaklistoffset*/
3202 0, /*tp_iter*/
3203 0, /*tp_iternext*/
3204 context_methods, /*tp_methods*/
3205 0, /*tp_members*/
3206 context_getsetlist, /*tp_getset*/
3207 0, /*tp_base*/
3208 0, /*tp_dict*/
3209 0, /*tp_descr_get*/
3210 0, /*tp_descr_set*/
3211 0, /*tp_dictoffset*/
3212 0, /*tp_init*/
3213 0, /*tp_alloc*/
3214 context_new, /*tp_new*/
3215};
3216
3217
3218
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003219#ifdef HAVE_OPENSSL_RAND
3220
3221/* helper routines for seeding the SSL PRNG */
3222static PyObject *
3223PySSL_RAND_add(PyObject *self, PyObject *args)
3224{
3225 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003226 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003227 double entropy;
3228
3229 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003230 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003231 do {
3232 written = Py_MIN(len, INT_MAX);
3233 RAND_add(buf, (int)written, entropy);
3234 buf += written;
3235 len -= written;
3236 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003237 Py_INCREF(Py_None);
3238 return Py_None;
3239}
3240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003241PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003242"RAND_add(string, entropy)\n\
3243\n\
3244Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003245bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003246
3247static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003248PySSL_RAND(int len, int pseudo)
3249{
3250 int ok;
3251 PyObject *bytes;
3252 unsigned long err;
3253 const char *errstr;
3254 PyObject *v;
3255
Victor Stinner1e81a392013-12-19 16:47:04 +01003256 if (len < 0) {
3257 PyErr_SetString(PyExc_ValueError, "num must be positive");
3258 return NULL;
3259 }
3260
Victor Stinner99c8b162011-05-24 12:05:19 +02003261 bytes = PyBytes_FromStringAndSize(NULL, len);
3262 if (bytes == NULL)
3263 return NULL;
3264 if (pseudo) {
3265 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3266 if (ok == 0 || ok == 1)
3267 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3268 }
3269 else {
3270 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3271 if (ok == 1)
3272 return bytes;
3273 }
3274 Py_DECREF(bytes);
3275
3276 err = ERR_get_error();
3277 errstr = ERR_reason_error_string(err);
3278 v = Py_BuildValue("(ks)", err, errstr);
3279 if (v != NULL) {
3280 PyErr_SetObject(PySSLErrorObject, v);
3281 Py_DECREF(v);
3282 }
3283 return NULL;
3284}
3285
3286static PyObject *
3287PySSL_RAND_bytes(PyObject *self, PyObject *args)
3288{
3289 int len;
3290 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3291 return NULL;
3292 return PySSL_RAND(len, 0);
3293}
3294
3295PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3296"RAND_bytes(n) -> bytes\n\
3297\n\
3298Generate n cryptographically strong pseudo-random bytes.");
3299
3300static PyObject *
3301PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3302{
3303 int len;
3304 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3305 return NULL;
3306 return PySSL_RAND(len, 1);
3307}
3308
3309PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3310"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3311\n\
3312Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3313generated are cryptographically strong.");
3314
3315static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003316PySSL_RAND_status(PyObject *self)
3317{
Christian Heimes217cfd12007-12-02 14:31:20 +00003318 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003319}
3320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003321PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003322"RAND_status() -> 0 or 1\n\
3323\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003324Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3325It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3326using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003327
Victor Stinnerfcfed192015-01-06 13:54:58 +01003328#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003329static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003330PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003331{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003332 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003333 int bytes;
3334
Jesus Ceac8754a12012-09-11 02:00:58 +02003335 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003336 PyUnicode_FSConverter, &path))
3337 return NULL;
3338
3339 bytes = RAND_egd(PyBytes_AsString(path));
3340 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003341 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003342 PyErr_SetString(PySSLErrorObject,
3343 "EGD connection failed or EGD did not return "
3344 "enough data to seed the PRNG");
3345 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003346 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003347 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003348}
3349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003350PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003351"RAND_egd(path) -> bytes\n\
3352\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003353Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3354Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003355fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerfcfed192015-01-06 13:54:58 +01003356#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003357
Christian Heimesf77b4b22013-08-21 13:26:05 +02003358#endif /* HAVE_OPENSSL_RAND */
3359
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003360
Christian Heimes6d7ad132013-06-09 18:02:55 +02003361PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3362"get_default_verify_paths() -> tuple\n\
3363\n\
3364Return search paths and environment vars that are used by SSLContext's\n\
3365set_default_verify_paths() to load default CAs. The values are\n\
3366'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3367
3368static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003369PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003370{
3371 PyObject *ofile_env = NULL;
3372 PyObject *ofile = NULL;
3373 PyObject *odir_env = NULL;
3374 PyObject *odir = NULL;
3375
Benjamin Petersond113c962015-07-18 10:59:13 -07003376#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003377 const char *tmp = (info); \
3378 target = NULL; \
3379 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3380 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3381 target = PyBytes_FromString(tmp); } \
3382 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08003383 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02003384
Benjamin Petersond113c962015-07-18 10:59:13 -07003385 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3386 CONVERT(X509_get_default_cert_file(), ofile);
3387 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3388 CONVERT(X509_get_default_cert_dir(), odir);
3389#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02003390
Christian Heimes200bb1b2013-06-14 15:14:29 +02003391 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003392
3393 error:
3394 Py_XDECREF(ofile_env);
3395 Py_XDECREF(ofile);
3396 Py_XDECREF(odir_env);
3397 Py_XDECREF(odir);
3398 return NULL;
3399}
3400
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003401static PyObject*
3402asn1obj2py(ASN1_OBJECT *obj)
3403{
3404 int nid;
3405 const char *ln, *sn;
3406 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003407 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003408
3409 nid = OBJ_obj2nid(obj);
3410 if (nid == NID_undef) {
3411 PyErr_Format(PyExc_ValueError, "Unknown object");
3412 return NULL;
3413 }
3414 sn = OBJ_nid2sn(nid);
3415 ln = OBJ_nid2ln(nid);
3416 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3417 if (buflen < 0) {
3418 _setSSLError(NULL, 0, __FILE__, __LINE__);
3419 return NULL;
3420 }
3421 if (buflen) {
3422 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3423 } else {
3424 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3425 }
3426}
3427
3428PyDoc_STRVAR(PySSL_txt2obj_doc,
3429"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3430\n\
3431Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3432objects are looked up by OID. With name=True short and long name are also\n\
3433matched.");
3434
3435static PyObject*
3436PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3437{
3438 char *kwlist[] = {"txt", "name", NULL};
3439 PyObject *result = NULL;
3440 char *txt;
3441 int name = 0;
3442 ASN1_OBJECT *obj;
3443
3444 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3445 kwlist, &txt, &name)) {
3446 return NULL;
3447 }
3448 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3449 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003450 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003451 return NULL;
3452 }
3453 result = asn1obj2py(obj);
3454 ASN1_OBJECT_free(obj);
3455 return result;
3456}
3457
3458PyDoc_STRVAR(PySSL_nid2obj_doc,
3459"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3460\n\
3461Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3462
3463static PyObject*
3464PySSL_nid2obj(PyObject *self, PyObject *args)
3465{
3466 PyObject *result = NULL;
3467 int nid;
3468 ASN1_OBJECT *obj;
3469
3470 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3471 return NULL;
3472 }
3473 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003474 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003475 return NULL;
3476 }
3477 obj = OBJ_nid2obj(nid);
3478 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003479 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003480 return NULL;
3481 }
3482 result = asn1obj2py(obj);
3483 ASN1_OBJECT_free(obj);
3484 return result;
3485}
3486
Christian Heimes46bebee2013-06-09 19:03:31 +02003487#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003488
3489static PyObject*
3490certEncodingType(DWORD encodingType)
3491{
3492 static PyObject *x509_asn = NULL;
3493 static PyObject *pkcs_7_asn = NULL;
3494
3495 if (x509_asn == NULL) {
3496 x509_asn = PyUnicode_InternFromString("x509_asn");
3497 if (x509_asn == NULL)
3498 return NULL;
3499 }
3500 if (pkcs_7_asn == NULL) {
3501 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3502 if (pkcs_7_asn == NULL)
3503 return NULL;
3504 }
3505 switch(encodingType) {
3506 case X509_ASN_ENCODING:
3507 Py_INCREF(x509_asn);
3508 return x509_asn;
3509 case PKCS_7_ASN_ENCODING:
3510 Py_INCREF(pkcs_7_asn);
3511 return pkcs_7_asn;
3512 default:
3513 return PyLong_FromLong(encodingType);
3514 }
3515}
3516
3517static PyObject*
3518parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3519{
3520 CERT_ENHKEY_USAGE *usage;
3521 DWORD size, error, i;
3522 PyObject *retval;
3523
3524 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3525 error = GetLastError();
3526 if (error == CRYPT_E_NOT_FOUND) {
3527 Py_RETURN_TRUE;
3528 }
3529 return PyErr_SetFromWindowsErr(error);
3530 }
3531
3532 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3533 if (usage == NULL) {
3534 return PyErr_NoMemory();
3535 }
3536
3537 /* Now get the actual enhanced usage property */
3538 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3539 PyMem_Free(usage);
3540 error = GetLastError();
3541 if (error == CRYPT_E_NOT_FOUND) {
3542 Py_RETURN_TRUE;
3543 }
3544 return PyErr_SetFromWindowsErr(error);
3545 }
3546 retval = PySet_New(NULL);
3547 if (retval == NULL) {
3548 goto error;
3549 }
3550 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3551 if (usage->rgpszUsageIdentifier[i]) {
3552 PyObject *oid;
3553 int err;
3554 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
3555 if (oid == NULL) {
3556 Py_CLEAR(retval);
3557 goto error;
3558 }
3559 err = PySet_Add(retval, oid);
3560 Py_DECREF(oid);
3561 if (err == -1) {
3562 Py_CLEAR(retval);
3563 goto error;
3564 }
3565 }
3566 }
3567 error:
3568 PyMem_Free(usage);
3569 return retval;
3570}
3571
3572PyDoc_STRVAR(PySSL_enum_certificates_doc,
3573"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003574\n\
3575Retrieve certificates from Windows' cert store. store_name may be one of\n\
3576'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003577The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02003578encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01003579PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3580boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003581
Christian Heimes46bebee2013-06-09 19:03:31 +02003582static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01003583PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02003584{
Christian Heimes44109d72013-11-22 01:51:30 +01003585 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02003586 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02003587 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01003588 PCCERT_CONTEXT pCertCtx = NULL;
3589 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003590 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02003591
Benjamin Peterson43b84272015-04-06 13:05:22 -04003592 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Christian Heimes44109d72013-11-22 01:51:30 +01003593 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003594 return NULL;
3595 }
Christian Heimes44109d72013-11-22 01:51:30 +01003596 result = PyList_New(0);
3597 if (result == NULL) {
3598 return NULL;
3599 }
3600 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3601 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003602 Py_DECREF(result);
3603 return PyErr_SetFromWindowsErr(GetLastError());
3604 }
3605
Christian Heimes44109d72013-11-22 01:51:30 +01003606 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3607 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3608 pCertCtx->cbCertEncoded);
3609 if (!cert) {
3610 Py_CLEAR(result);
3611 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003612 }
Christian Heimes44109d72013-11-22 01:51:30 +01003613 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3614 Py_CLEAR(result);
3615 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003616 }
Christian Heimes44109d72013-11-22 01:51:30 +01003617 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3618 if (keyusage == Py_True) {
3619 Py_DECREF(keyusage);
3620 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02003621 }
Christian Heimes44109d72013-11-22 01:51:30 +01003622 if (keyusage == NULL) {
3623 Py_CLEAR(result);
3624 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02003625 }
Christian Heimes44109d72013-11-22 01:51:30 +01003626 if ((tup = PyTuple_New(3)) == NULL) {
3627 Py_CLEAR(result);
3628 break;
3629 }
3630 PyTuple_SET_ITEM(tup, 0, cert);
3631 cert = NULL;
3632 PyTuple_SET_ITEM(tup, 1, enc);
3633 enc = NULL;
3634 PyTuple_SET_ITEM(tup, 2, keyusage);
3635 keyusage = NULL;
3636 if (PyList_Append(result, tup) < 0) {
3637 Py_CLEAR(result);
3638 break;
3639 }
3640 Py_CLEAR(tup);
3641 }
3642 if (pCertCtx) {
3643 /* loop ended with an error, need to clean up context manually */
3644 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02003645 }
3646
3647 /* In error cases cert, enc and tup may not be NULL */
3648 Py_XDECREF(cert);
3649 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01003650 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02003651 Py_XDECREF(tup);
3652
3653 if (!CertCloseStore(hStore, 0)) {
3654 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01003655 Py_XDECREF(result);
3656 return PyErr_SetFromWindowsErr(GetLastError());
3657 }
3658 return result;
3659}
3660
3661PyDoc_STRVAR(PySSL_enum_crls_doc,
3662"enum_crls(store_name) -> []\n\
3663\n\
3664Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3665'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3666The function returns a list of (bytes, encoding_type) tuples. The\n\
3667encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3668PKCS_7_ASN_ENCODING.");
3669
3670static PyObject *
3671PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3672{
3673 char *kwlist[] = {"store_name", NULL};
3674 char *store_name;
3675 HCERTSTORE hStore = NULL;
3676 PCCRL_CONTEXT pCrlCtx = NULL;
3677 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3678 PyObject *result = NULL;
3679
Benjamin Peterson43b84272015-04-06 13:05:22 -04003680 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Christian Heimes44109d72013-11-22 01:51:30 +01003681 kwlist, &store_name)) {
3682 return NULL;
3683 }
3684 result = PyList_New(0);
3685 if (result == NULL) {
3686 return NULL;
3687 }
3688 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3689 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003690 Py_DECREF(result);
3691 return PyErr_SetFromWindowsErr(GetLastError());
3692 }
Christian Heimes44109d72013-11-22 01:51:30 +01003693
3694 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3695 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3696 pCrlCtx->cbCrlEncoded);
3697 if (!crl) {
3698 Py_CLEAR(result);
3699 break;
3700 }
3701 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3702 Py_CLEAR(result);
3703 break;
3704 }
3705 if ((tup = PyTuple_New(2)) == NULL) {
3706 Py_CLEAR(result);
3707 break;
3708 }
3709 PyTuple_SET_ITEM(tup, 0, crl);
3710 crl = NULL;
3711 PyTuple_SET_ITEM(tup, 1, enc);
3712 enc = NULL;
3713
3714 if (PyList_Append(result, tup) < 0) {
3715 Py_CLEAR(result);
3716 break;
3717 }
3718 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02003719 }
Christian Heimes44109d72013-11-22 01:51:30 +01003720 if (pCrlCtx) {
3721 /* loop ended with an error, need to clean up context manually */
3722 CertFreeCRLContext(pCrlCtx);
3723 }
3724
3725 /* In error cases cert, enc and tup may not be NULL */
3726 Py_XDECREF(crl);
3727 Py_XDECREF(enc);
3728 Py_XDECREF(tup);
3729
3730 if (!CertCloseStore(hStore, 0)) {
3731 /* This error case might shadow another exception.*/
3732 Py_XDECREF(result);
3733 return PyErr_SetFromWindowsErr(GetLastError());
3734 }
3735 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02003736}
Christian Heimes44109d72013-11-22 01:51:30 +01003737
3738#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00003739
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003740/* List of functions exported by this module. */
3741
3742static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003743 {"_test_decode_cert", PySSL_test_decode_certificate,
3744 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003745#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003746 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3747 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003748 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3749 PySSL_RAND_bytes_doc},
3750 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3751 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerfcfed192015-01-06 13:54:58 +01003752#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003753 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003754 PySSL_RAND_egd_doc},
Victor Stinnerfcfed192015-01-06 13:54:58 +01003755#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003756 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3757 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003758#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003759 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003760 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003761#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003762 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3763 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3764 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3765 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003766#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003767 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3768 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3769 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3770 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003771 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003772};
3773
3774
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003775#ifdef WITH_THREAD
3776
3777/* an implementation of OpenSSL threading operations in terms
3778 of the Python C thread library */
3779
3780static PyThread_type_lock *_ssl_locks = NULL;
3781
Christian Heimes4d98ca92013-08-19 17:36:29 +02003782#if OPENSSL_VERSION_NUMBER >= 0x10000000
3783/* use new CRYPTO_THREADID API. */
3784static void
3785_ssl_threadid_callback(CRYPTO_THREADID *id)
3786{
3787 CRYPTO_THREADID_set_numeric(id,
3788 (unsigned long)PyThread_get_thread_ident());
3789}
3790#else
3791/* deprecated CRYPTO_set_id_callback() API. */
3792static unsigned long
3793_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003794 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003795}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003796#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003797
Bill Janssen6e027db2007-11-15 22:23:56 +00003798static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003799 (int mode, int n, const char *file, int line) {
3800 /* this function is needed to perform locking on shared data
3801 structures. (Note that OpenSSL uses a number of global data
3802 structures that will be implicitly shared whenever multiple
3803 threads use OpenSSL.) Multi-threaded applications will
3804 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003806 locking_function() must be able to handle up to
3807 CRYPTO_num_locks() different mutex locks. It sets the n-th
3808 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003810 file and line are the file number of the function setting the
3811 lock. They can be useful for debugging.
3812 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003814 if ((_ssl_locks == NULL) ||
3815 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3816 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003818 if (mode & CRYPTO_LOCK) {
3819 PyThread_acquire_lock(_ssl_locks[n], 1);
3820 } else {
3821 PyThread_release_lock(_ssl_locks[n]);
3822 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003823}
3824
3825static int _setup_ssl_threads(void) {
3826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003827 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003829 if (_ssl_locks == NULL) {
3830 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003831 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3832 if (_ssl_locks == NULL) {
3833 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003834 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003835 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003836 memset(_ssl_locks, 0,
3837 sizeof(PyThread_type_lock) * _ssl_locks_count);
3838 for (i = 0; i < _ssl_locks_count; i++) {
3839 _ssl_locks[i] = PyThread_allocate_lock();
3840 if (_ssl_locks[i] == NULL) {
3841 unsigned int j;
3842 for (j = 0; j < i; j++) {
3843 PyThread_free_lock(_ssl_locks[j]);
3844 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003845 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003846 return 0;
3847 }
3848 }
3849 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003850#if OPENSSL_VERSION_NUMBER >= 0x10000000
3851 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3852#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003853 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003854#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003855 }
3856 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003857}
3858
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003859#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003860
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003861PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003862"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003863for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003864
Martin v. Löwis1a214512008-06-11 05:26:20 +00003865
3866static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003867 PyModuleDef_HEAD_INIT,
3868 "_ssl",
3869 module_doc,
3870 -1,
3871 PySSL_methods,
3872 NULL,
3873 NULL,
3874 NULL,
3875 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003876};
3877
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003878
3879static void
3880parse_openssl_version(unsigned long libver,
3881 unsigned int *major, unsigned int *minor,
3882 unsigned int *fix, unsigned int *patch,
3883 unsigned int *status)
3884{
3885 *status = libver & 0xF;
3886 libver >>= 4;
3887 *patch = libver & 0xFF;
3888 libver >>= 8;
3889 *fix = libver & 0xFF;
3890 libver >>= 8;
3891 *minor = libver & 0xFF;
3892 libver >>= 8;
3893 *major = libver & 0xFF;
3894}
3895
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003896PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003897PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003898{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003899 PyObject *m, *d, *r;
3900 unsigned long libver;
3901 unsigned int major, minor, fix, patch, status;
3902 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003903 struct py_ssl_error_code *errcode;
3904 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003905
Antoine Pitrou152efa22010-05-16 18:19:27 +00003906 if (PyType_Ready(&PySSLContext_Type) < 0)
3907 return NULL;
3908 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003909 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003911 m = PyModule_Create(&_sslmodule);
3912 if (m == NULL)
3913 return NULL;
3914 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003916 /* Load _socket module and its C API */
3917 socket_api = PySocketModule_ImportModuleAndAPI();
3918 if (!socket_api)
3919 return NULL;
3920 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003922 /* Init OpenSSL */
3923 SSL_load_error_strings();
3924 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003925#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003926 /* note that this will start threading if not already started */
3927 if (!_setup_ssl_threads()) {
3928 return NULL;
3929 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003930#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003931 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003933 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003934 sslerror_type_slots[0].pfunc = PyExc_OSError;
3935 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003936 if (PySSLErrorObject == NULL)
3937 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003938
Antoine Pitrou41032a62011-10-27 23:56:55 +02003939 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3940 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3941 PySSLErrorObject, NULL);
3942 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3943 "ssl.SSLWantReadError", SSLWantReadError_doc,
3944 PySSLErrorObject, NULL);
3945 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3946 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3947 PySSLErrorObject, NULL);
3948 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3949 "ssl.SSLSyscallError", SSLSyscallError_doc,
3950 PySSLErrorObject, NULL);
3951 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3952 "ssl.SSLEOFError", SSLEOFError_doc,
3953 PySSLErrorObject, NULL);
3954 if (PySSLZeroReturnErrorObject == NULL
3955 || PySSLWantReadErrorObject == NULL
3956 || PySSLWantWriteErrorObject == NULL
3957 || PySSLSyscallErrorObject == NULL
3958 || PySSLEOFErrorObject == NULL)
3959 return NULL;
3960 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3961 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3962 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3963 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3964 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3965 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003966 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003967 if (PyDict_SetItemString(d, "_SSLContext",
3968 (PyObject *)&PySSLContext_Type) != 0)
3969 return NULL;
3970 if (PyDict_SetItemString(d, "_SSLSocket",
3971 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003972 return NULL;
3973 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3974 PY_SSL_ERROR_ZERO_RETURN);
3975 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3976 PY_SSL_ERROR_WANT_READ);
3977 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3978 PY_SSL_ERROR_WANT_WRITE);
3979 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3980 PY_SSL_ERROR_WANT_X509_LOOKUP);
3981 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3982 PY_SSL_ERROR_SYSCALL);
3983 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3984 PY_SSL_ERROR_SSL);
3985 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3986 PY_SSL_ERROR_WANT_CONNECT);
3987 /* non ssl.h errorcodes */
3988 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3989 PY_SSL_ERROR_EOF);
3990 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3991 PY_SSL_ERROR_INVALID_ERROR_CODE);
3992 /* cert requirements */
3993 PyModule_AddIntConstant(m, "CERT_NONE",
3994 PY_SSL_CERT_NONE);
3995 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3996 PY_SSL_CERT_OPTIONAL);
3997 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3998 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01003999 /* CRL verification for verification_flags */
4000 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4001 0);
4002 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4003 X509_V_FLAG_CRL_CHECK);
4004 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4005 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4006 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4007 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004008#ifdef X509_V_FLAG_TRUSTED_FIRST
4009 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4010 X509_V_FLAG_TRUSTED_FIRST);
4011#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004012
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004013 /* Alert Descriptions from ssl.h */
4014 /* note RESERVED constants no longer intended for use have been removed */
4015 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4016
4017#define ADD_AD_CONSTANT(s) \
4018 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4019 SSL_AD_##s)
4020
4021 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4022 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4023 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4024 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4025 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4026 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4027 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4028 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4029 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4030 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4031 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4032 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4033 ADD_AD_CONSTANT(UNKNOWN_CA);
4034 ADD_AD_CONSTANT(ACCESS_DENIED);
4035 ADD_AD_CONSTANT(DECODE_ERROR);
4036 ADD_AD_CONSTANT(DECRYPT_ERROR);
4037 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4038 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4039 ADD_AD_CONSTANT(INTERNAL_ERROR);
4040 ADD_AD_CONSTANT(USER_CANCELLED);
4041 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004042 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004043#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4044 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4045#endif
4046#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4047 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4048#endif
4049#ifdef SSL_AD_UNRECOGNIZED_NAME
4050 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4051#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004052#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4053 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4054#endif
4055#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4056 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4057#endif
4058#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4059 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4060#endif
4061
4062#undef ADD_AD_CONSTANT
4063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004064 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004065#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004066 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4067 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004068#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004069#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004070 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4071 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004072#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004073 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4074 PY_SSL_VERSION_SSL23);
4075 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4076 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004077#if HAVE_TLSv1_2
4078 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4079 PY_SSL_VERSION_TLS1_1);
4080 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4081 PY_SSL_VERSION_TLS1_2);
4082#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004083
Antoine Pitroub5218772010-05-21 09:56:06 +00004084 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004085 PyModule_AddIntConstant(m, "OP_ALL",
4086 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004087 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4088 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4089 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004090#if HAVE_TLSv1_2
4091 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4092 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4093#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004094 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4095 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004096 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004097#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004098 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004099#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004100#ifdef SSL_OP_NO_COMPRESSION
4101 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4102 SSL_OP_NO_COMPRESSION);
4103#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004104
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004105#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004106 r = Py_True;
4107#else
4108 r = Py_False;
4109#endif
4110 Py_INCREF(r);
4111 PyModule_AddObject(m, "HAS_SNI", r);
4112
Antoine Pitroud6494802011-07-21 01:11:30 +02004113#if HAVE_OPENSSL_FINISHED
4114 r = Py_True;
4115#else
4116 r = Py_False;
4117#endif
4118 Py_INCREF(r);
4119 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4120
Antoine Pitrou501da612011-12-21 09:27:41 +01004121#ifdef OPENSSL_NO_ECDH
4122 r = Py_False;
4123#else
4124 r = Py_True;
4125#endif
4126 Py_INCREF(r);
4127 PyModule_AddObject(m, "HAS_ECDH", r);
4128
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004129#ifdef OPENSSL_NPN_NEGOTIATED
4130 r = Py_True;
4131#else
4132 r = Py_False;
4133#endif
4134 Py_INCREF(r);
4135 PyModule_AddObject(m, "HAS_NPN", r);
4136
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004137 /* Mappings for error codes */
4138 err_codes_to_names = PyDict_New();
4139 err_names_to_codes = PyDict_New();
4140 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4141 return NULL;
4142 errcode = error_codes;
4143 while (errcode->mnemonic != NULL) {
4144 PyObject *mnemo, *key;
4145 mnemo = PyUnicode_FromString(errcode->mnemonic);
4146 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4147 if (mnemo == NULL || key == NULL)
4148 return NULL;
4149 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4150 return NULL;
4151 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4152 return NULL;
4153 Py_DECREF(key);
4154 Py_DECREF(mnemo);
4155 errcode++;
4156 }
4157 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4158 return NULL;
4159 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4160 return NULL;
4161
4162 lib_codes_to_names = PyDict_New();
4163 if (lib_codes_to_names == NULL)
4164 return NULL;
4165 libcode = library_codes;
4166 while (libcode->library != NULL) {
4167 PyObject *mnemo, *key;
4168 key = PyLong_FromLong(libcode->code);
4169 mnemo = PyUnicode_FromString(libcode->library);
4170 if (key == NULL || mnemo == NULL)
4171 return NULL;
4172 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4173 return NULL;
4174 Py_DECREF(key);
4175 Py_DECREF(mnemo);
4176 libcode++;
4177 }
4178 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4179 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004181 /* OpenSSL version */
4182 /* SSLeay() gives us the version of the library linked against,
4183 which could be different from the headers version.
4184 */
4185 libver = SSLeay();
4186 r = PyLong_FromUnsignedLong(libver);
4187 if (r == NULL)
4188 return NULL;
4189 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4190 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004191 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004192 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4193 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4194 return NULL;
4195 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4196 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4197 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004198
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004199 libver = OPENSSL_VERSION_NUMBER;
4200 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4201 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4202 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4203 return NULL;
4204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004205 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004206}