blob: ffcc4a9f61290205ca381d6e436fc3d37f56c1ad [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
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020021
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020023#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
25#define PySSL_END_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000028 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020029 PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
31#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000034#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save)
37#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038#define PySSL_BEGIN_ALLOW_THREADS
39#define PySSL_BLOCK_THREADS
40#define PySSL_UNBLOCK_THREADS
41#define PySSL_END_ALLOW_THREADS
42
43#endif
44
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010045/* Include symbols from _socket module */
46#include "socketmodule.h"
47
48static PySocketModule_APIObject PySocketModule;
49
50#if defined(HAVE_POLL_H)
51#include <poll.h>
52#elif defined(HAVE_SYS_POLL_H)
53#include <sys/poll.h>
54#endif
55
56/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
65
66/* SSL error object */
67static PyObject *PySSLErrorObject;
68static PyObject *PySSLZeroReturnErrorObject;
69static PyObject *PySSLWantReadErrorObject;
70static PyObject *PySSLWantWriteErrorObject;
71static PyObject *PySSLSyscallErrorObject;
72static PyObject *PySSLEOFErrorObject;
73
74/* Error mappings */
75static PyObject *err_codes_to_names;
76static PyObject *err_names_to_codes;
77static PyObject *lib_codes_to_names;
78
79struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83struct py_ssl_library_code {
84 const char *library;
85 int code;
86};
87
88/* Include generated data (error codes) */
89#include "_ssl_data.h"
90
91/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
92 http://www.openssl.org/news/changelog.html
93 */
94#if OPENSSL_VERSION_NUMBER >= 0x10001000L
95# define HAVE_TLSv1_2 1
96#else
97# define HAVE_TLSv1_2 0
98#endif
99
Antoine Pitrouce852cb2013-03-30 16:45:04 +0100100/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100101 * This includes the SSL_set_SSL_CTX() function.
102 */
103#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
104# define HAVE_SNI 1
105#else
106# define HAVE_SNI 0
107#endif
108
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000109enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000110 /* these mirror ssl.h */
111 PY_SSL_ERROR_NONE,
112 PY_SSL_ERROR_SSL,
113 PY_SSL_ERROR_WANT_READ,
114 PY_SSL_ERROR_WANT_WRITE,
115 PY_SSL_ERROR_WANT_X509_LOOKUP,
116 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
117 PY_SSL_ERROR_ZERO_RETURN,
118 PY_SSL_ERROR_WANT_CONNECT,
119 /* start of non ssl.h errorcodes */
120 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
121 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
122 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000123};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000124
Thomas Woutersed03b412007-08-28 21:37:11 +0000125enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PY_SSL_CLIENT,
127 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000128};
129
130enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000131 PY_SSL_CERT_NONE,
132 PY_SSL_CERT_OPTIONAL,
133 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000134};
135
136enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +0200137#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000138 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200139#endif
140 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
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100201
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000202typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000203 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100205#ifdef OPENSSL_NPN_NEGOTIATED
206 char *npn_protocols;
207 int npn_protocols_len;
208#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100209#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200210 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100211#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000213
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214typedef struct {
215 PyObject_HEAD
216 PyObject *Socket; /* weakref to socket on which we're layered */
217 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100218 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200220 char shutdown_seen_zero;
221 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200222 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000224
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225static PyTypeObject PySSLContext_Type;
226static PyTypeObject PySSLSocket_Type;
227
228static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
229static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000230static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000231 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
233static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
236#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000238typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000239 SOCKET_IS_NONBLOCKING,
240 SOCKET_IS_BLOCKING,
241 SOCKET_HAS_TIMED_OUT,
242 SOCKET_HAS_BEEN_CLOSED,
243 SOCKET_TOO_LARGE_FOR_SELECT,
244 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000245} timeout_state;
246
Thomas Woutersed03b412007-08-28 21:37:11 +0000247/* Wrap error strings with filename and line # */
248#define STRINGIFY1(x) #x
249#define STRINGIFY2(x) STRINGIFY1(x)
250#define ERRSTR1(x,y,z) (x ":" y ": " z)
251#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
252
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200253
254/*
255 * SSL errors.
256 */
257
258PyDoc_STRVAR(SSLError_doc,
259"An error occurred in the SSL implementation.");
260
261PyDoc_STRVAR(SSLZeroReturnError_doc,
262"SSL/TLS session closed cleanly.");
263
264PyDoc_STRVAR(SSLWantReadError_doc,
265"Non-blocking SSL socket needs to read more data\n"
266"before the requested operation can be completed.");
267
268PyDoc_STRVAR(SSLWantWriteError_doc,
269"Non-blocking SSL socket needs to write more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLSyscallError_doc,
273"System error when attempting SSL operation.");
274
275PyDoc_STRVAR(SSLEOFError_doc,
276"SSL/TLS connection terminated abruptly.");
277
278static PyObject *
279SSLError_str(PyOSErrorObject *self)
280{
281 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
282 Py_INCREF(self->strerror);
283 return self->strerror;
284 }
285 else
286 return PyObject_Str(self->args);
287}
288
289static PyType_Slot sslerror_type_slots[] = {
290 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
291 {Py_tp_doc, SSLError_doc},
292 {Py_tp_str, SSLError_str},
293 {0, 0},
294};
295
296static PyType_Spec sslerror_type_spec = {
297 "ssl.SSLError",
298 sizeof(PyOSErrorObject),
299 0,
300 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
301 sslerror_type_slots
302};
303
304static void
305fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
306 int lineno, unsigned long errcode)
307{
308 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
309 PyObject *init_value, *msg, *key;
310 _Py_IDENTIFIER(reason);
311 _Py_IDENTIFIER(library);
312
313 if (errcode != 0) {
314 int lib, reason;
315
316 lib = ERR_GET_LIB(errcode);
317 reason = ERR_GET_REASON(errcode);
318 key = Py_BuildValue("ii", lib, reason);
319 if (key == NULL)
320 goto fail;
321 reason_obj = PyDict_GetItem(err_codes_to_names, key);
322 Py_DECREF(key);
323 if (reason_obj == NULL) {
324 /* XXX if reason < 100, it might reflect a library number (!!) */
325 PyErr_Clear();
326 }
327 key = PyLong_FromLong(lib);
328 if (key == NULL)
329 goto fail;
330 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
331 Py_DECREF(key);
332 if (lib_obj == NULL) {
333 PyErr_Clear();
334 }
335 if (errstr == NULL)
336 errstr = ERR_reason_error_string(errcode);
337 }
338 if (errstr == NULL)
339 errstr = "unknown error";
340
341 if (reason_obj && lib_obj)
342 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
343 lib_obj, reason_obj, errstr, lineno);
344 else if (lib_obj)
345 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
346 lib_obj, errstr, lineno);
347 else
348 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200349 if (msg == NULL)
350 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100351
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200352 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100353 if (init_value == NULL)
354 goto fail;
355
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 err_value = PyObject_CallObject(type, init_value);
357 Py_DECREF(init_value);
358 if (err_value == NULL)
359 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100360
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200361 if (reason_obj == NULL)
362 reason_obj = Py_None;
363 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
364 goto fail;
365 if (lib_obj == NULL)
366 lib_obj = Py_None;
367 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
368 goto fail;
369 PyErr_SetObject(type, err_value);
370fail:
371 Py_XDECREF(err_value);
372}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000373
374static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000376{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200377 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200378 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 int err;
380 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200381 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 if (obj->ssl != NULL) {
387 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 switch (err) {
390 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200391 errstr = "TLS/SSL connection has been closed (EOF)";
392 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 p = PY_SSL_ERROR_ZERO_RETURN;
394 break;
395 case SSL_ERROR_WANT_READ:
396 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000398 p = PY_SSL_ERROR_WANT_READ;
399 break;
400 case SSL_ERROR_WANT_WRITE:
401 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200402 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 errstr = "The operation did not complete (write)";
404 break;
405 case SSL_ERROR_WANT_X509_LOOKUP:
406 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000407 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 break;
409 case SSL_ERROR_WANT_CONNECT:
410 p = PY_SSL_ERROR_WANT_CONNECT;
411 errstr = "The operation did not complete (connect)";
412 break;
413 case SSL_ERROR_SYSCALL:
414 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 if (e == 0) {
416 PySocketSockObject *s
417 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
418 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200420 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000421 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000425 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200426 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000427 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000430 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200431 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 }
434 } else {
435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000436 }
437 break;
438 }
439 case SSL_ERROR_SSL:
440 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200442 if (e == 0)
443 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000444 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 break;
446 }
447 default:
448 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
449 errstr = "Invalid error code";
450 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200452 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000453 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455}
456
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457static PyObject *
458_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
459
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200460 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 else
463 errcode = 0;
464 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000465 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467}
468
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469/*
470 * SSL objects
471 */
472
Antoine Pitrou152efa22010-05-16 18:19:27 +0000473static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100474newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000475 enum py_ssl_server_or_client socket_type,
476 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000477{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200480 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 if (self == NULL)
484 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 self->peer_cert = NULL;
487 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100489 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200490 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200491 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100492 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 /* Make sure the SSL error state is initialized */
495 (void) ERR_get_state();
496 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000499 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100501 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000502 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200503 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000504#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200505 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000506#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000508
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100509#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000510 if (server_hostname != NULL)
511 SSL_set_tlsext_host_name(self->ssl, server_hostname);
512#endif
513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* If the socket is in non-blocking mode or timeout mode, set the BIO
515 * to non-blocking mode (blocking is the default)
516 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000517 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
519 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
520 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 PySSL_BEGIN_ALLOW_THREADS
523 if (socket_type == PY_SSL_CLIENT)
524 SSL_set_connect_state(self->ssl);
525 else
526 SSL_set_accept_state(self->ssl);
527 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000528
Antoine Pitroud6494802011-07-21 01:11:30 +0200529 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000530 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000532}
533
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000534/* SSL object methods */
535
Antoine Pitrou152efa22010-05-16 18:19:27 +0000536static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000537{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 int ret;
539 int err;
540 int sockstate, nonblocking;
541 PySocketSockObject *sock
542 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 if (((PyObject*)sock) == Py_None) {
545 _setSSLError("Underlying socket connection gone",
546 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
547 return NULL;
548 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000549 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 /* just in case the blocking state of the socket has been changed */
552 nonblocking = (sock->sock_timeout >= 0.0);
553 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
554 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 /* Actually negotiate SSL connection */
557 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000559 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 ret = SSL_do_handshake(self->ssl);
561 err = SSL_get_error(self->ssl, ret);
562 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000563 if (PyErr_CheckSignals())
564 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 if (err == SSL_ERROR_WANT_READ) {
566 sockstate = check_socket_and_wait_for_timeout(sock, 0);
567 } else if (err == SSL_ERROR_WANT_WRITE) {
568 sockstate = check_socket_and_wait_for_timeout(sock, 1);
569 } else {
570 sockstate = SOCKET_OPERATION_OK;
571 }
572 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000573 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000574 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000575 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
577 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000578 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
581 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
585 break;
586 }
587 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000588 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 if (ret < 1)
590 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 if (self->peer_cert)
593 X509_free (self->peer_cert);
594 PySSL_BEGIN_ALLOW_THREADS
595 self->peer_cert = SSL_get_peer_certificate(self->ssl);
596 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200597 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598
599 Py_INCREF(Py_None);
600 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000601
602error:
603 Py_DECREF(sock);
604 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000605}
606
Thomas Woutersed03b412007-08-28 21:37:11 +0000607static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 char namebuf[X509_NAME_MAXLEN];
611 int buflen;
612 PyObject *name_obj;
613 PyObject *value_obj;
614 PyObject *attr;
615 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
618 if (buflen < 0) {
619 _setSSLError(NULL, 0, __FILE__, __LINE__);
620 goto fail;
621 }
622 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
623 if (name_obj == NULL)
624 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
627 if (buflen < 0) {
628 _setSSLError(NULL, 0, __FILE__, __LINE__);
629 Py_DECREF(name_obj);
630 goto fail;
631 }
632 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 OPENSSL_free(valuebuf);
635 if (value_obj == NULL) {
636 Py_DECREF(name_obj);
637 goto fail;
638 }
639 attr = PyTuple_New(2);
640 if (attr == NULL) {
641 Py_DECREF(name_obj);
642 Py_DECREF(value_obj);
643 goto fail;
644 }
645 PyTuple_SET_ITEM(attr, 0, name_obj);
646 PyTuple_SET_ITEM(attr, 1, value_obj);
647 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000648
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000650 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000651}
652
653static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000655{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
657 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
658 PyObject *rdnt;
659 PyObject *attr = NULL; /* tuple to hold an attribute */
660 int entry_count = X509_NAME_entry_count(xname);
661 X509_NAME_ENTRY *entry;
662 ASN1_OBJECT *name;
663 ASN1_STRING *value;
664 int index_counter;
665 int rdn_level = -1;
666 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 dn = PyList_New(0);
669 if (dn == NULL)
670 return NULL;
671 /* now create another tuple to hold the top-level RDN */
672 rdn = PyList_New(0);
673 if (rdn == NULL)
674 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 for (index_counter = 0;
677 index_counter < entry_count;
678 index_counter++)
679 {
680 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 /* check to see if we've gotten to a new RDN */
683 if (rdn_level >= 0) {
684 if (rdn_level != entry->set) {
685 /* yes, new RDN */
686 /* add old RDN to DN */
687 rdnt = PyList_AsTuple(rdn);
688 Py_DECREF(rdn);
689 if (rdnt == NULL)
690 goto fail0;
691 retcode = PyList_Append(dn, rdnt);
692 Py_DECREF(rdnt);
693 if (retcode < 0)
694 goto fail0;
695 /* create new RDN */
696 rdn = PyList_New(0);
697 if (rdn == NULL)
698 goto fail0;
699 }
700 }
701 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000703 /* now add this attribute to the current RDN */
704 name = X509_NAME_ENTRY_get_object(entry);
705 value = X509_NAME_ENTRY_get_data(entry);
706 attr = _create_tuple_for_attribute(name, value);
707 /*
708 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
709 entry->set,
710 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
711 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
712 */
713 if (attr == NULL)
714 goto fail1;
715 retcode = PyList_Append(rdn, attr);
716 Py_DECREF(attr);
717 if (retcode < 0)
718 goto fail1;
719 }
720 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100721 if (rdn != NULL) {
722 if (PyList_GET_SIZE(rdn) > 0) {
723 rdnt = PyList_AsTuple(rdn);
724 Py_DECREF(rdn);
725 if (rdnt == NULL)
726 goto fail0;
727 retcode = PyList_Append(dn, rdnt);
728 Py_DECREF(rdnt);
729 if (retcode < 0)
730 goto fail0;
731 }
732 else {
733 Py_DECREF(rdn);
734 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 /* convert list to tuple */
738 rdnt = PyList_AsTuple(dn);
739 Py_DECREF(dn);
740 if (rdnt == NULL)
741 return NULL;
742 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
744 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
747 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 Py_XDECREF(dn);
749 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750}
751
752static PyObject *
753_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 /* this code follows the procedure outlined in
756 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
757 function to extract the STACK_OF(GENERAL_NAME),
758 then iterates through the stack to add the
759 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 int i, j;
762 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200763 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 X509_EXTENSION *ext = NULL;
765 GENERAL_NAMES *names = NULL;
766 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000767 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 BIO *biobuf = NULL;
769 char buf[2048];
770 char *vptr;
771 int len;
772 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000773#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000775#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000777#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (certificate == NULL)
780 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 /* get a memory buffer */
783 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200785 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 while ((i = X509_get_ext_by_NID(
787 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 if (peer_alt_names == Py_None) {
790 peer_alt_names = PyList_New(0);
791 if (peer_alt_names == NULL)
792 goto fail;
793 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 /* now decode the altName */
796 ext = X509_get_ext(certificate, i);
797 if(!(method = X509V3_EXT_get(ext))) {
798 PyErr_SetString
799 (PySSLErrorObject,
800 ERRSTR("No method for internalizing subjectAltName!"));
801 goto fail;
802 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 p = ext->value->data;
805 if (method->it)
806 names = (GENERAL_NAMES*)
807 (ASN1_item_d2i(NULL,
808 &p,
809 ext->value->length,
810 ASN1_ITEM_ptr(method->it)));
811 else
812 names = (GENERAL_NAMES*)
813 (method->d2i(NULL,
814 &p,
815 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200819 int gntype;
820 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200823 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200824 switch (gntype) {
825 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 /* we special-case DirName as a tuple of
827 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 t = PyTuple_New(2);
830 if (t == NULL) {
831 goto fail;
832 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 v = PyUnicode_FromString("DirName");
835 if (v == NULL) {
836 Py_DECREF(t);
837 goto fail;
838 }
839 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 v = _create_tuple_for_X509_NAME (name->d.dirn);
842 if (v == NULL) {
843 Py_DECREF(t);
844 goto fail;
845 }
846 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200847 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000848
Christian Heimes824f7f32013-08-17 00:54:47 +0200849 case GEN_EMAIL:
850 case GEN_DNS:
851 case GEN_URI:
852 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
853 correctly, CVE-2013-4238 */
854 t = PyTuple_New(2);
855 if (t == NULL)
856 goto fail;
857 switch (gntype) {
858 case GEN_EMAIL:
859 v = PyUnicode_FromString("email");
860 as = name->d.rfc822Name;
861 break;
862 case GEN_DNS:
863 v = PyUnicode_FromString("DNS");
864 as = name->d.dNSName;
865 break;
866 case GEN_URI:
867 v = PyUnicode_FromString("URI");
868 as = name->d.uniformResourceIdentifier;
869 break;
870 }
871 if (v == NULL) {
872 Py_DECREF(t);
873 goto fail;
874 }
875 PyTuple_SET_ITEM(t, 0, v);
876 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
877 ASN1_STRING_length(as));
878 if (v == NULL) {
879 Py_DECREF(t);
880 goto fail;
881 }
882 PyTuple_SET_ITEM(t, 1, v);
883 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Christian Heimes824f7f32013-08-17 00:54:47 +0200885 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200887 switch (gntype) {
888 /* check for new general name type */
889 case GEN_OTHERNAME:
890 case GEN_X400:
891 case GEN_EDIPARTY:
892 case GEN_IPADD:
893 case GEN_RID:
894 break;
895 default:
896 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
897 "Unknown general name type %d",
898 gntype) == -1) {
899 goto fail;
900 }
901 break;
902 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 (void) BIO_reset(biobuf);
904 GENERAL_NAME_print(biobuf, name);
905 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
906 if (len < 0) {
907 _setSSLError(NULL, 0, __FILE__, __LINE__);
908 goto fail;
909 }
910 vptr = strchr(buf, ':');
911 if (vptr == NULL)
912 goto fail;
913 t = PyTuple_New(2);
914 if (t == NULL)
915 goto fail;
916 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
917 if (v == NULL) {
918 Py_DECREF(t);
919 goto fail;
920 }
921 PyTuple_SET_ITEM(t, 0, v);
922 v = PyUnicode_FromStringAndSize((vptr + 1),
923 (len - (vptr - buf + 1)));
924 if (v == NULL) {
925 Py_DECREF(t);
926 goto fail;
927 }
928 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200929 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 if (PyList_Append(peer_alt_names, t) < 0) {
935 Py_DECREF(t);
936 goto fail;
937 }
938 Py_DECREF(t);
939 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100940 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 }
942 BIO_free(biobuf);
943 if (peer_alt_names != Py_None) {
944 v = PyList_AsTuple(peer_alt_names);
945 Py_DECREF(peer_alt_names);
946 return v;
947 } else {
948 return peer_alt_names;
949 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000950
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
952 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 if (biobuf != NULL)
954 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 if (peer_alt_names != Py_None) {
957 Py_XDECREF(peer_alt_names);
958 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961}
962
963static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000964_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 PyObject *retval = NULL;
967 BIO *biobuf = NULL;
968 PyObject *peer;
969 PyObject *peer_alt_names = NULL;
970 PyObject *issuer;
971 PyObject *version;
972 PyObject *sn_obj;
973 ASN1_INTEGER *serialNumber;
974 char buf[2048];
975 int len;
976 ASN1_TIME *notBefore, *notAfter;
977 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 retval = PyDict_New();
980 if (retval == NULL)
981 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 peer = _create_tuple_for_X509_NAME(
984 X509_get_subject_name(certificate));
985 if (peer == NULL)
986 goto fail0;
987 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
988 Py_DECREF(peer);
989 goto fail0;
990 }
991 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000992
Antoine Pitroufb046912010-11-09 20:21:19 +0000993 issuer = _create_tuple_for_X509_NAME(
994 X509_get_issuer_name(certificate));
995 if (issuer == NULL)
996 goto fail0;
997 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000999 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001001 Py_DECREF(issuer);
1002
1003 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001004 if (version == NULL)
1005 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001006 if (PyDict_SetItemString(retval, "version", version) < 0) {
1007 Py_DECREF(version);
1008 goto fail0;
1009 }
1010 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 /* get a memory buffer */
1013 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001014
Antoine Pitroufb046912010-11-09 20:21:19 +00001015 (void) BIO_reset(biobuf);
1016 serialNumber = X509_get_serialNumber(certificate);
1017 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1018 i2a_ASN1_INTEGER(biobuf, serialNumber);
1019 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1020 if (len < 0) {
1021 _setSSLError(NULL, 0, __FILE__, __LINE__);
1022 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001024 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1025 if (sn_obj == NULL)
1026 goto fail1;
1027 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1028 Py_DECREF(sn_obj);
1029 goto fail1;
1030 }
1031 Py_DECREF(sn_obj);
1032
1033 (void) BIO_reset(biobuf);
1034 notBefore = X509_get_notBefore(certificate);
1035 ASN1_TIME_print(biobuf, notBefore);
1036 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1037 if (len < 0) {
1038 _setSSLError(NULL, 0, __FILE__, __LINE__);
1039 goto fail1;
1040 }
1041 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1042 if (pnotBefore == NULL)
1043 goto fail1;
1044 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1045 Py_DECREF(pnotBefore);
1046 goto fail1;
1047 }
1048 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 (void) BIO_reset(biobuf);
1051 notAfter = X509_get_notAfter(certificate);
1052 ASN1_TIME_print(biobuf, notAfter);
1053 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1054 if (len < 0) {
1055 _setSSLError(NULL, 0, __FILE__, __LINE__);
1056 goto fail1;
1057 }
1058 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1059 if (pnotAfter == NULL)
1060 goto fail1;
1061 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1062 Py_DECREF(pnotAfter);
1063 goto fail1;
1064 }
1065 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 peer_alt_names = _get_peer_alt_names(certificate);
1070 if (peer_alt_names == NULL)
1071 goto fail1;
1072 else if (peer_alt_names != Py_None) {
1073 if (PyDict_SetItemString(retval, "subjectAltName",
1074 peer_alt_names) < 0) {
1075 Py_DECREF(peer_alt_names);
1076 goto fail1;
1077 }
1078 Py_DECREF(peer_alt_names);
1079 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 BIO_free(biobuf);
1082 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001083
1084 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 if (biobuf != NULL)
1086 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001087 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 Py_XDECREF(retval);
1089 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001090}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001091
Christian Heimes9a5395a2013-06-17 15:44:12 +02001092static PyObject *
1093_certificate_to_der(X509 *certificate)
1094{
1095 unsigned char *bytes_buf = NULL;
1096 int len;
1097 PyObject *retval;
1098
1099 bytes_buf = NULL;
1100 len = i2d_X509(certificate, &bytes_buf);
1101 if (len < 0) {
1102 _setSSLError(NULL, 0, __FILE__, __LINE__);
1103 return NULL;
1104 }
1105 /* this is actually an immutable bytes sequence */
1106 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1107 OPENSSL_free(bytes_buf);
1108 return retval;
1109}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
1111static PyObject *
1112PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001115 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 X509 *x=NULL;
1117 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroufb046912010-11-09 20:21:19 +00001119 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1120 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1124 PyErr_SetString(PySSLErrorObject,
1125 "Can't malloc memory to read file");
1126 goto fail0;
1127 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
Victor Stinner3800e1e2010-05-16 21:23:48 +00001129 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 PyErr_SetString(PySSLErrorObject,
1131 "Can't open file");
1132 goto fail0;
1133 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1136 if (x == NULL) {
1137 PyErr_SetString(PySSLErrorObject,
1138 "Error decoding PEM-encoded file");
1139 goto fail0;
1140 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141
Antoine Pitroufb046912010-11-09 20:21:19 +00001142 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001143 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
1145 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001146 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 if (cert != NULL) BIO_free(cert);
1148 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149}
1150
1151
1152static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001153PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001156 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001157
Antoine Pitrou721738f2012-08-15 23:20:39 +02001158 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160
Antoine Pitrou20b85552013-09-29 19:50:53 +02001161 if (!self->handshake_done) {
1162 PyErr_SetString(PyExc_ValueError,
1163 "handshake not done yet");
1164 return NULL;
1165 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 if (!self->peer_cert)
1167 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Antoine Pitrou721738f2012-08-15 23:20:39 +02001169 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001171 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001173 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 if ((verification & SSL_VERIFY_PEER) == 0)
1175 return PyDict_New();
1176 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001177 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001179}
1180
1181PyDoc_STRVAR(PySSL_peercert_doc,
1182"peer_certificate([der=False]) -> certificate\n\
1183\n\
1184Returns the certificate for the peer. If no certificate was provided,\n\
1185returns None. If a certificate was provided, but not validated, returns\n\
1186an empty dictionary. Otherwise returns a dict containing information\n\
1187about the peer certificate.\n\
1188\n\
1189If the optional argument is True, returns a DER-encoded copy of the\n\
1190peer certificate, or None if no certificate was provided. This will\n\
1191return the certificate even if it wasn't validated.");
1192
Antoine Pitrou152efa22010-05-16 18:19:27 +00001193static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001196 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 char *cipher_name;
1198 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001201 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 current = SSL_get_current_cipher(self->ssl);
1203 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001204 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 retval = PyTuple_New(3);
1207 if (retval == NULL)
1208 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 cipher_name = (char *) SSL_CIPHER_get_name(current);
1211 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001212 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 PyTuple_SET_ITEM(retval, 0, Py_None);
1214 } else {
1215 v = PyUnicode_FromString(cipher_name);
1216 if (v == NULL)
1217 goto fail0;
1218 PyTuple_SET_ITEM(retval, 0, v);
1219 }
1220 cipher_protocol = SSL_CIPHER_get_version(current);
1221 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001222 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 PyTuple_SET_ITEM(retval, 1, Py_None);
1224 } else {
1225 v = PyUnicode_FromString(cipher_protocol);
1226 if (v == NULL)
1227 goto fail0;
1228 PyTuple_SET_ITEM(retval, 1, v);
1229 }
1230 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1231 if (v == NULL)
1232 goto fail0;
1233 PyTuple_SET_ITEM(retval, 2, v);
1234 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001235
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 Py_DECREF(retval);
1238 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239}
1240
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001241#ifdef OPENSSL_NPN_NEGOTIATED
1242static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1243 const unsigned char *out;
1244 unsigned int outlen;
1245
Victor Stinner4569cd52013-06-23 14:58:43 +02001246 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001247 &out, &outlen);
1248
1249 if (out == NULL)
1250 Py_RETURN_NONE;
1251 return PyUnicode_FromStringAndSize((char *) out, outlen);
1252}
1253#endif
1254
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001255static PyObject *PySSL_compression(PySSLSocket *self) {
1256#ifdef OPENSSL_NO_COMP
1257 Py_RETURN_NONE;
1258#else
1259 const COMP_METHOD *comp_method;
1260 const char *short_name;
1261
1262 if (self->ssl == NULL)
1263 Py_RETURN_NONE;
1264 comp_method = SSL_get_current_compression(self->ssl);
1265 if (comp_method == NULL || comp_method->type == NID_undef)
1266 Py_RETURN_NONE;
1267 short_name = OBJ_nid2sn(comp_method->type);
1268 if (short_name == NULL)
1269 Py_RETURN_NONE;
1270 return PyUnicode_DecodeFSDefault(short_name);
1271#endif
1272}
1273
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001274static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1275 Py_INCREF(self->ctx);
1276 return self->ctx;
1277}
1278
1279static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1280 void *closure) {
1281
1282 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001283#if !HAVE_SNI
1284 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1285 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001286 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001287#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001288 Py_INCREF(value);
1289 Py_DECREF(self->ctx);
1290 self->ctx = (PySSLContext *) value;
1291 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001292#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001293 } else {
1294 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1295 return -1;
1296 }
1297
1298 return 0;
1299}
1300
1301PyDoc_STRVAR(PySSL_set_context_doc,
1302"_setter_context(ctx)\n\
1303\
1304This changes the context associated with the SSLSocket. This is typically\n\
1305used from within a callback function set by the set_servername_callback\n\
1306on the SSLContext to change the certificate information associated with the\n\
1307SSLSocket before the cryptographic exchange handshake messages\n");
1308
1309
1310
Antoine Pitrou152efa22010-05-16 18:19:27 +00001311static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001312{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 if (self->peer_cert) /* Possible not to have one? */
1314 X509_free (self->peer_cert);
1315 if (self->ssl)
1316 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001318 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001320}
1321
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001322/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001323 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001324 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001325 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001326
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001327static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001328check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001329{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 fd_set fds;
1331 struct timeval tv;
1332 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1335 if (s->sock_timeout < 0.0)
1336 return SOCKET_IS_BLOCKING;
1337 else if (s->sock_timeout == 0.0)
1338 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* Guard against closed socket */
1341 if (s->sock_fd < 0)
1342 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 /* Prefer poll, if available, since you can poll() any fd
1345 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 {
1348 struct pollfd pollfd;
1349 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 pollfd.fd = s->sock_fd;
1352 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 /* s->sock_timeout is in seconds, timeout in ms */
1355 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1356 PySSL_BEGIN_ALLOW_THREADS
1357 rc = poll(&pollfd, 1, timeout);
1358 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 goto normal_return;
1361 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001362#endif
1363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001365 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 /* Construct the arguments to select */
1369 tv.tv_sec = (int)s->sock_timeout;
1370 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1371 FD_ZERO(&fds);
1372 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 /* See if the socket is ready */
1375 PySSL_BEGIN_ALLOW_THREADS
1376 if (writing)
1377 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1378 else
1379 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1380 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001381
Bill Janssen6e027db2007-11-15 22:23:56 +00001382#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001383normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001384#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1386 (when we are able to write or when there's something to read) */
1387 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001388}
1389
Antoine Pitrou152efa22010-05-16 18:19:27 +00001390static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001391{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 Py_buffer buf;
1393 int len;
1394 int sockstate;
1395 int err;
1396 int nonblocking;
1397 PySocketSockObject *sock
1398 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 if (((PyObject*)sock) == Py_None) {
1401 _setSSLError("Underlying socket connection gone",
1402 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1403 return NULL;
1404 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001405 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001407 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1408 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001410 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411
Victor Stinner6efa9652013-06-25 00:42:31 +02001412 if (buf.len > INT_MAX) {
1413 PyErr_Format(PyExc_OverflowError,
1414 "string longer than %d bytes", INT_MAX);
1415 goto error;
1416 }
1417
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 /* just in case the blocking state of the socket has been changed */
1419 nonblocking = (sock->sock_timeout >= 0.0);
1420 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1421 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1422
1423 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1424 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001425 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 "The write operation timed out");
1427 goto error;
1428 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1429 PyErr_SetString(PySSLErrorObject,
1430 "Underlying socket has been closed.");
1431 goto error;
1432 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1433 PyErr_SetString(PySSLErrorObject,
1434 "Underlying socket too large for select().");
1435 goto error;
1436 }
1437 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001439 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001440 err = SSL_get_error(self->ssl, len);
1441 PySSL_END_ALLOW_THREADS
1442 if (PyErr_CheckSignals()) {
1443 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001444 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001446 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001447 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001448 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 } else {
1450 sockstate = SOCKET_OPERATION_OK;
1451 }
1452 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001453 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001454 "The write operation timed out");
1455 goto error;
1456 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1457 PyErr_SetString(PySSLErrorObject,
1458 "Underlying socket has been closed.");
1459 goto error;
1460 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1461 break;
1462 }
1463 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001464
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001465 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 PyBuffer_Release(&buf);
1467 if (len > 0)
1468 return PyLong_FromLong(len);
1469 else
1470 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001471
1472error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001473 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001474 PyBuffer_Release(&buf);
1475 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001476}
1477
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001478PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479"write(s) -> len\n\
1480\n\
1481Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001482of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001483
Antoine Pitrou152efa22010-05-16 18:19:27 +00001484static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001485{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 PySSL_BEGIN_ALLOW_THREADS
1489 count = SSL_pending(self->ssl);
1490 PySSL_END_ALLOW_THREADS
1491 if (count < 0)
1492 return PySSL_SetError(self, count, __FILE__, __LINE__);
1493 else
1494 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001495}
1496
1497PyDoc_STRVAR(PySSL_SSLpending_doc,
1498"pending() -> count\n\
1499\n\
1500Returns the number of already decrypted bytes available for read,\n\
1501pending on the connection.\n");
1502
Antoine Pitrou152efa22010-05-16 18:19:27 +00001503static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001504{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 PyObject *dest = NULL;
1506 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001508 int len, count;
1509 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 int sockstate;
1511 int err;
1512 int nonblocking;
1513 PySocketSockObject *sock
1514 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 if (((PyObject*)sock) == Py_None) {
1517 _setSSLError("Underlying socket connection gone",
1518 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1519 return NULL;
1520 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001521 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001523 buf.obj = NULL;
1524 buf.buf = NULL;
1525 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001526 goto error;
1527
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001528 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1529 dest = PyBytes_FromStringAndSize(NULL, len);
1530 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001531 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 mem = PyBytes_AS_STRING(dest);
1533 }
1534 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001536 mem = buf.buf;
1537 if (len <= 0 || len > buf.len) {
1538 len = (int) buf.len;
1539 if (buf.len != len) {
1540 PyErr_SetString(PyExc_OverflowError,
1541 "maximum length can't fit in a C 'int'");
1542 goto error;
1543 }
1544 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 }
1546
1547 /* just in case the blocking state of the socket has been changed */
1548 nonblocking = (sock->sock_timeout >= 0.0);
1549 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1550 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1551
1552 /* first check if there are bytes ready to be read */
1553 PySSL_BEGIN_ALLOW_THREADS
1554 count = SSL_pending(self->ssl);
1555 PySSL_END_ALLOW_THREADS
1556
1557 if (!count) {
1558 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1559 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001560 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 "The read operation timed out");
1562 goto error;
1563 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1564 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001565 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 goto error;
1567 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1568 count = 0;
1569 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001570 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 }
1572 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 PySSL_BEGIN_ALLOW_THREADS
1574 count = SSL_read(self->ssl, mem, len);
1575 err = SSL_get_error(self->ssl, count);
1576 PySSL_END_ALLOW_THREADS
1577 if (PyErr_CheckSignals())
1578 goto error;
1579 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001580 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001582 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001583 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1584 (SSL_get_shutdown(self->ssl) ==
1585 SSL_RECEIVED_SHUTDOWN))
1586 {
1587 count = 0;
1588 goto done;
1589 } else {
1590 sockstate = SOCKET_OPERATION_OK;
1591 }
1592 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001593 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001594 "The read operation timed out");
1595 goto error;
1596 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1597 break;
1598 }
1599 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1600 if (count <= 0) {
1601 PySSL_SetError(self, count, __FILE__, __LINE__);
1602 goto error;
1603 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001604
1605done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001606 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001608 _PyBytes_Resize(&dest, count);
1609 return dest;
1610 }
1611 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 PyBuffer_Release(&buf);
1613 return PyLong_FromLong(count);
1614 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001615
1616error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001617 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001618 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001619 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001620 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001623}
1624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001625PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001626"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001628Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001629
Antoine Pitrou152efa22010-05-16 18:19:27 +00001630static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001631{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 int err, ssl_err, sockstate, nonblocking;
1633 int zeros = 0;
1634 PySocketSockObject *sock
1635 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001636
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001637 /* Guard against closed socket */
1638 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1639 _setSSLError("Underlying socket connection gone",
1640 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1641 return NULL;
1642 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001643 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644
1645 /* Just in case the blocking state of the socket has been changed */
1646 nonblocking = (sock->sock_timeout >= 0.0);
1647 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1648 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1649
1650 while (1) {
1651 PySSL_BEGIN_ALLOW_THREADS
1652 /* Disable read-ahead so that unwrap can work correctly.
1653 * Otherwise OpenSSL might read in too much data,
1654 * eating clear text data that happens to be
1655 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001656 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001657 * function is used and the shutdown_seen_zero != 0
1658 * condition is met.
1659 */
1660 if (self->shutdown_seen_zero)
1661 SSL_set_read_ahead(self->ssl, 0);
1662 err = SSL_shutdown(self->ssl);
1663 PySSL_END_ALLOW_THREADS
1664 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1665 if (err > 0)
1666 break;
1667 if (err == 0) {
1668 /* Don't loop endlessly; instead preserve legacy
1669 behaviour of trying SSL_shutdown() only twice.
1670 This looks necessary for OpenSSL < 0.9.8m */
1671 if (++zeros > 1)
1672 break;
1673 /* Shutdown was sent, now try receiving */
1674 self->shutdown_seen_zero = 1;
1675 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001676 }
1677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 /* Possibly retry shutdown until timeout or failure */
1679 ssl_err = SSL_get_error(self->ssl, err);
1680 if (ssl_err == SSL_ERROR_WANT_READ)
1681 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1682 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1683 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1684 else
1685 break;
1686 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1687 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001688 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 "The read operation timed out");
1690 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001691 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001693 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 }
1695 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1696 PyErr_SetString(PySSLErrorObject,
1697 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001698 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 }
1700 else if (sockstate != SOCKET_OPERATION_OK)
1701 /* Retain the SSL error code */
1702 break;
1703 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001704
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001705 if (err < 0) {
1706 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001709 else
1710 /* It's already INCREF'ed */
1711 return (PyObject *) sock;
1712
1713error:
1714 Py_DECREF(sock);
1715 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001716}
1717
1718PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1719"shutdown(s) -> socket\n\
1720\n\
1721Does the SSL shutdown handshake with the remote end, and returns\n\
1722the underlying socket object.");
1723
Antoine Pitroud6494802011-07-21 01:11:30 +02001724#if HAVE_OPENSSL_FINISHED
1725static PyObject *
1726PySSL_tls_unique_cb(PySSLSocket *self)
1727{
1728 PyObject *retval = NULL;
1729 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001730 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001731
1732 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1733 /* if session is resumed XOR we are the client */
1734 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1735 }
1736 else {
1737 /* if a new session XOR we are the server */
1738 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1739 }
1740
1741 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001742 if (len == 0)
1743 Py_RETURN_NONE;
1744
1745 retval = PyBytes_FromStringAndSize(buf, len);
1746
1747 return retval;
1748}
1749
1750PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1751"tls_unique_cb() -> bytes\n\
1752\n\
1753Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1754\n\
1755If the TLS handshake is not yet complete, None is returned");
1756
1757#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001758
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001759static PyGetSetDef ssl_getsetlist[] = {
1760 {"context", (getter) PySSL_get_context,
1761 (setter) PySSL_set_context, PySSL_set_context_doc},
1762 {NULL}, /* sentinel */
1763};
1764
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001765static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1767 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1768 PySSL_SSLwrite_doc},
1769 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1770 PySSL_SSLread_doc},
1771 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1772 PySSL_SSLpending_doc},
1773 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1774 PySSL_peercert_doc},
1775 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001776#ifdef OPENSSL_NPN_NEGOTIATED
1777 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1778#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001779 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1781 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001782#if HAVE_OPENSSL_FINISHED
1783 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1784 PySSL_tls_unique_cb_doc},
1785#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787};
1788
Antoine Pitrou152efa22010-05-16 18:19:27 +00001789static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 "_ssl._SSLSocket", /*tp_name*/
1792 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 0, /*tp_itemsize*/
1794 /* methods */
1795 (destructor)PySSL_dealloc, /*tp_dealloc*/
1796 0, /*tp_print*/
1797 0, /*tp_getattr*/
1798 0, /*tp_setattr*/
1799 0, /*tp_reserved*/
1800 0, /*tp_repr*/
1801 0, /*tp_as_number*/
1802 0, /*tp_as_sequence*/
1803 0, /*tp_as_mapping*/
1804 0, /*tp_hash*/
1805 0, /*tp_call*/
1806 0, /*tp_str*/
1807 0, /*tp_getattro*/
1808 0, /*tp_setattro*/
1809 0, /*tp_as_buffer*/
1810 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1811 0, /*tp_doc*/
1812 0, /*tp_traverse*/
1813 0, /*tp_clear*/
1814 0, /*tp_richcompare*/
1815 0, /*tp_weaklistoffset*/
1816 0, /*tp_iter*/
1817 0, /*tp_iternext*/
1818 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001819 0, /*tp_members*/
1820 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001821};
1822
Antoine Pitrou152efa22010-05-16 18:19:27 +00001823
1824/*
1825 * _SSLContext objects
1826 */
1827
1828static PyObject *
1829context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1830{
1831 char *kwlist[] = {"protocol", NULL};
1832 PySSLContext *self;
1833 int proto_version = PY_SSL_VERSION_SSL23;
1834 SSL_CTX *ctx = NULL;
1835
1836 if (!PyArg_ParseTupleAndKeywords(
1837 args, kwds, "i:_SSLContext", kwlist,
1838 &proto_version))
1839 return NULL;
1840
1841 PySSL_BEGIN_ALLOW_THREADS
1842 if (proto_version == PY_SSL_VERSION_TLS1)
1843 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001844#if HAVE_TLSv1_2
1845 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1846 ctx = SSL_CTX_new(TLSv1_1_method());
1847 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1848 ctx = SSL_CTX_new(TLSv1_2_method());
1849#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001850 else if (proto_version == PY_SSL_VERSION_SSL3)
1851 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001852#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001853 else if (proto_version == PY_SSL_VERSION_SSL2)
1854 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001855#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001856 else if (proto_version == PY_SSL_VERSION_SSL23)
1857 ctx = SSL_CTX_new(SSLv23_method());
1858 else
1859 proto_version = -1;
1860 PySSL_END_ALLOW_THREADS
1861
1862 if (proto_version == -1) {
1863 PyErr_SetString(PyExc_ValueError,
1864 "invalid protocol version");
1865 return NULL;
1866 }
1867 if (ctx == NULL) {
1868 PyErr_SetString(PySSLErrorObject,
1869 "failed to allocate SSL context");
1870 return NULL;
1871 }
1872
1873 assert(type != NULL && type->tp_alloc != NULL);
1874 self = (PySSLContext *) type->tp_alloc(type, 0);
1875 if (self == NULL) {
1876 SSL_CTX_free(ctx);
1877 return NULL;
1878 }
1879 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001880#ifdef OPENSSL_NPN_NEGOTIATED
1881 self->npn_protocols = NULL;
1882#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001883#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001884 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001885#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001886 /* Defaults */
1887 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001888 SSL_CTX_set_options(self->ctx,
1889 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001890
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001891#define SID_CTX "Python"
1892 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1893 sizeof(SID_CTX));
1894#undef SID_CTX
1895
Antoine Pitrou152efa22010-05-16 18:19:27 +00001896 return (PyObject *)self;
1897}
1898
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001899static int
1900context_traverse(PySSLContext *self, visitproc visit, void *arg)
1901{
1902#ifndef OPENSSL_NO_TLSEXT
1903 Py_VISIT(self->set_hostname);
1904#endif
1905 return 0;
1906}
1907
1908static int
1909context_clear(PySSLContext *self)
1910{
1911#ifndef OPENSSL_NO_TLSEXT
1912 Py_CLEAR(self->set_hostname);
1913#endif
1914 return 0;
1915}
1916
Antoine Pitrou152efa22010-05-16 18:19:27 +00001917static void
1918context_dealloc(PySSLContext *self)
1919{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001920 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001921 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001922#ifdef OPENSSL_NPN_NEGOTIATED
1923 PyMem_Free(self->npn_protocols);
1924#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001925 Py_TYPE(self)->tp_free(self);
1926}
1927
1928static PyObject *
1929set_ciphers(PySSLContext *self, PyObject *args)
1930{
1931 int ret;
1932 const char *cipherlist;
1933
1934 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1935 return NULL;
1936 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1937 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001938 /* Clearing the error queue is necessary on some OpenSSL versions,
1939 otherwise the error will be reported again when another SSL call
1940 is done. */
1941 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001942 PyErr_SetString(PySSLErrorObject,
1943 "No cipher can be selected.");
1944 return NULL;
1945 }
1946 Py_RETURN_NONE;
1947}
1948
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001949#ifdef OPENSSL_NPN_NEGOTIATED
1950/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1951static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001952_advertiseNPN_cb(SSL *s,
1953 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001954 void *args)
1955{
1956 PySSLContext *ssl_ctx = (PySSLContext *) args;
1957
1958 if (ssl_ctx->npn_protocols == NULL) {
1959 *data = (unsigned char *) "";
1960 *len = 0;
1961 } else {
1962 *data = (unsigned char *) ssl_ctx->npn_protocols;
1963 *len = ssl_ctx->npn_protocols_len;
1964 }
1965
1966 return SSL_TLSEXT_ERR_OK;
1967}
1968/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1969static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001970_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001971 unsigned char **out, unsigned char *outlen,
1972 const unsigned char *server, unsigned int server_len,
1973 void *args)
1974{
1975 PySSLContext *ssl_ctx = (PySSLContext *) args;
1976
1977 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1978 int client_len;
1979
1980 if (client == NULL) {
1981 client = (unsigned char *) "";
1982 client_len = 0;
1983 } else {
1984 client_len = ssl_ctx->npn_protocols_len;
1985 }
1986
1987 SSL_select_next_proto(out, outlen,
1988 server, server_len,
1989 client, client_len);
1990
1991 return SSL_TLSEXT_ERR_OK;
1992}
1993#endif
1994
1995static PyObject *
1996_set_npn_protocols(PySSLContext *self, PyObject *args)
1997{
1998#ifdef OPENSSL_NPN_NEGOTIATED
1999 Py_buffer protos;
2000
2001 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2002 return NULL;
2003
Christian Heimes5cb31c92012-09-20 12:42:54 +02002004 if (self->npn_protocols != NULL) {
2005 PyMem_Free(self->npn_protocols);
2006 }
2007
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002008 self->npn_protocols = PyMem_Malloc(protos.len);
2009 if (self->npn_protocols == NULL) {
2010 PyBuffer_Release(&protos);
2011 return PyErr_NoMemory();
2012 }
2013 memcpy(self->npn_protocols, protos.buf, protos.len);
2014 self->npn_protocols_len = (int) protos.len;
2015
2016 /* set both server and client callbacks, because the context can
2017 * be used to create both types of sockets */
2018 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2019 _advertiseNPN_cb,
2020 self);
2021 SSL_CTX_set_next_proto_select_cb(self->ctx,
2022 _selectNPN_cb,
2023 self);
2024
2025 PyBuffer_Release(&protos);
2026 Py_RETURN_NONE;
2027#else
2028 PyErr_SetString(PyExc_NotImplementedError,
2029 "The NPN extension requires OpenSSL 1.0.1 or later.");
2030 return NULL;
2031#endif
2032}
2033
Antoine Pitrou152efa22010-05-16 18:19:27 +00002034static PyObject *
2035get_verify_mode(PySSLContext *self, void *c)
2036{
2037 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2038 case SSL_VERIFY_NONE:
2039 return PyLong_FromLong(PY_SSL_CERT_NONE);
2040 case SSL_VERIFY_PEER:
2041 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2042 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2043 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2044 }
2045 PyErr_SetString(PySSLErrorObject,
2046 "invalid return value from SSL_CTX_get_verify_mode");
2047 return NULL;
2048}
2049
2050static int
2051set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2052{
2053 int n, mode;
2054 if (!PyArg_Parse(arg, "i", &n))
2055 return -1;
2056 if (n == PY_SSL_CERT_NONE)
2057 mode = SSL_VERIFY_NONE;
2058 else if (n == PY_SSL_CERT_OPTIONAL)
2059 mode = SSL_VERIFY_PEER;
2060 else if (n == PY_SSL_CERT_REQUIRED)
2061 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2062 else {
2063 PyErr_SetString(PyExc_ValueError,
2064 "invalid value for verify_mode");
2065 return -1;
2066 }
2067 SSL_CTX_set_verify(self->ctx, mode, NULL);
2068 return 0;
2069}
2070
2071static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002072get_options(PySSLContext *self, void *c)
2073{
2074 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2075}
2076
2077static int
2078set_options(PySSLContext *self, PyObject *arg, void *c)
2079{
2080 long new_opts, opts, set, clear;
2081 if (!PyArg_Parse(arg, "l", &new_opts))
2082 return -1;
2083 opts = SSL_CTX_get_options(self->ctx);
2084 clear = opts & ~new_opts;
2085 set = ~opts & new_opts;
2086 if (clear) {
2087#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2088 SSL_CTX_clear_options(self->ctx, clear);
2089#else
2090 PyErr_SetString(PyExc_ValueError,
2091 "can't clear options before OpenSSL 0.9.8m");
2092 return -1;
2093#endif
2094 }
2095 if (set)
2096 SSL_CTX_set_options(self->ctx, set);
2097 return 0;
2098}
2099
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002100typedef struct {
2101 PyThreadState *thread_state;
2102 PyObject *callable;
2103 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002104 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002105 int error;
2106} _PySSLPasswordInfo;
2107
2108static int
2109_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2110 const char *bad_type_error)
2111{
2112 /* Set the password and size fields of a _PySSLPasswordInfo struct
2113 from a unicode, bytes, or byte array object.
2114 The password field will be dynamically allocated and must be freed
2115 by the caller */
2116 PyObject *password_bytes = NULL;
2117 const char *data = NULL;
2118 Py_ssize_t size;
2119
2120 if (PyUnicode_Check(password)) {
2121 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2122 if (!password_bytes) {
2123 goto error;
2124 }
2125 data = PyBytes_AS_STRING(password_bytes);
2126 size = PyBytes_GET_SIZE(password_bytes);
2127 } else if (PyBytes_Check(password)) {
2128 data = PyBytes_AS_STRING(password);
2129 size = PyBytes_GET_SIZE(password);
2130 } else if (PyByteArray_Check(password)) {
2131 data = PyByteArray_AS_STRING(password);
2132 size = PyByteArray_GET_SIZE(password);
2133 } else {
2134 PyErr_SetString(PyExc_TypeError, bad_type_error);
2135 goto error;
2136 }
2137
Victor Stinner9ee02032013-06-23 15:08:23 +02002138 if (size > (Py_ssize_t)INT_MAX) {
2139 PyErr_Format(PyExc_ValueError,
2140 "password cannot be longer than %d bytes", INT_MAX);
2141 goto error;
2142 }
2143
Victor Stinner11ebff22013-07-07 17:07:52 +02002144 PyMem_Free(pw_info->password);
2145 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002146 if (!pw_info->password) {
2147 PyErr_SetString(PyExc_MemoryError,
2148 "unable to allocate password buffer");
2149 goto error;
2150 }
2151 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002152 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002153
2154 Py_XDECREF(password_bytes);
2155 return 1;
2156
2157error:
2158 Py_XDECREF(password_bytes);
2159 return 0;
2160}
2161
2162static int
2163_password_callback(char *buf, int size, int rwflag, void *userdata)
2164{
2165 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2166 PyObject *fn_ret = NULL;
2167
2168 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2169
2170 if (pw_info->callable) {
2171 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2172 if (!fn_ret) {
2173 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2174 core python API, so we could use it to add a frame here */
2175 goto error;
2176 }
2177
2178 if (!_pwinfo_set(pw_info, fn_ret,
2179 "password callback must return a string")) {
2180 goto error;
2181 }
2182 Py_CLEAR(fn_ret);
2183 }
2184
2185 if (pw_info->size > size) {
2186 PyErr_Format(PyExc_ValueError,
2187 "password cannot be longer than %d bytes", size);
2188 goto error;
2189 }
2190
2191 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2192 memcpy(buf, pw_info->password, pw_info->size);
2193 return pw_info->size;
2194
2195error:
2196 Py_XDECREF(fn_ret);
2197 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2198 pw_info->error = 1;
2199 return -1;
2200}
2201
Antoine Pitroub5218772010-05-21 09:56:06 +00002202static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002203load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2204{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002205 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2206 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002208 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2209 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2210 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 int r;
2212
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002213 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002214 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002215 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002216 "O|OO:load_cert_chain", kwlist,
2217 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002218 return NULL;
2219 if (keyfile == Py_None)
2220 keyfile = NULL;
2221 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2222 PyErr_SetString(PyExc_TypeError,
2223 "certfile should be a valid filesystem path");
2224 return NULL;
2225 }
2226 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2227 PyErr_SetString(PyExc_TypeError,
2228 "keyfile should be a valid filesystem path");
2229 goto error;
2230 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002231 if (password && password != Py_None) {
2232 if (PyCallable_Check(password)) {
2233 pw_info.callable = password;
2234 } else if (!_pwinfo_set(&pw_info, password,
2235 "password should be a string or callable")) {
2236 goto error;
2237 }
2238 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2239 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2240 }
2241 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002242 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2243 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002244 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002245 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002246 if (pw_info.error) {
2247 ERR_clear_error();
2248 /* the password callback has already set the error information */
2249 }
2250 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002251 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002252 PyErr_SetFromErrno(PyExc_IOError);
2253 }
2254 else {
2255 _setSSLError(NULL, 0, __FILE__, __LINE__);
2256 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002257 goto error;
2258 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002259 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002260 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002261 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2262 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002263 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2264 Py_CLEAR(keyfile_bytes);
2265 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002266 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002267 if (pw_info.error) {
2268 ERR_clear_error();
2269 /* the password callback has already set the error information */
2270 }
2271 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002272 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002273 PyErr_SetFromErrno(PyExc_IOError);
2274 }
2275 else {
2276 _setSSLError(NULL, 0, __FILE__, __LINE__);
2277 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002278 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002279 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002280 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002281 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002282 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002283 if (r != 1) {
2284 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002285 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002286 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002287 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2288 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002289 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002290 Py_RETURN_NONE;
2291
2292error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002293 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2294 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002295 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296 Py_XDECREF(keyfile_bytes);
2297 Py_XDECREF(certfile_bytes);
2298 return NULL;
2299}
2300
2301static PyObject *
2302load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2303{
2304 char *kwlist[] = {"cafile", "capath", NULL};
2305 PyObject *cafile = NULL, *capath = NULL;
2306 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2307 const char *cafile_buf = NULL, *capath_buf = NULL;
2308 int r;
2309
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002310 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002311 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2312 "|OO:load_verify_locations", kwlist,
2313 &cafile, &capath))
2314 return NULL;
2315 if (cafile == Py_None)
2316 cafile = NULL;
2317 if (capath == Py_None)
2318 capath = NULL;
2319 if (cafile == NULL && capath == NULL) {
2320 PyErr_SetString(PyExc_TypeError,
2321 "cafile and capath cannot be both omitted");
2322 return NULL;
2323 }
2324 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2325 PyErr_SetString(PyExc_TypeError,
2326 "cafile should be a valid filesystem path");
2327 return NULL;
2328 }
2329 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002330 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331 PyErr_SetString(PyExc_TypeError,
2332 "capath should be a valid filesystem path");
2333 return NULL;
2334 }
2335 if (cafile)
2336 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2337 if (capath)
2338 capath_buf = PyBytes_AS_STRING(capath_bytes);
2339 PySSL_BEGIN_ALLOW_THREADS
2340 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2341 PySSL_END_ALLOW_THREADS
2342 Py_XDECREF(cafile_bytes);
2343 Py_XDECREF(capath_bytes);
2344 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002345 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002346 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002347 PyErr_SetFromErrno(PyExc_IOError);
2348 }
2349 else {
2350 _setSSLError(NULL, 0, __FILE__, __LINE__);
2351 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002352 return NULL;
2353 }
2354 Py_RETURN_NONE;
2355}
2356
2357static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002358load_dh_params(PySSLContext *self, PyObject *filepath)
2359{
2360 FILE *f;
2361 DH *dh;
2362
Victor Stinnerdaf45552013-08-28 00:53:59 +02002363 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002364 if (f == NULL) {
2365 if (!PyErr_Occurred())
2366 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2367 return NULL;
2368 }
2369 errno = 0;
2370 PySSL_BEGIN_ALLOW_THREADS
2371 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002372 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002373 PySSL_END_ALLOW_THREADS
2374 if (dh == NULL) {
2375 if (errno != 0) {
2376 ERR_clear_error();
2377 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2378 }
2379 else {
2380 _setSSLError(NULL, 0, __FILE__, __LINE__);
2381 }
2382 return NULL;
2383 }
2384 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2385 _setSSLError(NULL, 0, __FILE__, __LINE__);
2386 DH_free(dh);
2387 Py_RETURN_NONE;
2388}
2389
2390static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002391context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2392{
Antoine Pitroud5323212010-10-22 18:19:07 +00002393 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002394 PySocketSockObject *sock;
2395 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002396 char *hostname = NULL;
2397 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002398
Antoine Pitroud5323212010-10-22 18:19:07 +00002399 /* server_hostname is either None (or absent), or to be encoded
2400 using the idna encoding. */
2401 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002402 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002403 &sock, &server_side,
2404 Py_TYPE(Py_None), &hostname_obj)) {
2405 PyErr_Clear();
2406 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2407 PySocketModule.Sock_Type,
2408 &sock, &server_side,
2409 "idna", &hostname))
2410 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002411#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002412 PyMem_Free(hostname);
2413 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2414 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002415 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002416#endif
2417 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002418
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002419 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002420 hostname);
2421 if (hostname != NULL)
2422 PyMem_Free(hostname);
2423 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002424}
2425
Antoine Pitroub0182c82010-10-12 20:09:02 +00002426static PyObject *
2427session_stats(PySSLContext *self, PyObject *unused)
2428{
2429 int r;
2430 PyObject *value, *stats = PyDict_New();
2431 if (!stats)
2432 return NULL;
2433
2434#define ADD_STATS(SSL_NAME, KEY_NAME) \
2435 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2436 if (value == NULL) \
2437 goto error; \
2438 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2439 Py_DECREF(value); \
2440 if (r < 0) \
2441 goto error;
2442
2443 ADD_STATS(number, "number");
2444 ADD_STATS(connect, "connect");
2445 ADD_STATS(connect_good, "connect_good");
2446 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2447 ADD_STATS(accept, "accept");
2448 ADD_STATS(accept_good, "accept_good");
2449 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2450 ADD_STATS(accept, "accept");
2451 ADD_STATS(hits, "hits");
2452 ADD_STATS(misses, "misses");
2453 ADD_STATS(timeouts, "timeouts");
2454 ADD_STATS(cache_full, "cache_full");
2455
2456#undef ADD_STATS
2457
2458 return stats;
2459
2460error:
2461 Py_DECREF(stats);
2462 return NULL;
2463}
2464
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002465static PyObject *
2466set_default_verify_paths(PySSLContext *self, PyObject *unused)
2467{
2468 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2469 _setSSLError(NULL, 0, __FILE__, __LINE__);
2470 return NULL;
2471 }
2472 Py_RETURN_NONE;
2473}
2474
Antoine Pitrou501da612011-12-21 09:27:41 +01002475#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002476static PyObject *
2477set_ecdh_curve(PySSLContext *self, PyObject *name)
2478{
2479 PyObject *name_bytes;
2480 int nid;
2481 EC_KEY *key;
2482
2483 if (!PyUnicode_FSConverter(name, &name_bytes))
2484 return NULL;
2485 assert(PyBytes_Check(name_bytes));
2486 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2487 Py_DECREF(name_bytes);
2488 if (nid == 0) {
2489 PyErr_Format(PyExc_ValueError,
2490 "unknown elliptic curve name %R", name);
2491 return NULL;
2492 }
2493 key = EC_KEY_new_by_curve_name(nid);
2494 if (key == NULL) {
2495 _setSSLError(NULL, 0, __FILE__, __LINE__);
2496 return NULL;
2497 }
2498 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2499 EC_KEY_free(key);
2500 Py_RETURN_NONE;
2501}
Antoine Pitrou501da612011-12-21 09:27:41 +01002502#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002503
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002504#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002505static int
2506_servername_callback(SSL *s, int *al, void *args)
2507{
2508 int ret;
2509 PySSLContext *ssl_ctx = (PySSLContext *) args;
2510 PySSLSocket *ssl;
2511 PyObject *servername_o;
2512 PyObject *servername_idna;
2513 PyObject *result;
2514 /* The high-level ssl.SSLSocket object */
2515 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002516 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002517#ifdef WITH_THREAD
2518 PyGILState_STATE gstate = PyGILState_Ensure();
2519#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002520
2521 if (ssl_ctx->set_hostname == NULL) {
2522 /* remove race condition in this the call back while if removing the
2523 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002524#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002525 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002526#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002527 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002528 }
2529
2530 ssl = SSL_get_app_data(s);
2531 assert(PySSLSocket_Check(ssl));
2532 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2533 Py_INCREF(ssl_socket);
2534 if (ssl_socket == Py_None) {
2535 goto error;
2536 }
Victor Stinner7e001512013-06-25 00:44:31 +02002537
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002538 if (servername == NULL) {
2539 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2540 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002541 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002542 else {
2543 servername_o = PyBytes_FromString(servername);
2544 if (servername_o == NULL) {
2545 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2546 goto error;
2547 }
2548 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2549 if (servername_idna == NULL) {
2550 PyErr_WriteUnraisable(servername_o);
2551 Py_DECREF(servername_o);
2552 goto error;
2553 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002554 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002555 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2556 servername_idna, ssl_ctx, NULL);
2557 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002558 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002559 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002560
2561 if (result == NULL) {
2562 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2563 *al = SSL_AD_HANDSHAKE_FAILURE;
2564 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2565 }
2566 else {
2567 if (result != Py_None) {
2568 *al = (int) PyLong_AsLong(result);
2569 if (PyErr_Occurred()) {
2570 PyErr_WriteUnraisable(result);
2571 *al = SSL_AD_INTERNAL_ERROR;
2572 }
2573 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2574 }
2575 else {
2576 ret = SSL_TLSEXT_ERR_OK;
2577 }
2578 Py_DECREF(result);
2579 }
2580
Stefan Krah20d60802013-01-17 17:07:17 +01002581#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002582 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002583#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002584 return ret;
2585
2586error:
2587 Py_DECREF(ssl_socket);
2588 *al = SSL_AD_INTERNAL_ERROR;
2589 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002590#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002591 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002592#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002593 return ret;
2594}
Antoine Pitroua5963382013-03-30 16:39:00 +01002595#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002596
2597PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2598"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002599\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002600This sets a callback that will be called when a server name is provided by\n\
2601the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002602\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002603If the argument is None then the callback is disabled. The method is called\n\
2604with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002605See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002606
2607static PyObject *
2608set_servername_callback(PySSLContext *self, PyObject *args)
2609{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002610#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002611 PyObject *cb;
2612
2613 if (!PyArg_ParseTuple(args, "O", &cb))
2614 return NULL;
2615
2616 Py_CLEAR(self->set_hostname);
2617 if (cb == Py_None) {
2618 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2619 }
2620 else {
2621 if (!PyCallable_Check(cb)) {
2622 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2623 PyErr_SetString(PyExc_TypeError,
2624 "not a callable object");
2625 return NULL;
2626 }
2627 Py_INCREF(cb);
2628 self->set_hostname = cb;
2629 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2630 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2631 }
2632 Py_RETURN_NONE;
2633#else
2634 PyErr_SetString(PyExc_NotImplementedError,
2635 "The TLS extension servername callback, "
2636 "SSL_CTX_set_tlsext_servername_callback, "
2637 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002638 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002639#endif
2640}
2641
Christian Heimes9a5395a2013-06-17 15:44:12 +02002642PyDoc_STRVAR(PySSL_get_stats_doc,
2643"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2644\n\
2645Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2646CA extension and certificate revocation lists inside the context's cert\n\
2647store.\n\
2648NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2649been used at least once.");
2650
2651static PyObject *
2652cert_store_stats(PySSLContext *self)
2653{
2654 X509_STORE *store;
2655 X509_OBJECT *obj;
2656 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2657
2658 store = SSL_CTX_get_cert_store(self->ctx);
2659 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2660 obj = sk_X509_OBJECT_value(store->objs, i);
2661 switch (obj->type) {
2662 case X509_LU_X509:
2663 x509++;
2664 if (X509_check_ca(obj->data.x509)) {
2665 ca++;
2666 }
2667 break;
2668 case X509_LU_CRL:
2669 crl++;
2670 break;
2671 case X509_LU_PKEY:
2672 pkey++;
2673 break;
2674 default:
2675 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2676 * As far as I can tell they are internal states and never
2677 * stored in a cert store */
2678 break;
2679 }
2680 }
2681 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2682 "x509_ca", ca);
2683}
2684
2685PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2686"get_ca_certs([der=False]) -> list of loaded certificate\n\
2687\n\
2688Returns a list of dicts with information of loaded CA certs. If the\n\
2689optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2690NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2691been used at least once.");
2692
2693static PyObject *
2694get_ca_certs(PySSLContext *self, PyObject *args)
2695{
2696 X509_STORE *store;
2697 PyObject *ci = NULL, *rlist = NULL;
2698 int i;
2699 int binary_mode = 0;
2700
2701 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2702 return NULL;
2703 }
2704
2705 if ((rlist = PyList_New(0)) == NULL) {
2706 return NULL;
2707 }
2708
2709 store = SSL_CTX_get_cert_store(self->ctx);
2710 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2711 X509_OBJECT *obj;
2712 X509 *cert;
2713
2714 obj = sk_X509_OBJECT_value(store->objs, i);
2715 if (obj->type != X509_LU_X509) {
2716 /* not a x509 cert */
2717 continue;
2718 }
2719 /* CA for any purpose */
2720 cert = obj->data.x509;
2721 if (!X509_check_ca(cert)) {
2722 continue;
2723 }
2724 if (binary_mode) {
2725 ci = _certificate_to_der(cert);
2726 } else {
2727 ci = _decode_certificate(cert);
2728 }
2729 if (ci == NULL) {
2730 goto error;
2731 }
2732 if (PyList_Append(rlist, ci) == -1) {
2733 goto error;
2734 }
2735 Py_CLEAR(ci);
2736 }
2737 return rlist;
2738
2739 error:
2740 Py_XDECREF(ci);
2741 Py_XDECREF(rlist);
2742 return NULL;
2743}
2744
2745
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002747 {"options", (getter) get_options,
2748 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002749 {"verify_mode", (getter) get_verify_mode,
2750 (setter) set_verify_mode, NULL},
2751 {NULL}, /* sentinel */
2752};
2753
2754static struct PyMethodDef context_methods[] = {
2755 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2756 METH_VARARGS | METH_KEYWORDS, NULL},
2757 {"set_ciphers", (PyCFunction) set_ciphers,
2758 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002759 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2760 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002761 {"load_cert_chain", (PyCFunction) load_cert_chain,
2762 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002763 {"load_dh_params", (PyCFunction) load_dh_params,
2764 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765 {"load_verify_locations", (PyCFunction) load_verify_locations,
2766 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002767 {"session_stats", (PyCFunction) session_stats,
2768 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002769 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2770 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002771#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002772 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2773 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002774#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002775 {"set_servername_callback", (PyCFunction) set_servername_callback,
2776 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002777 {"cert_store_stats", (PyCFunction) cert_store_stats,
2778 METH_NOARGS, PySSL_get_stats_doc},
2779 {"get_ca_certs", (PyCFunction) get_ca_certs,
2780 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002781 {NULL, NULL} /* sentinel */
2782};
2783
2784static PyTypeObject PySSLContext_Type = {
2785 PyVarObject_HEAD_INIT(NULL, 0)
2786 "_ssl._SSLContext", /*tp_name*/
2787 sizeof(PySSLContext), /*tp_basicsize*/
2788 0, /*tp_itemsize*/
2789 (destructor)context_dealloc, /*tp_dealloc*/
2790 0, /*tp_print*/
2791 0, /*tp_getattr*/
2792 0, /*tp_setattr*/
2793 0, /*tp_reserved*/
2794 0, /*tp_repr*/
2795 0, /*tp_as_number*/
2796 0, /*tp_as_sequence*/
2797 0, /*tp_as_mapping*/
2798 0, /*tp_hash*/
2799 0, /*tp_call*/
2800 0, /*tp_str*/
2801 0, /*tp_getattro*/
2802 0, /*tp_setattro*/
2803 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002804 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002806 (traverseproc) context_traverse, /*tp_traverse*/
2807 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808 0, /*tp_richcompare*/
2809 0, /*tp_weaklistoffset*/
2810 0, /*tp_iter*/
2811 0, /*tp_iternext*/
2812 context_methods, /*tp_methods*/
2813 0, /*tp_members*/
2814 context_getsetlist, /*tp_getset*/
2815 0, /*tp_base*/
2816 0, /*tp_dict*/
2817 0, /*tp_descr_get*/
2818 0, /*tp_descr_set*/
2819 0, /*tp_dictoffset*/
2820 0, /*tp_init*/
2821 0, /*tp_alloc*/
2822 context_new, /*tp_new*/
2823};
2824
2825
2826
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002827#ifdef HAVE_OPENSSL_RAND
2828
2829/* helper routines for seeding the SSL PRNG */
2830static PyObject *
2831PySSL_RAND_add(PyObject *self, PyObject *args)
2832{
2833 char *buf;
2834 int len;
2835 double entropy;
2836
2837 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002838 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002839 RAND_add(buf, len, entropy);
2840 Py_INCREF(Py_None);
2841 return Py_None;
2842}
2843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002844PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002845"RAND_add(string, entropy)\n\
2846\n\
2847Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002848bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849
2850static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002851PySSL_RAND(int len, int pseudo)
2852{
2853 int ok;
2854 PyObject *bytes;
2855 unsigned long err;
2856 const char *errstr;
2857 PyObject *v;
2858
2859 bytes = PyBytes_FromStringAndSize(NULL, len);
2860 if (bytes == NULL)
2861 return NULL;
2862 if (pseudo) {
2863 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2864 if (ok == 0 || ok == 1)
2865 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2866 }
2867 else {
2868 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2869 if (ok == 1)
2870 return bytes;
2871 }
2872 Py_DECREF(bytes);
2873
2874 err = ERR_get_error();
2875 errstr = ERR_reason_error_string(err);
2876 v = Py_BuildValue("(ks)", err, errstr);
2877 if (v != NULL) {
2878 PyErr_SetObject(PySSLErrorObject, v);
2879 Py_DECREF(v);
2880 }
2881 return NULL;
2882}
2883
2884static PyObject *
2885PySSL_RAND_bytes(PyObject *self, PyObject *args)
2886{
2887 int len;
2888 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2889 return NULL;
2890 return PySSL_RAND(len, 0);
2891}
2892
2893PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2894"RAND_bytes(n) -> bytes\n\
2895\n\
2896Generate n cryptographically strong pseudo-random bytes.");
2897
2898static PyObject *
2899PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2900{
2901 int len;
2902 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2903 return NULL;
2904 return PySSL_RAND(len, 1);
2905}
2906
2907PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2908"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2909\n\
2910Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2911generated are cryptographically strong.");
2912
2913static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002914PySSL_RAND_status(PyObject *self)
2915{
Christian Heimes217cfd12007-12-02 14:31:20 +00002916 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002917}
2918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002919PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002920"RAND_status() -> 0 or 1\n\
2921\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002922Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2923It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2924using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002925
2926static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002927PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002928{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002929 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002930 int bytes;
2931
Jesus Ceac8754a12012-09-11 02:00:58 +02002932 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002933 PyUnicode_FSConverter, &path))
2934 return NULL;
2935
2936 bytes = RAND_egd(PyBytes_AsString(path));
2937 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002938 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002939 PyErr_SetString(PySSLErrorObject,
2940 "EGD connection failed or EGD did not return "
2941 "enough data to seed the PRNG");
2942 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002943 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002944 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002945}
2946
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002947PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002948"RAND_egd(path) -> bytes\n\
2949\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002950Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2951Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002952fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002953
Christian Heimesf77b4b22013-08-21 13:26:05 +02002954#endif /* HAVE_OPENSSL_RAND */
2955
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002956
Christian Heimes6d7ad132013-06-09 18:02:55 +02002957PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2958"get_default_verify_paths() -> tuple\n\
2959\n\
2960Return search paths and environment vars that are used by SSLContext's\n\
2961set_default_verify_paths() to load default CAs. The values are\n\
2962'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2963
2964static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002965PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002966{
2967 PyObject *ofile_env = NULL;
2968 PyObject *ofile = NULL;
2969 PyObject *odir_env = NULL;
2970 PyObject *odir = NULL;
2971
2972#define convert(info, target) { \
2973 const char *tmp = (info); \
2974 target = NULL; \
2975 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2976 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2977 target = PyBytes_FromString(tmp); } \
2978 if (!target) goto error; \
2979 } while(0)
2980
2981 convert(X509_get_default_cert_file_env(), ofile_env);
2982 convert(X509_get_default_cert_file(), ofile);
2983 convert(X509_get_default_cert_dir_env(), odir_env);
2984 convert(X509_get_default_cert_dir(), odir);
2985#undef convert
2986
Christian Heimes200bb1b2013-06-14 15:14:29 +02002987 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002988
2989 error:
2990 Py_XDECREF(ofile_env);
2991 Py_XDECREF(ofile);
2992 Py_XDECREF(odir_env);
2993 Py_XDECREF(odir);
2994 return NULL;
2995}
2996
Christian Heimes46bebee2013-06-09 19:03:31 +02002997#ifdef _MSC_VER
2998PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2999"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3000\n\
3001Retrieve certificates from Windows' cert store. store_name may be one of\n\
3002'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3003cert_type must be either 'certificate' or 'crl'.\n\
3004The function returns a list of (bytes, encoding_type) tuples. The\n\
3005encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3006PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003007
Christian Heimes46bebee2013-06-09 19:03:31 +02003008static PyObject *
3009PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3010{
3011 char *kwlist[] = {"store_name", "cert_type", NULL};
3012 char *store_name;
3013 char *cert_type = "certificate";
3014 HCERTSTORE hStore = NULL;
3015 PyObject *result = NULL;
3016 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3017 int ok = 1;
3018
3019 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3020 kwlist, &store_name, &cert_type)) {
3021 return NULL;
3022 }
3023
3024 if ((strcmp(cert_type, "certificate") != 0) &&
3025 (strcmp(cert_type, "crl") != 0)) {
3026 return PyErr_Format(PyExc_ValueError,
3027 "cert_type must be 'certificate' or 'crl', "
3028 "not %.100s", cert_type);
3029 }
3030
3031 if ((result = PyList_New(0)) == NULL) {
3032 return NULL;
3033 }
3034
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003035 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003036 Py_DECREF(result);
3037 return PyErr_SetFromWindowsErr(GetLastError());
3038 }
3039
3040 if (strcmp(cert_type, "certificate") == 0) {
3041 PCCERT_CONTEXT pCertCtx = NULL;
3042 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3043 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3044 pCertCtx->cbCertEncoded);
3045 if (!cert) {
3046 ok = 0;
3047 break;
3048 }
3049 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3050 ok = 0;
3051 break;
3052 }
3053 if ((tup = PyTuple_New(2)) == NULL) {
3054 ok = 0;
3055 break;
3056 }
3057 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3058 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3059
3060 if (PyList_Append(result, tup) < 0) {
3061 ok = 0;
3062 break;
3063 }
3064 Py_CLEAR(tup);
3065 }
3066 if (pCertCtx) {
3067 /* loop ended with an error, need to clean up context manually */
3068 CertFreeCertificateContext(pCertCtx);
3069 }
3070 } else {
3071 PCCRL_CONTEXT pCrlCtx = NULL;
3072 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3073 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3074 pCrlCtx->cbCrlEncoded);
3075 if (!cert) {
3076 ok = 0;
3077 break;
3078 }
3079 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3080 ok = 0;
3081 break;
3082 }
3083 if ((tup = PyTuple_New(2)) == NULL) {
3084 ok = 0;
3085 break;
3086 }
3087 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3088 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3089
3090 if (PyList_Append(result, tup) < 0) {
3091 ok = 0;
3092 break;
3093 }
3094 Py_CLEAR(tup);
3095 }
3096 if (pCrlCtx) {
3097 /* loop ended with an error, need to clean up context manually */
3098 CertFreeCRLContext(pCrlCtx);
3099 }
3100 }
3101
3102 /* In error cases cert, enc and tup may not be NULL */
3103 Py_XDECREF(cert);
3104 Py_XDECREF(enc);
3105 Py_XDECREF(tup);
3106
3107 if (!CertCloseStore(hStore, 0)) {
3108 /* This error case might shadow another exception.*/
3109 Py_DECREF(result);
3110 return PyErr_SetFromWindowsErr(GetLastError());
3111 }
3112 if (ok) {
3113 return result;
3114 } else {
3115 Py_DECREF(result);
3116 return NULL;
3117 }
3118}
3119#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003120
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003121/* List of functions exported by this module. */
3122
3123static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003124 {"_test_decode_cert", PySSL_test_decode_certificate,
3125 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003126#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003127 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3128 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003129 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3130 PySSL_RAND_bytes_doc},
3131 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3132 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003133 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003134 PySSL_RAND_egd_doc},
3135 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3136 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003137#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003138 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003139 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003140#ifdef _MSC_VER
3141 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3142 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3143#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003144 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003145};
3146
3147
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003148#ifdef WITH_THREAD
3149
3150/* an implementation of OpenSSL threading operations in terms
3151 of the Python C thread library */
3152
3153static PyThread_type_lock *_ssl_locks = NULL;
3154
Christian Heimes4d98ca92013-08-19 17:36:29 +02003155#if OPENSSL_VERSION_NUMBER >= 0x10000000
3156/* use new CRYPTO_THREADID API. */
3157static void
3158_ssl_threadid_callback(CRYPTO_THREADID *id)
3159{
3160 CRYPTO_THREADID_set_numeric(id,
3161 (unsigned long)PyThread_get_thread_ident());
3162}
3163#else
3164/* deprecated CRYPTO_set_id_callback() API. */
3165static unsigned long
3166_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003167 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003168}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003169#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003170
Bill Janssen6e027db2007-11-15 22:23:56 +00003171static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003172 (int mode, int n, const char *file, int line) {
3173 /* this function is needed to perform locking on shared data
3174 structures. (Note that OpenSSL uses a number of global data
3175 structures that will be implicitly shared whenever multiple
3176 threads use OpenSSL.) Multi-threaded applications will
3177 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003179 locking_function() must be able to handle up to
3180 CRYPTO_num_locks() different mutex locks. It sets the n-th
3181 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003183 file and line are the file number of the function setting the
3184 lock. They can be useful for debugging.
3185 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003187 if ((_ssl_locks == NULL) ||
3188 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3189 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003191 if (mode & CRYPTO_LOCK) {
3192 PyThread_acquire_lock(_ssl_locks[n], 1);
3193 } else {
3194 PyThread_release_lock(_ssl_locks[n]);
3195 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003196}
3197
3198static int _setup_ssl_threads(void) {
3199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003200 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003202 if (_ssl_locks == NULL) {
3203 _ssl_locks_count = CRYPTO_num_locks();
3204 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003205 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003206 if (_ssl_locks == NULL)
3207 return 0;
3208 memset(_ssl_locks, 0,
3209 sizeof(PyThread_type_lock) * _ssl_locks_count);
3210 for (i = 0; i < _ssl_locks_count; i++) {
3211 _ssl_locks[i] = PyThread_allocate_lock();
3212 if (_ssl_locks[i] == NULL) {
3213 unsigned int j;
3214 for (j = 0; j < i; j++) {
3215 PyThread_free_lock(_ssl_locks[j]);
3216 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003217 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003218 return 0;
3219 }
3220 }
3221 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003222#if OPENSSL_VERSION_NUMBER >= 0x10000000
3223 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3224#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003225 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003226#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003227 }
3228 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003229}
3230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003231#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003233PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003234"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003235for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003236
Martin v. Löwis1a214512008-06-11 05:26:20 +00003237
3238static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003239 PyModuleDef_HEAD_INIT,
3240 "_ssl",
3241 module_doc,
3242 -1,
3243 PySSL_methods,
3244 NULL,
3245 NULL,
3246 NULL,
3247 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003248};
3249
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003250
3251static void
3252parse_openssl_version(unsigned long libver,
3253 unsigned int *major, unsigned int *minor,
3254 unsigned int *fix, unsigned int *patch,
3255 unsigned int *status)
3256{
3257 *status = libver & 0xF;
3258 libver >>= 4;
3259 *patch = libver & 0xFF;
3260 libver >>= 8;
3261 *fix = libver & 0xFF;
3262 libver >>= 8;
3263 *minor = libver & 0xFF;
3264 libver >>= 8;
3265 *major = libver & 0xFF;
3266}
3267
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003268PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003269PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003270{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003271 PyObject *m, *d, *r;
3272 unsigned long libver;
3273 unsigned int major, minor, fix, patch, status;
3274 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003275 struct py_ssl_error_code *errcode;
3276 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003277
Antoine Pitrou152efa22010-05-16 18:19:27 +00003278 if (PyType_Ready(&PySSLContext_Type) < 0)
3279 return NULL;
3280 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003281 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003283 m = PyModule_Create(&_sslmodule);
3284 if (m == NULL)
3285 return NULL;
3286 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003288 /* Load _socket module and its C API */
3289 socket_api = PySocketModule_ImportModuleAndAPI();
3290 if (!socket_api)
3291 return NULL;
3292 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003294 /* Init OpenSSL */
3295 SSL_load_error_strings();
3296 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003297#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003298 /* note that this will start threading if not already started */
3299 if (!_setup_ssl_threads()) {
3300 return NULL;
3301 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003302#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003303 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003305 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003306 sslerror_type_slots[0].pfunc = PyExc_OSError;
3307 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003308 if (PySSLErrorObject == NULL)
3309 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003310
Antoine Pitrou41032a62011-10-27 23:56:55 +02003311 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3312 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3313 PySSLErrorObject, NULL);
3314 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3315 "ssl.SSLWantReadError", SSLWantReadError_doc,
3316 PySSLErrorObject, NULL);
3317 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3318 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3319 PySSLErrorObject, NULL);
3320 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3321 "ssl.SSLSyscallError", SSLSyscallError_doc,
3322 PySSLErrorObject, NULL);
3323 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3324 "ssl.SSLEOFError", SSLEOFError_doc,
3325 PySSLErrorObject, NULL);
3326 if (PySSLZeroReturnErrorObject == NULL
3327 || PySSLWantReadErrorObject == NULL
3328 || PySSLWantWriteErrorObject == NULL
3329 || PySSLSyscallErrorObject == NULL
3330 || PySSLEOFErrorObject == NULL)
3331 return NULL;
3332 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3333 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3334 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3335 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3336 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3337 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003338 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003339 if (PyDict_SetItemString(d, "_SSLContext",
3340 (PyObject *)&PySSLContext_Type) != 0)
3341 return NULL;
3342 if (PyDict_SetItemString(d, "_SSLSocket",
3343 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003344 return NULL;
3345 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3346 PY_SSL_ERROR_ZERO_RETURN);
3347 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3348 PY_SSL_ERROR_WANT_READ);
3349 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3350 PY_SSL_ERROR_WANT_WRITE);
3351 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3352 PY_SSL_ERROR_WANT_X509_LOOKUP);
3353 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3354 PY_SSL_ERROR_SYSCALL);
3355 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3356 PY_SSL_ERROR_SSL);
3357 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3358 PY_SSL_ERROR_WANT_CONNECT);
3359 /* non ssl.h errorcodes */
3360 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3361 PY_SSL_ERROR_EOF);
3362 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3363 PY_SSL_ERROR_INVALID_ERROR_CODE);
3364 /* cert requirements */
3365 PyModule_AddIntConstant(m, "CERT_NONE",
3366 PY_SSL_CERT_NONE);
3367 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3368 PY_SSL_CERT_OPTIONAL);
3369 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3370 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003371
Christian Heimes46bebee2013-06-09 19:03:31 +02003372#ifdef _MSC_VER
3373 /* Windows dwCertEncodingType */
3374 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3375 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3376#endif
3377
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003378 /* Alert Descriptions from ssl.h */
3379 /* note RESERVED constants no longer intended for use have been removed */
3380 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3381
3382#define ADD_AD_CONSTANT(s) \
3383 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3384 SSL_AD_##s)
3385
3386 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3387 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3388 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3389 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3390 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3391 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3392 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3393 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3394 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3395 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3396 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3397 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3398 ADD_AD_CONSTANT(UNKNOWN_CA);
3399 ADD_AD_CONSTANT(ACCESS_DENIED);
3400 ADD_AD_CONSTANT(DECODE_ERROR);
3401 ADD_AD_CONSTANT(DECRYPT_ERROR);
3402 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3403 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3404 ADD_AD_CONSTANT(INTERNAL_ERROR);
3405 ADD_AD_CONSTANT(USER_CANCELLED);
3406 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003407 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003408#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3409 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3410#endif
3411#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3412 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3413#endif
3414#ifdef SSL_AD_UNRECOGNIZED_NAME
3415 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3416#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003417#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3418 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3419#endif
3420#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3421 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3422#endif
3423#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3424 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3425#endif
3426
3427#undef ADD_AD_CONSTANT
3428
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003429 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003430#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003431 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3432 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003433#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003434 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3435 PY_SSL_VERSION_SSL3);
3436 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3437 PY_SSL_VERSION_SSL23);
3438 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3439 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003440#if HAVE_TLSv1_2
3441 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3442 PY_SSL_VERSION_TLS1_1);
3443 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3444 PY_SSL_VERSION_TLS1_2);
3445#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003446
Antoine Pitroub5218772010-05-21 09:56:06 +00003447 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003448 PyModule_AddIntConstant(m, "OP_ALL",
3449 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003450 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3451 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3452 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003453#if HAVE_TLSv1_2
3454 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3455 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3456#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003457 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3458 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003459 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003460#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003461 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003462#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003463#ifdef SSL_OP_NO_COMPRESSION
3464 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3465 SSL_OP_NO_COMPRESSION);
3466#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003467
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003468#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003469 r = Py_True;
3470#else
3471 r = Py_False;
3472#endif
3473 Py_INCREF(r);
3474 PyModule_AddObject(m, "HAS_SNI", r);
3475
Antoine Pitroud6494802011-07-21 01:11:30 +02003476#if HAVE_OPENSSL_FINISHED
3477 r = Py_True;
3478#else
3479 r = Py_False;
3480#endif
3481 Py_INCREF(r);
3482 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3483
Antoine Pitrou501da612011-12-21 09:27:41 +01003484#ifdef OPENSSL_NO_ECDH
3485 r = Py_False;
3486#else
3487 r = Py_True;
3488#endif
3489 Py_INCREF(r);
3490 PyModule_AddObject(m, "HAS_ECDH", r);
3491
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003492#ifdef OPENSSL_NPN_NEGOTIATED
3493 r = Py_True;
3494#else
3495 r = Py_False;
3496#endif
3497 Py_INCREF(r);
3498 PyModule_AddObject(m, "HAS_NPN", r);
3499
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003500 /* Mappings for error codes */
3501 err_codes_to_names = PyDict_New();
3502 err_names_to_codes = PyDict_New();
3503 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3504 return NULL;
3505 errcode = error_codes;
3506 while (errcode->mnemonic != NULL) {
3507 PyObject *mnemo, *key;
3508 mnemo = PyUnicode_FromString(errcode->mnemonic);
3509 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3510 if (mnemo == NULL || key == NULL)
3511 return NULL;
3512 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3513 return NULL;
3514 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3515 return NULL;
3516 Py_DECREF(key);
3517 Py_DECREF(mnemo);
3518 errcode++;
3519 }
3520 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3521 return NULL;
3522 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3523 return NULL;
3524
3525 lib_codes_to_names = PyDict_New();
3526 if (lib_codes_to_names == NULL)
3527 return NULL;
3528 libcode = library_codes;
3529 while (libcode->library != NULL) {
3530 PyObject *mnemo, *key;
3531 key = PyLong_FromLong(libcode->code);
3532 mnemo = PyUnicode_FromString(libcode->library);
3533 if (key == NULL || mnemo == NULL)
3534 return NULL;
3535 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3536 return NULL;
3537 Py_DECREF(key);
3538 Py_DECREF(mnemo);
3539 libcode++;
3540 }
3541 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3542 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003544 /* OpenSSL version */
3545 /* SSLeay() gives us the version of the library linked against,
3546 which could be different from the headers version.
3547 */
3548 libver = SSLeay();
3549 r = PyLong_FromUnsignedLong(libver);
3550 if (r == NULL)
3551 return NULL;
3552 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3553 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003554 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003555 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3556 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3557 return NULL;
3558 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3559 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3560 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003561
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003562 libver = OPENSSL_VERSION_NUMBER;
3563 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3564 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3565 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3566 return NULL;
3567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003568 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003569}