blob: 448114bd732b188fa1c7bc755d8aeb231109d9cf [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
22#ifdef HAVE_PTHREAD_ATFORK
23# include <pthread.h>
24#endif
25
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
29 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000037#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020039#define PySSL_BEGIN_ALLOW_THREADS_S(save)
40#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041#define PySSL_BEGIN_ALLOW_THREADS
42#define PySSL_BLOCK_THREADS
43#define PySSL_UNBLOCK_THREADS
44#define PySSL_END_ALLOW_THREADS
45
46#endif
47
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000048enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000049 /* these mirror ssl.h */
50 PY_SSL_ERROR_NONE,
51 PY_SSL_ERROR_SSL,
52 PY_SSL_ERROR_WANT_READ,
53 PY_SSL_ERROR_WANT_WRITE,
54 PY_SSL_ERROR_WANT_X509_LOOKUP,
55 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
56 PY_SSL_ERROR_ZERO_RETURN,
57 PY_SSL_ERROR_WANT_CONNECT,
58 /* start of non ssl.h errorcodes */
59 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
60 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
61 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000062};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000063
Thomas Woutersed03b412007-08-28 21:37:11 +000064enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CLIENT,
66 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000067};
68
69enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000070 PY_SSL_CERT_NONE,
71 PY_SSL_CERT_OPTIONAL,
72 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000073};
74
75enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020076#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000077 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020078#endif
79 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000080 PY_SSL_VERSION_SSL23,
81 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000082};
83
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020084struct py_ssl_error_code {
85 const char *mnemonic;
86 int library, reason;
87};
88
89struct py_ssl_library_code {
90 const char *library;
91 int code;
92};
93
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000094/* Include symbols from _socket module */
95#include "socketmodule.h"
96
Benjamin Petersonb173f782009-05-05 22:31:58 +000097static PySocketModule_APIObject PySocketModule;
98
Thomas Woutersed03b412007-08-28 21:37:11 +000099#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000100#include <poll.h>
101#elif defined(HAVE_SYS_POLL_H)
102#include <sys/poll.h>
103#endif
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* Include OpenSSL header files */
106#include "openssl/rsa.h"
107#include "openssl/crypto.h"
108#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000110#include "openssl/pem.h"
111#include "openssl/ssl.h"
112#include "openssl/err.h"
113#include "openssl/rand.h"
114
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200115/* Include generated data (error codes) */
116#include "_ssl_data.h"
117
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000118/* SSL error object */
119static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200120static PyObject *PySSLZeroReturnErrorObject;
121static PyObject *PySSLWantReadErrorObject;
122static PyObject *PySSLWantWriteErrorObject;
123static PyObject *PySSLSyscallErrorObject;
124static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000125
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200126/* Error mappings */
127static PyObject *err_codes_to_names;
128static PyObject *err_names_to_codes;
129static PyObject *lib_codes_to_names;
130
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131#ifdef WITH_THREAD
132
133/* serves as a flag to see whether we've initialized the SSL thread support. */
134/* 0 means no, greater than 0 means yes */
135
136static unsigned int _ssl_locks_count = 0;
137
138#endif /* def WITH_THREAD */
139
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000140/* SSL socket object */
141
142#define X509_NAME_MAXLEN 256
143
144/* RAND_* APIs got added to OpenSSL in 0.9.5 */
145#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
146# define HAVE_OPENSSL_RAND 1
147#else
148# undef HAVE_OPENSSL_RAND
149#endif
150
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000151/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
152 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
153 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
154#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000155# define HAVE_SSL_CTX_CLEAR_OPTIONS
156#else
157# undef HAVE_SSL_CTX_CLEAR_OPTIONS
158#endif
159
Antoine Pitroud6494802011-07-21 01:11:30 +0200160/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
161 * older SSL, but let's be safe */
162#define PySSL_CB_MAXLEN 128
163
164/* SSL_get_finished got added to OpenSSL in 0.9.5 */
165#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
166# define HAVE_OPENSSL_FINISHED 1
167#else
168# define HAVE_OPENSSL_FINISHED 0
169#endif
170
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100171/* ECDH support got added to OpenSSL in 0.9.8 */
172#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
173# define OPENSSL_NO_ECDH
174#endif
175
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100176/* compression support got added to OpenSSL in 0.9.8 */
177#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
178# define OPENSSL_NO_COMP
179#endif
180
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100181
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000182typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000183 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000184 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100185#ifdef OPENSSL_NPN_NEGOTIATED
186 char *npn_protocols;
187 int npn_protocols_len;
188#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000190
Antoine Pitrou152efa22010-05-16 18:19:27 +0000191typedef struct {
192 PyObject_HEAD
193 PyObject *Socket; /* weakref to socket on which we're layered */
194 SSL *ssl;
195 X509 *peer_cert;
196 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200197 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000198} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000199
Antoine Pitrou152efa22010-05-16 18:19:27 +0000200static PyTypeObject PySSLContext_Type;
201static PyTypeObject PySSLSocket_Type;
202
203static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
204static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000205static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
208static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000209
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
211#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000212
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000213typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000214 SOCKET_IS_NONBLOCKING,
215 SOCKET_IS_BLOCKING,
216 SOCKET_HAS_TIMED_OUT,
217 SOCKET_HAS_BEEN_CLOSED,
218 SOCKET_TOO_LARGE_FOR_SELECT,
219 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000220} timeout_state;
221
Thomas Woutersed03b412007-08-28 21:37:11 +0000222/* Wrap error strings with filename and line # */
223#define STRINGIFY1(x) #x
224#define STRINGIFY2(x) STRINGIFY1(x)
225#define ERRSTR1(x,y,z) (x ":" y ": " z)
226#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
227
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200228
229/*
230 * SSL errors.
231 */
232
233PyDoc_STRVAR(SSLError_doc,
234"An error occurred in the SSL implementation.");
235
236PyDoc_STRVAR(SSLZeroReturnError_doc,
237"SSL/TLS session closed cleanly.");
238
239PyDoc_STRVAR(SSLWantReadError_doc,
240"Non-blocking SSL socket needs to read more data\n"
241"before the requested operation can be completed.");
242
243PyDoc_STRVAR(SSLWantWriteError_doc,
244"Non-blocking SSL socket needs to write more data\n"
245"before the requested operation can be completed.");
246
247PyDoc_STRVAR(SSLSyscallError_doc,
248"System error when attempting SSL operation.");
249
250PyDoc_STRVAR(SSLEOFError_doc,
251"SSL/TLS connection terminated abruptly.");
252
253static PyObject *
254SSLError_str(PyOSErrorObject *self)
255{
256 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
257 Py_INCREF(self->strerror);
258 return self->strerror;
259 }
260 else
261 return PyObject_Str(self->args);
262}
263
264static PyType_Slot sslerror_type_slots[] = {
265 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
266 {Py_tp_doc, SSLError_doc},
267 {Py_tp_str, SSLError_str},
268 {0, 0},
269};
270
271static PyType_Spec sslerror_type_spec = {
272 "ssl.SSLError",
273 sizeof(PyOSErrorObject),
274 0,
275 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
276 sslerror_type_slots
277};
278
279static void
280fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
281 int lineno, unsigned long errcode)
282{
283 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
284 PyObject *init_value, *msg, *key;
285 _Py_IDENTIFIER(reason);
286 _Py_IDENTIFIER(library);
287
288 if (errcode != 0) {
289 int lib, reason;
290
291 lib = ERR_GET_LIB(errcode);
292 reason = ERR_GET_REASON(errcode);
293 key = Py_BuildValue("ii", lib, reason);
294 if (key == NULL)
295 goto fail;
296 reason_obj = PyDict_GetItem(err_codes_to_names, key);
297 Py_DECREF(key);
298 if (reason_obj == NULL) {
299 /* XXX if reason < 100, it might reflect a library number (!!) */
300 PyErr_Clear();
301 }
302 key = PyLong_FromLong(lib);
303 if (key == NULL)
304 goto fail;
305 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
306 Py_DECREF(key);
307 if (lib_obj == NULL) {
308 PyErr_Clear();
309 }
310 if (errstr == NULL)
311 errstr = ERR_reason_error_string(errcode);
312 }
313 if (errstr == NULL)
314 errstr = "unknown error";
315
316 if (reason_obj && lib_obj)
317 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
318 lib_obj, reason_obj, errstr, lineno);
319 else if (lib_obj)
320 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
321 lib_obj, errstr, lineno);
322 else
323 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
324
325 if (msg == NULL)
326 goto fail;
327 init_value = Py_BuildValue("iN", ssl_errno, msg);
328 err_value = PyObject_CallObject(type, init_value);
329 Py_DECREF(init_value);
330 if (err_value == NULL)
331 goto fail;
332 if (reason_obj == NULL)
333 reason_obj = Py_None;
334 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
335 goto fail;
336 if (lib_obj == NULL)
337 lib_obj = Py_None;
338 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
339 goto fail;
340 PyErr_SetObject(type, err_value);
341fail:
342 Py_XDECREF(err_value);
343}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000344
345static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000347{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200348 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200349 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000350 int err;
351 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200352 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000354 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000356
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 if (obj->ssl != NULL) {
358 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000360 switch (err) {
361 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200362 errstr = "TLS/SSL connection has been closed (EOF)";
363 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000364 p = PY_SSL_ERROR_ZERO_RETURN;
365 break;
366 case SSL_ERROR_WANT_READ:
367 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200368 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000369 p = PY_SSL_ERROR_WANT_READ;
370 break;
371 case SSL_ERROR_WANT_WRITE:
372 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200373 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 errstr = "The operation did not complete (write)";
375 break;
376 case SSL_ERROR_WANT_X509_LOOKUP:
377 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000378 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 break;
380 case SSL_ERROR_WANT_CONNECT:
381 p = PY_SSL_ERROR_WANT_CONNECT;
382 errstr = "The operation did not complete (connect)";
383 break;
384 case SSL_ERROR_SYSCALL:
385 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 if (e == 0) {
387 PySocketSockObject *s
388 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
389 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000390 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200391 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000392 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000394 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000395 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000396 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200397 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000398 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200399 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000400 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000401 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200402 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000403 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 }
405 } else {
406 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 }
408 break;
409 }
410 case SSL_ERROR_SSL:
411 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000412 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200413 if (e == 0)
414 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000415 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 break;
417 }
418 default:
419 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
420 errstr = "Invalid error code";
421 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200423 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000424 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000426}
427
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428static PyObject *
429_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
430
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200431 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000432 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433 else
434 errcode = 0;
435 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000436 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438}
439
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200440/*
441 * SSL objects
442 */
443
Antoine Pitrou152efa22010-05-16 18:19:27 +0000444static PySSLSocket *
445newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000446 enum py_ssl_server_or_client socket_type,
447 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000449 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000450
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 if (self == NULL)
453 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 self->peer_cert = NULL;
456 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 self->Socket = NULL;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200458 self->shutdown_seen_zero = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 /* Make sure the SSL error state is initialized */
461 (void) ERR_get_state();
462 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000464 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000465 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000467 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000468#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000470#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000471
Antoine Pitroud5323212010-10-22 18:19:07 +0000472#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
473 if (server_hostname != NULL)
474 SSL_set_tlsext_host_name(self->ssl, server_hostname);
475#endif
476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000477 /* If the socket is in non-blocking mode or timeout mode, set the BIO
478 * to non-blocking mode (blocking is the default)
479 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000480 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
482 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
483 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 PySSL_BEGIN_ALLOW_THREADS
486 if (socket_type == PY_SSL_CLIENT)
487 SSL_set_connect_state(self->ssl);
488 else
489 SSL_set_accept_state(self->ssl);
490 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000491
Antoine Pitroud6494802011-07-21 01:11:30 +0200492 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495}
496
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497/* SSL object methods */
498
Antoine Pitrou152efa22010-05-16 18:19:27 +0000499static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000500{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000501 int ret;
502 int err;
503 int sockstate, nonblocking;
504 PySocketSockObject *sock
505 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000506
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000507 if (((PyObject*)sock) == Py_None) {
508 _setSSLError("Underlying socket connection gone",
509 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
510 return NULL;
511 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000512 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* just in case the blocking state of the socket has been changed */
515 nonblocking = (sock->sock_timeout >= 0.0);
516 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
517 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000519 /* Actually negotiate SSL connection */
520 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000522 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 ret = SSL_do_handshake(self->ssl);
524 err = SSL_get_error(self->ssl, ret);
525 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000526 if (PyErr_CheckSignals())
527 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000528 if (err == SSL_ERROR_WANT_READ) {
529 sockstate = check_socket_and_wait_for_timeout(sock, 0);
530 } else if (err == SSL_ERROR_WANT_WRITE) {
531 sockstate = check_socket_and_wait_for_timeout(sock, 1);
532 } else {
533 sockstate = SOCKET_OPERATION_OK;
534 }
535 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000536 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000537 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000538 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
540 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000541 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000542 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
544 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000545 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000546 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
548 break;
549 }
550 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000551 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 if (ret < 1)
553 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000555 if (self->peer_cert)
556 X509_free (self->peer_cert);
557 PySSL_BEGIN_ALLOW_THREADS
558 self->peer_cert = SSL_get_peer_certificate(self->ssl);
559 PySSL_END_ALLOW_THREADS
560
561 Py_INCREF(Py_None);
562 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000563
564error:
565 Py_DECREF(sock);
566 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000567}
568
Thomas Woutersed03b412007-08-28 21:37:11 +0000569static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 char namebuf[X509_NAME_MAXLEN];
573 int buflen;
574 PyObject *name_obj;
575 PyObject *value_obj;
576 PyObject *attr;
577 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
580 if (buflen < 0) {
581 _setSSLError(NULL, 0, __FILE__, __LINE__);
582 goto fail;
583 }
584 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
585 if (name_obj == NULL)
586 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
589 if (buflen < 0) {
590 _setSSLError(NULL, 0, __FILE__, __LINE__);
591 Py_DECREF(name_obj);
592 goto fail;
593 }
594 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000595 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 OPENSSL_free(valuebuf);
597 if (value_obj == NULL) {
598 Py_DECREF(name_obj);
599 goto fail;
600 }
601 attr = PyTuple_New(2);
602 if (attr == NULL) {
603 Py_DECREF(name_obj);
604 Py_DECREF(value_obj);
605 goto fail;
606 }
607 PyTuple_SET_ITEM(attr, 0, name_obj);
608 PyTuple_SET_ITEM(attr, 1, value_obj);
609 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000610
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000613}
614
615static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000617{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
619 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
620 PyObject *rdnt;
621 PyObject *attr = NULL; /* tuple to hold an attribute */
622 int entry_count = X509_NAME_entry_count(xname);
623 X509_NAME_ENTRY *entry;
624 ASN1_OBJECT *name;
625 ASN1_STRING *value;
626 int index_counter;
627 int rdn_level = -1;
628 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 dn = PyList_New(0);
631 if (dn == NULL)
632 return NULL;
633 /* now create another tuple to hold the top-level RDN */
634 rdn = PyList_New(0);
635 if (rdn == NULL)
636 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 for (index_counter = 0;
639 index_counter < entry_count;
640 index_counter++)
641 {
642 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 /* check to see if we've gotten to a new RDN */
645 if (rdn_level >= 0) {
646 if (rdn_level != entry->set) {
647 /* yes, new RDN */
648 /* add old RDN to DN */
649 rdnt = PyList_AsTuple(rdn);
650 Py_DECREF(rdn);
651 if (rdnt == NULL)
652 goto fail0;
653 retcode = PyList_Append(dn, rdnt);
654 Py_DECREF(rdnt);
655 if (retcode < 0)
656 goto fail0;
657 /* create new RDN */
658 rdn = PyList_New(0);
659 if (rdn == NULL)
660 goto fail0;
661 }
662 }
663 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 /* now add this attribute to the current RDN */
666 name = X509_NAME_ENTRY_get_object(entry);
667 value = X509_NAME_ENTRY_get_data(entry);
668 attr = _create_tuple_for_attribute(name, value);
669 /*
670 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
671 entry->set,
672 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
673 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
674 */
675 if (attr == NULL)
676 goto fail1;
677 retcode = PyList_Append(rdn, attr);
678 Py_DECREF(attr);
679 if (retcode < 0)
680 goto fail1;
681 }
682 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100683 if (rdn != NULL) {
684 if (PyList_GET_SIZE(rdn) > 0) {
685 rdnt = PyList_AsTuple(rdn);
686 Py_DECREF(rdn);
687 if (rdnt == NULL)
688 goto fail0;
689 retcode = PyList_Append(dn, rdnt);
690 Py_DECREF(rdnt);
691 if (retcode < 0)
692 goto fail0;
693 }
694 else {
695 Py_DECREF(rdn);
696 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 /* convert list to tuple */
700 rdnt = PyList_AsTuple(dn);
701 Py_DECREF(dn);
702 if (rdnt == NULL)
703 return NULL;
704 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
706 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
709 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 Py_XDECREF(dn);
711 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712}
713
714static PyObject *
715_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 /* this code follows the procedure outlined in
718 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
719 function to extract the STACK_OF(GENERAL_NAME),
720 then iterates through the stack to add the
721 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 int i, j;
724 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200725 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 X509_EXTENSION *ext = NULL;
727 GENERAL_NAMES *names = NULL;
728 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000729 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 BIO *biobuf = NULL;
731 char buf[2048];
732 char *vptr;
733 int len;
734 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000735#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000737#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000739#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 if (certificate == NULL)
742 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 /* get a memory buffer */
745 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200747 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 while ((i = X509_get_ext_by_NID(
749 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 if (peer_alt_names == Py_None) {
752 peer_alt_names = PyList_New(0);
753 if (peer_alt_names == NULL)
754 goto fail;
755 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 /* now decode the altName */
758 ext = X509_get_ext(certificate, i);
759 if(!(method = X509V3_EXT_get(ext))) {
760 PyErr_SetString
761 (PySSLErrorObject,
762 ERRSTR("No method for internalizing subjectAltName!"));
763 goto fail;
764 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 p = ext->value->data;
767 if (method->it)
768 names = (GENERAL_NAMES*)
769 (ASN1_item_d2i(NULL,
770 &p,
771 ext->value->length,
772 ASN1_ITEM_ptr(method->it)));
773 else
774 names = (GENERAL_NAMES*)
775 (method->d2i(NULL,
776 &p,
777 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200781 int gntype;
782 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200785 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200786 switch (gntype) {
787 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 /* we special-case DirName as a tuple of
789 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 t = PyTuple_New(2);
792 if (t == NULL) {
793 goto fail;
794 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 v = PyUnicode_FromString("DirName");
797 if (v == NULL) {
798 Py_DECREF(t);
799 goto fail;
800 }
801 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 v = _create_tuple_for_X509_NAME (name->d.dirn);
804 if (v == NULL) {
805 Py_DECREF(t);
806 goto fail;
807 }
808 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200809 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000810
Christian Heimes824f7f32013-08-17 00:54:47 +0200811 case GEN_EMAIL:
812 case GEN_DNS:
813 case GEN_URI:
814 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
815 correctly, CVE-2013-4238 */
816 t = PyTuple_New(2);
817 if (t == NULL)
818 goto fail;
819 switch (gntype) {
820 case GEN_EMAIL:
821 v = PyUnicode_FromString("email");
822 as = name->d.rfc822Name;
823 break;
824 case GEN_DNS:
825 v = PyUnicode_FromString("DNS");
826 as = name->d.dNSName;
827 break;
828 case GEN_URI:
829 v = PyUnicode_FromString("URI");
830 as = name->d.uniformResourceIdentifier;
831 break;
832 }
833 if (v == NULL) {
834 Py_DECREF(t);
835 goto fail;
836 }
837 PyTuple_SET_ITEM(t, 0, v);
838 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
839 ASN1_STRING_length(as));
840 if (v == NULL) {
841 Py_DECREF(t);
842 goto fail;
843 }
844 PyTuple_SET_ITEM(t, 1, v);
845 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846
Christian Heimes824f7f32013-08-17 00:54:47 +0200847 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200849 switch (gntype) {
850 /* check for new general name type */
851 case GEN_OTHERNAME:
852 case GEN_X400:
853 case GEN_EDIPARTY:
854 case GEN_IPADD:
855 case GEN_RID:
856 break;
857 default:
858 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
859 "Unknown general name type %d",
860 gntype) == -1) {
861 goto fail;
862 }
863 break;
864 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 (void) BIO_reset(biobuf);
866 GENERAL_NAME_print(biobuf, name);
867 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
868 if (len < 0) {
869 _setSSLError(NULL, 0, __FILE__, __LINE__);
870 goto fail;
871 }
872 vptr = strchr(buf, ':');
873 if (vptr == NULL)
874 goto fail;
875 t = PyTuple_New(2);
876 if (t == NULL)
877 goto fail;
878 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
879 if (v == NULL) {
880 Py_DECREF(t);
881 goto fail;
882 }
883 PyTuple_SET_ITEM(t, 0, v);
884 v = PyUnicode_FromStringAndSize((vptr + 1),
885 (len - (vptr - buf + 1)));
886 if (v == NULL) {
887 Py_DECREF(t);
888 goto fail;
889 }
890 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200891 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 if (PyList_Append(peer_alt_names, t) < 0) {
897 Py_DECREF(t);
898 goto fail;
899 }
900 Py_DECREF(t);
901 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100902 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 }
904 BIO_free(biobuf);
905 if (peer_alt_names != Py_None) {
906 v = PyList_AsTuple(peer_alt_names);
907 Py_DECREF(peer_alt_names);
908 return v;
909 } else {
910 return peer_alt_names;
911 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000912
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
914 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 if (biobuf != NULL)
916 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 if (peer_alt_names != Py_None) {
919 Py_XDECREF(peer_alt_names);
920 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923}
924
925static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000926_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 PyObject *retval = NULL;
929 BIO *biobuf = NULL;
930 PyObject *peer;
931 PyObject *peer_alt_names = NULL;
932 PyObject *issuer;
933 PyObject *version;
934 PyObject *sn_obj;
935 ASN1_INTEGER *serialNumber;
936 char buf[2048];
937 int len;
938 ASN1_TIME *notBefore, *notAfter;
939 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 retval = PyDict_New();
942 if (retval == NULL)
943 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 peer = _create_tuple_for_X509_NAME(
946 X509_get_subject_name(certificate));
947 if (peer == NULL)
948 goto fail0;
949 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
950 Py_DECREF(peer);
951 goto fail0;
952 }
953 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000954
Antoine Pitroufb046912010-11-09 20:21:19 +0000955 issuer = _create_tuple_for_X509_NAME(
956 X509_get_issuer_name(certificate));
957 if (issuer == NULL)
958 goto fail0;
959 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000961 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000963 Py_DECREF(issuer);
964
965 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200966 if (version == NULL)
967 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000968 if (PyDict_SetItemString(retval, "version", version) < 0) {
969 Py_DECREF(version);
970 goto fail0;
971 }
972 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 /* get a memory buffer */
975 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000976
Antoine Pitroufb046912010-11-09 20:21:19 +0000977 (void) BIO_reset(biobuf);
978 serialNumber = X509_get_serialNumber(certificate);
979 /* should not exceed 20 octets, 160 bits, so buf is big enough */
980 i2a_ASN1_INTEGER(biobuf, serialNumber);
981 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
982 if (len < 0) {
983 _setSSLError(NULL, 0, __FILE__, __LINE__);
984 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000986 sn_obj = PyUnicode_FromStringAndSize(buf, len);
987 if (sn_obj == NULL)
988 goto fail1;
989 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
990 Py_DECREF(sn_obj);
991 goto fail1;
992 }
993 Py_DECREF(sn_obj);
994
995 (void) BIO_reset(biobuf);
996 notBefore = X509_get_notBefore(certificate);
997 ASN1_TIME_print(biobuf, notBefore);
998 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
999 if (len < 0) {
1000 _setSSLError(NULL, 0, __FILE__, __LINE__);
1001 goto fail1;
1002 }
1003 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1004 if (pnotBefore == NULL)
1005 goto fail1;
1006 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1007 Py_DECREF(pnotBefore);
1008 goto fail1;
1009 }
1010 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 (void) BIO_reset(biobuf);
1013 notAfter = X509_get_notAfter(certificate);
1014 ASN1_TIME_print(biobuf, notAfter);
1015 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1016 if (len < 0) {
1017 _setSSLError(NULL, 0, __FILE__, __LINE__);
1018 goto fail1;
1019 }
1020 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1021 if (pnotAfter == NULL)
1022 goto fail1;
1023 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1024 Py_DECREF(pnotAfter);
1025 goto fail1;
1026 }
1027 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 peer_alt_names = _get_peer_alt_names(certificate);
1032 if (peer_alt_names == NULL)
1033 goto fail1;
1034 else if (peer_alt_names != Py_None) {
1035 if (PyDict_SetItemString(retval, "subjectAltName",
1036 peer_alt_names) < 0) {
1037 Py_DECREF(peer_alt_names);
1038 goto fail1;
1039 }
1040 Py_DECREF(peer_alt_names);
1041 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 BIO_free(biobuf);
1044 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001045
1046 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 if (biobuf != NULL)
1048 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001049 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 Py_XDECREF(retval);
1051 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001052}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001053
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054
1055static PyObject *
1056PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001059 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 X509 *x=NULL;
1061 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062
Antoine Pitroufb046912010-11-09 20:21:19 +00001063 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1064 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1068 PyErr_SetString(PySSLErrorObject,
1069 "Can't malloc memory to read file");
1070 goto fail0;
1071 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072
Victor Stinner3800e1e2010-05-16 21:23:48 +00001073 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 PyErr_SetString(PySSLErrorObject,
1075 "Can't open file");
1076 goto fail0;
1077 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1080 if (x == NULL) {
1081 PyErr_SetString(PySSLErrorObject,
1082 "Error decoding PEM-encoded file");
1083 goto fail0;
1084 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085
Antoine Pitroufb046912010-11-09 20:21:19 +00001086 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001087 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088
1089 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001090 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 if (cert != NULL) BIO_free(cert);
1092 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093}
1094
1095
1096static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001097PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 PyObject *retval = NULL;
1100 int len;
1101 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001102 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103
Antoine Pitrou721738f2012-08-15 23:20:39 +02001104 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (!self->peer_cert)
1108 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
Antoine Pitrou721738f2012-08-15 23:20:39 +02001110 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 bytes_buf = NULL;
1116 len = i2d_X509(self->peer_cert, &bytes_buf);
1117 if (len < 0) {
1118 PySSL_SetError(self, len, __FILE__, __LINE__);
1119 return NULL;
1120 }
1121 /* this is actually an immutable bytes sequence */
1122 retval = PyBytes_FromStringAndSize
1123 ((const char *) bytes_buf, len);
1124 OPENSSL_free(bytes_buf);
1125 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001128 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 if ((verification & SSL_VERIFY_PEER) == 0)
1130 return PyDict_New();
1131 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001132 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134}
1135
1136PyDoc_STRVAR(PySSL_peercert_doc,
1137"peer_certificate([der=False]) -> certificate\n\
1138\n\
1139Returns the certificate for the peer. If no certificate was provided,\n\
1140returns None. If a certificate was provided, but not validated, returns\n\
1141an empty dictionary. Otherwise returns a dict containing information\n\
1142about the peer certificate.\n\
1143\n\
1144If the optional argument is True, returns a DER-encoded copy of the\n\
1145peer certificate, or None if no certificate was provided. This will\n\
1146return the certificate even if it wasn't validated.");
1147
Antoine Pitrou152efa22010-05-16 18:19:27 +00001148static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001151 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 char *cipher_name;
1153 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001156 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 current = SSL_get_current_cipher(self->ssl);
1158 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001159 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 retval = PyTuple_New(3);
1162 if (retval == NULL)
1163 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 cipher_name = (char *) SSL_CIPHER_get_name(current);
1166 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001167 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 PyTuple_SET_ITEM(retval, 0, Py_None);
1169 } else {
1170 v = PyUnicode_FromString(cipher_name);
1171 if (v == NULL)
1172 goto fail0;
1173 PyTuple_SET_ITEM(retval, 0, v);
1174 }
1175 cipher_protocol = SSL_CIPHER_get_version(current);
1176 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001177 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 PyTuple_SET_ITEM(retval, 1, Py_None);
1179 } else {
1180 v = PyUnicode_FromString(cipher_protocol);
1181 if (v == NULL)
1182 goto fail0;
1183 PyTuple_SET_ITEM(retval, 1, v);
1184 }
1185 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1186 if (v == NULL)
1187 goto fail0;
1188 PyTuple_SET_ITEM(retval, 2, v);
1189 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001190
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 Py_DECREF(retval);
1193 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194}
1195
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001196#ifdef OPENSSL_NPN_NEGOTIATED
1197static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1198 const unsigned char *out;
1199 unsigned int outlen;
1200
Victor Stinner4569cd52013-06-23 14:58:43 +02001201 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001202 &out, &outlen);
1203
1204 if (out == NULL)
1205 Py_RETURN_NONE;
1206 return PyUnicode_FromStringAndSize((char *) out, outlen);
1207}
1208#endif
1209
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001210static PyObject *PySSL_compression(PySSLSocket *self) {
1211#ifdef OPENSSL_NO_COMP
1212 Py_RETURN_NONE;
1213#else
1214 const COMP_METHOD *comp_method;
1215 const char *short_name;
1216
1217 if (self->ssl == NULL)
1218 Py_RETURN_NONE;
1219 comp_method = SSL_get_current_compression(self->ssl);
1220 if (comp_method == NULL || comp_method->type == NID_undef)
1221 Py_RETURN_NONE;
1222 short_name = OBJ_nid2sn(comp_method->type);
1223 if (short_name == NULL)
1224 Py_RETURN_NONE;
1225 return PyUnicode_DecodeFSDefault(short_name);
1226#endif
1227}
1228
Antoine Pitrou152efa22010-05-16 18:19:27 +00001229static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001230{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 if (self->peer_cert) /* Possible not to have one? */
1232 X509_free (self->peer_cert);
1233 if (self->ssl)
1234 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 Py_XDECREF(self->Socket);
1236 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001237}
1238
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001239/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001240 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001241 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001242 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001243
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001244static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001245check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001246{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 fd_set fds;
1248 struct timeval tv;
1249 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1252 if (s->sock_timeout < 0.0)
1253 return SOCKET_IS_BLOCKING;
1254 else if (s->sock_timeout == 0.0)
1255 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 /* Guard against closed socket */
1258 if (s->sock_fd < 0)
1259 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* Prefer poll, if available, since you can poll() any fd
1262 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001263#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 {
1265 struct pollfd pollfd;
1266 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 pollfd.fd = s->sock_fd;
1269 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 /* s->sock_timeout is in seconds, timeout in ms */
1272 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1273 PySSL_BEGIN_ALLOW_THREADS
1274 rc = poll(&pollfd, 1, timeout);
1275 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 goto normal_return;
1278 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001279#endif
1280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001282 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 /* Construct the arguments to select */
1286 tv.tv_sec = (int)s->sock_timeout;
1287 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1288 FD_ZERO(&fds);
1289 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 /* See if the socket is ready */
1292 PySSL_BEGIN_ALLOW_THREADS
1293 if (writing)
1294 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1295 else
1296 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1297 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001298
Bill Janssen6e027db2007-11-15 22:23:56 +00001299#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001300normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001301#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1303 (when we are able to write or when there's something to read) */
1304 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001305}
1306
Antoine Pitrou152efa22010-05-16 18:19:27 +00001307static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001308{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 Py_buffer buf;
1310 int len;
1311 int sockstate;
1312 int err;
1313 int nonblocking;
1314 PySocketSockObject *sock
1315 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 if (((PyObject*)sock) == Py_None) {
1318 _setSSLError("Underlying socket connection gone",
1319 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1320 return NULL;
1321 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001322 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001324 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1325 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001327 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328
Victor Stinner6efa9652013-06-25 00:42:31 +02001329 if (buf.len > INT_MAX) {
1330 PyErr_Format(PyExc_OverflowError,
1331 "string longer than %d bytes", INT_MAX);
1332 goto error;
1333 }
1334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 /* just in case the blocking state of the socket has been changed */
1336 nonblocking = (sock->sock_timeout >= 0.0);
1337 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1338 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1339
1340 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1341 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001342 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 "The write operation timed out");
1344 goto error;
1345 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1346 PyErr_SetString(PySSLErrorObject,
1347 "Underlying socket has been closed.");
1348 goto error;
1349 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1350 PyErr_SetString(PySSLErrorObject,
1351 "Underlying socket too large for select().");
1352 goto error;
1353 }
1354 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001356 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 err = SSL_get_error(self->ssl, len);
1358 PySSL_END_ALLOW_THREADS
1359 if (PyErr_CheckSignals()) {
1360 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001361 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001363 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001365 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 } else {
1367 sockstate = SOCKET_OPERATION_OK;
1368 }
1369 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001370 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 "The write operation timed out");
1372 goto error;
1373 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1374 PyErr_SetString(PySSLErrorObject,
1375 "Underlying socket has been closed.");
1376 goto error;
1377 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1378 break;
1379 }
1380 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001381
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001382 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 PyBuffer_Release(&buf);
1384 if (len > 0)
1385 return PyLong_FromLong(len);
1386 else
1387 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001388
1389error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001390 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 PyBuffer_Release(&buf);
1392 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001393}
1394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001395PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001396"write(s) -> len\n\
1397\n\
1398Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001399of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400
Antoine Pitrou152efa22010-05-16 18:19:27 +00001401static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001402{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001404
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 PySSL_BEGIN_ALLOW_THREADS
1406 count = SSL_pending(self->ssl);
1407 PySSL_END_ALLOW_THREADS
1408 if (count < 0)
1409 return PySSL_SetError(self, count, __FILE__, __LINE__);
1410 else
1411 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001412}
1413
1414PyDoc_STRVAR(PySSL_SSLpending_doc,
1415"pending() -> count\n\
1416\n\
1417Returns the number of already decrypted bytes available for read,\n\
1418pending on the connection.\n");
1419
Antoine Pitrou152efa22010-05-16 18:19:27 +00001420static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001421{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 PyObject *dest = NULL;
1423 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001425 int len, count;
1426 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 int sockstate;
1428 int err;
1429 int nonblocking;
1430 PySocketSockObject *sock
1431 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 if (((PyObject*)sock) == Py_None) {
1434 _setSSLError("Underlying socket connection gone",
1435 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1436 return NULL;
1437 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001438 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001440 buf.obj = NULL;
1441 buf.buf = NULL;
1442 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001443 goto error;
1444
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001445 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1446 dest = PyBytes_FromStringAndSize(NULL, len);
1447 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001448 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001449 mem = PyBytes_AS_STRING(dest);
1450 }
1451 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001452 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001453 mem = buf.buf;
1454 if (len <= 0 || len > buf.len) {
1455 len = (int) buf.len;
1456 if (buf.len != len) {
1457 PyErr_SetString(PyExc_OverflowError,
1458 "maximum length can't fit in a C 'int'");
1459 goto error;
1460 }
1461 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 }
1463
1464 /* just in case the blocking state of the socket has been changed */
1465 nonblocking = (sock->sock_timeout >= 0.0);
1466 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1467 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1468
1469 /* first check if there are bytes ready to be read */
1470 PySSL_BEGIN_ALLOW_THREADS
1471 count = SSL_pending(self->ssl);
1472 PySSL_END_ALLOW_THREADS
1473
1474 if (!count) {
1475 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1476 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001477 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 "The read operation timed out");
1479 goto error;
1480 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1481 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001482 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 goto error;
1484 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1485 count = 0;
1486 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001487 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 }
1489 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 PySSL_BEGIN_ALLOW_THREADS
1491 count = SSL_read(self->ssl, mem, len);
1492 err = SSL_get_error(self->ssl, count);
1493 PySSL_END_ALLOW_THREADS
1494 if (PyErr_CheckSignals())
1495 goto error;
1496 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001497 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001499 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1501 (SSL_get_shutdown(self->ssl) ==
1502 SSL_RECEIVED_SHUTDOWN))
1503 {
1504 count = 0;
1505 goto done;
1506 } else {
1507 sockstate = SOCKET_OPERATION_OK;
1508 }
1509 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001510 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 "The read operation timed out");
1512 goto error;
1513 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1514 break;
1515 }
1516 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1517 if (count <= 0) {
1518 PySSL_SetError(self, count, __FILE__, __LINE__);
1519 goto error;
1520 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001521
1522done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001523 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001525 _PyBytes_Resize(&dest, count);
1526 return dest;
1527 }
1528 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 PyBuffer_Release(&buf);
1530 return PyLong_FromLong(count);
1531 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532
1533error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001534 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001535 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001536 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001537 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001540}
1541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001542PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001543"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001544\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001545Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001546
Antoine Pitrou152efa22010-05-16 18:19:27 +00001547static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001548{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 int err, ssl_err, sockstate, nonblocking;
1550 int zeros = 0;
1551 PySocketSockObject *sock
1552 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 /* Guard against closed socket */
1555 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1556 _setSSLError("Underlying socket connection gone",
1557 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1558 return NULL;
1559 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001560 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561
1562 /* Just in case the blocking state of the socket has been changed */
1563 nonblocking = (sock->sock_timeout >= 0.0);
1564 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1565 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1566
1567 while (1) {
1568 PySSL_BEGIN_ALLOW_THREADS
1569 /* Disable read-ahead so that unwrap can work correctly.
1570 * Otherwise OpenSSL might read in too much data,
1571 * eating clear text data that happens to be
1572 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001573 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 * function is used and the shutdown_seen_zero != 0
1575 * condition is met.
1576 */
1577 if (self->shutdown_seen_zero)
1578 SSL_set_read_ahead(self->ssl, 0);
1579 err = SSL_shutdown(self->ssl);
1580 PySSL_END_ALLOW_THREADS
1581 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1582 if (err > 0)
1583 break;
1584 if (err == 0) {
1585 /* Don't loop endlessly; instead preserve legacy
1586 behaviour of trying SSL_shutdown() only twice.
1587 This looks necessary for OpenSSL < 0.9.8m */
1588 if (++zeros > 1)
1589 break;
1590 /* Shutdown was sent, now try receiving */
1591 self->shutdown_seen_zero = 1;
1592 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001593 }
1594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001595 /* Possibly retry shutdown until timeout or failure */
1596 ssl_err = SSL_get_error(self->ssl, err);
1597 if (ssl_err == SSL_ERROR_WANT_READ)
1598 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1599 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1600 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1601 else
1602 break;
1603 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1604 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001605 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 "The read operation timed out");
1607 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001608 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001610 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 }
1612 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1613 PyErr_SetString(PySSLErrorObject,
1614 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001615 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 }
1617 else if (sockstate != SOCKET_OPERATION_OK)
1618 /* Retain the SSL error code */
1619 break;
1620 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001621
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001622 if (err < 0) {
1623 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001626 else
1627 /* It's already INCREF'ed */
1628 return (PyObject *) sock;
1629
1630error:
1631 Py_DECREF(sock);
1632 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001633}
1634
1635PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1636"shutdown(s) -> socket\n\
1637\n\
1638Does the SSL shutdown handshake with the remote end, and returns\n\
1639the underlying socket object.");
1640
Antoine Pitroud6494802011-07-21 01:11:30 +02001641#if HAVE_OPENSSL_FINISHED
1642static PyObject *
1643PySSL_tls_unique_cb(PySSLSocket *self)
1644{
1645 PyObject *retval = NULL;
1646 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001647 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001648
1649 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1650 /* if session is resumed XOR we are the client */
1651 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1652 }
1653 else {
1654 /* if a new session XOR we are the server */
1655 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1656 }
1657
1658 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001659 if (len == 0)
1660 Py_RETURN_NONE;
1661
1662 retval = PyBytes_FromStringAndSize(buf, len);
1663
1664 return retval;
1665}
1666
1667PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1668"tls_unique_cb() -> bytes\n\
1669\n\
1670Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1671\n\
1672If the TLS handshake is not yet complete, None is returned");
1673
1674#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001675
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001676static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1678 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1679 PySSL_SSLwrite_doc},
1680 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1681 PySSL_SSLread_doc},
1682 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1683 PySSL_SSLpending_doc},
1684 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1685 PySSL_peercert_doc},
1686 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001687#ifdef OPENSSL_NPN_NEGOTIATED
1688 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1689#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001690 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1692 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001693#if HAVE_OPENSSL_FINISHED
1694 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1695 PySSL_tls_unique_cb_doc},
1696#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001698};
1699
Antoine Pitrou152efa22010-05-16 18:19:27 +00001700static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001702 "_ssl._SSLSocket", /*tp_name*/
1703 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001704 0, /*tp_itemsize*/
1705 /* methods */
1706 (destructor)PySSL_dealloc, /*tp_dealloc*/
1707 0, /*tp_print*/
1708 0, /*tp_getattr*/
1709 0, /*tp_setattr*/
1710 0, /*tp_reserved*/
1711 0, /*tp_repr*/
1712 0, /*tp_as_number*/
1713 0, /*tp_as_sequence*/
1714 0, /*tp_as_mapping*/
1715 0, /*tp_hash*/
1716 0, /*tp_call*/
1717 0, /*tp_str*/
1718 0, /*tp_getattro*/
1719 0, /*tp_setattro*/
1720 0, /*tp_as_buffer*/
1721 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1722 0, /*tp_doc*/
1723 0, /*tp_traverse*/
1724 0, /*tp_clear*/
1725 0, /*tp_richcompare*/
1726 0, /*tp_weaklistoffset*/
1727 0, /*tp_iter*/
1728 0, /*tp_iternext*/
1729 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001730};
1731
Antoine Pitrou152efa22010-05-16 18:19:27 +00001732
1733/*
1734 * _SSLContext objects
1735 */
1736
1737static PyObject *
1738context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1739{
1740 char *kwlist[] = {"protocol", NULL};
1741 PySSLContext *self;
1742 int proto_version = PY_SSL_VERSION_SSL23;
1743 SSL_CTX *ctx = NULL;
1744
1745 if (!PyArg_ParseTupleAndKeywords(
1746 args, kwds, "i:_SSLContext", kwlist,
1747 &proto_version))
1748 return NULL;
1749
1750 PySSL_BEGIN_ALLOW_THREADS
1751 if (proto_version == PY_SSL_VERSION_TLS1)
1752 ctx = SSL_CTX_new(TLSv1_method());
1753 else if (proto_version == PY_SSL_VERSION_SSL3)
1754 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001755#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001756 else if (proto_version == PY_SSL_VERSION_SSL2)
1757 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001758#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001759 else if (proto_version == PY_SSL_VERSION_SSL23)
1760 ctx = SSL_CTX_new(SSLv23_method());
1761 else
1762 proto_version = -1;
1763 PySSL_END_ALLOW_THREADS
1764
1765 if (proto_version == -1) {
1766 PyErr_SetString(PyExc_ValueError,
1767 "invalid protocol version");
1768 return NULL;
1769 }
1770 if (ctx == NULL) {
1771 PyErr_SetString(PySSLErrorObject,
1772 "failed to allocate SSL context");
1773 return NULL;
1774 }
1775
1776 assert(type != NULL && type->tp_alloc != NULL);
1777 self = (PySSLContext *) type->tp_alloc(type, 0);
1778 if (self == NULL) {
1779 SSL_CTX_free(ctx);
1780 return NULL;
1781 }
1782 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001783#ifdef OPENSSL_NPN_NEGOTIATED
1784 self->npn_protocols = NULL;
1785#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001786 /* Defaults */
1787 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001788 SSL_CTX_set_options(self->ctx,
1789 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001790
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001791#define SID_CTX "Python"
1792 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1793 sizeof(SID_CTX));
1794#undef SID_CTX
1795
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796 return (PyObject *)self;
1797}
1798
1799static void
1800context_dealloc(PySSLContext *self)
1801{
1802 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001803#ifdef OPENSSL_NPN_NEGOTIATED
1804 PyMem_Free(self->npn_protocols);
1805#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 Py_TYPE(self)->tp_free(self);
1807}
1808
1809static PyObject *
1810set_ciphers(PySSLContext *self, PyObject *args)
1811{
1812 int ret;
1813 const char *cipherlist;
1814
1815 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1816 return NULL;
1817 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1818 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001819 /* Clearing the error queue is necessary on some OpenSSL versions,
1820 otherwise the error will be reported again when another SSL call
1821 is done. */
1822 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001823 PyErr_SetString(PySSLErrorObject,
1824 "No cipher can be selected.");
1825 return NULL;
1826 }
1827 Py_RETURN_NONE;
1828}
1829
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001830#ifdef OPENSSL_NPN_NEGOTIATED
1831/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1832static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001833_advertiseNPN_cb(SSL *s,
1834 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001835 void *args)
1836{
1837 PySSLContext *ssl_ctx = (PySSLContext *) args;
1838
1839 if (ssl_ctx->npn_protocols == NULL) {
1840 *data = (unsigned char *) "";
1841 *len = 0;
1842 } else {
1843 *data = (unsigned char *) ssl_ctx->npn_protocols;
1844 *len = ssl_ctx->npn_protocols_len;
1845 }
1846
1847 return SSL_TLSEXT_ERR_OK;
1848}
1849/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1850static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001851_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001852 unsigned char **out, unsigned char *outlen,
1853 const unsigned char *server, unsigned int server_len,
1854 void *args)
1855{
1856 PySSLContext *ssl_ctx = (PySSLContext *) args;
1857
1858 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1859 int client_len;
1860
1861 if (client == NULL) {
1862 client = (unsigned char *) "";
1863 client_len = 0;
1864 } else {
1865 client_len = ssl_ctx->npn_protocols_len;
1866 }
1867
1868 SSL_select_next_proto(out, outlen,
1869 server, server_len,
1870 client, client_len);
1871
1872 return SSL_TLSEXT_ERR_OK;
1873}
1874#endif
1875
1876static PyObject *
1877_set_npn_protocols(PySSLContext *self, PyObject *args)
1878{
1879#ifdef OPENSSL_NPN_NEGOTIATED
1880 Py_buffer protos;
1881
1882 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1883 return NULL;
1884
Christian Heimes5cb31c92012-09-20 12:42:54 +02001885 if (self->npn_protocols != NULL) {
1886 PyMem_Free(self->npn_protocols);
1887 }
1888
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001889 self->npn_protocols = PyMem_Malloc(protos.len);
1890 if (self->npn_protocols == NULL) {
1891 PyBuffer_Release(&protos);
1892 return PyErr_NoMemory();
1893 }
1894 memcpy(self->npn_protocols, protos.buf, protos.len);
1895 self->npn_protocols_len = (int) protos.len;
1896
1897 /* set both server and client callbacks, because the context can
1898 * be used to create both types of sockets */
1899 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1900 _advertiseNPN_cb,
1901 self);
1902 SSL_CTX_set_next_proto_select_cb(self->ctx,
1903 _selectNPN_cb,
1904 self);
1905
1906 PyBuffer_Release(&protos);
1907 Py_RETURN_NONE;
1908#else
1909 PyErr_SetString(PyExc_NotImplementedError,
1910 "The NPN extension requires OpenSSL 1.0.1 or later.");
1911 return NULL;
1912#endif
1913}
1914
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915static PyObject *
1916get_verify_mode(PySSLContext *self, void *c)
1917{
1918 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1919 case SSL_VERIFY_NONE:
1920 return PyLong_FromLong(PY_SSL_CERT_NONE);
1921 case SSL_VERIFY_PEER:
1922 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1923 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1924 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1925 }
1926 PyErr_SetString(PySSLErrorObject,
1927 "invalid return value from SSL_CTX_get_verify_mode");
1928 return NULL;
1929}
1930
1931static int
1932set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1933{
1934 int n, mode;
1935 if (!PyArg_Parse(arg, "i", &n))
1936 return -1;
1937 if (n == PY_SSL_CERT_NONE)
1938 mode = SSL_VERIFY_NONE;
1939 else if (n == PY_SSL_CERT_OPTIONAL)
1940 mode = SSL_VERIFY_PEER;
1941 else if (n == PY_SSL_CERT_REQUIRED)
1942 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1943 else {
1944 PyErr_SetString(PyExc_ValueError,
1945 "invalid value for verify_mode");
1946 return -1;
1947 }
1948 SSL_CTX_set_verify(self->ctx, mode, NULL);
1949 return 0;
1950}
1951
1952static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001953get_options(PySSLContext *self, void *c)
1954{
1955 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1956}
1957
1958static int
1959set_options(PySSLContext *self, PyObject *arg, void *c)
1960{
1961 long new_opts, opts, set, clear;
1962 if (!PyArg_Parse(arg, "l", &new_opts))
1963 return -1;
1964 opts = SSL_CTX_get_options(self->ctx);
1965 clear = opts & ~new_opts;
1966 set = ~opts & new_opts;
1967 if (clear) {
1968#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1969 SSL_CTX_clear_options(self->ctx, clear);
1970#else
1971 PyErr_SetString(PyExc_ValueError,
1972 "can't clear options before OpenSSL 0.9.8m");
1973 return -1;
1974#endif
1975 }
1976 if (set)
1977 SSL_CTX_set_options(self->ctx, set);
1978 return 0;
1979}
1980
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001981typedef struct {
1982 PyThreadState *thread_state;
1983 PyObject *callable;
1984 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001985 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001986 int error;
1987} _PySSLPasswordInfo;
1988
1989static int
1990_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1991 const char *bad_type_error)
1992{
1993 /* Set the password and size fields of a _PySSLPasswordInfo struct
1994 from a unicode, bytes, or byte array object.
1995 The password field will be dynamically allocated and must be freed
1996 by the caller */
1997 PyObject *password_bytes = NULL;
1998 const char *data = NULL;
1999 Py_ssize_t size;
2000
2001 if (PyUnicode_Check(password)) {
2002 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2003 if (!password_bytes) {
2004 goto error;
2005 }
2006 data = PyBytes_AS_STRING(password_bytes);
2007 size = PyBytes_GET_SIZE(password_bytes);
2008 } else if (PyBytes_Check(password)) {
2009 data = PyBytes_AS_STRING(password);
2010 size = PyBytes_GET_SIZE(password);
2011 } else if (PyByteArray_Check(password)) {
2012 data = PyByteArray_AS_STRING(password);
2013 size = PyByteArray_GET_SIZE(password);
2014 } else {
2015 PyErr_SetString(PyExc_TypeError, bad_type_error);
2016 goto error;
2017 }
2018
Victor Stinner9ee02032013-06-23 15:08:23 +02002019 if (size > (Py_ssize_t)INT_MAX) {
2020 PyErr_Format(PyExc_ValueError,
2021 "password cannot be longer than %d bytes", INT_MAX);
2022 goto error;
2023 }
2024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002025 free(pw_info->password);
2026 pw_info->password = malloc(size);
2027 if (!pw_info->password) {
2028 PyErr_SetString(PyExc_MemoryError,
2029 "unable to allocate password buffer");
2030 goto error;
2031 }
2032 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002033 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002034
2035 Py_XDECREF(password_bytes);
2036 return 1;
2037
2038error:
2039 Py_XDECREF(password_bytes);
2040 return 0;
2041}
2042
2043static int
2044_password_callback(char *buf, int size, int rwflag, void *userdata)
2045{
2046 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2047 PyObject *fn_ret = NULL;
2048
2049 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2050
2051 if (pw_info->callable) {
2052 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2053 if (!fn_ret) {
2054 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2055 core python API, so we could use it to add a frame here */
2056 goto error;
2057 }
2058
2059 if (!_pwinfo_set(pw_info, fn_ret,
2060 "password callback must return a string")) {
2061 goto error;
2062 }
2063 Py_CLEAR(fn_ret);
2064 }
2065
2066 if (pw_info->size > size) {
2067 PyErr_Format(PyExc_ValueError,
2068 "password cannot be longer than %d bytes", size);
2069 goto error;
2070 }
2071
2072 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2073 memcpy(buf, pw_info->password, pw_info->size);
2074 return pw_info->size;
2075
2076error:
2077 Py_XDECREF(fn_ret);
2078 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2079 pw_info->error = 1;
2080 return -1;
2081}
2082
Antoine Pitroub5218772010-05-21 09:56:06 +00002083static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002084load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2085{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002086 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2087 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002088 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002089 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2090 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2091 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002092 int r;
2093
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002094 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002095 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002096 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002097 "O|OO:load_cert_chain", kwlist,
2098 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002099 return NULL;
2100 if (keyfile == Py_None)
2101 keyfile = NULL;
2102 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2103 PyErr_SetString(PyExc_TypeError,
2104 "certfile should be a valid filesystem path");
2105 return NULL;
2106 }
2107 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2108 PyErr_SetString(PyExc_TypeError,
2109 "keyfile should be a valid filesystem path");
2110 goto error;
2111 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002112 if (password && password != Py_None) {
2113 if (PyCallable_Check(password)) {
2114 pw_info.callable = password;
2115 } else if (!_pwinfo_set(&pw_info, password,
2116 "password should be a string or callable")) {
2117 goto error;
2118 }
2119 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2120 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2121 }
2122 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002123 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2124 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002125 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002126 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002127 if (pw_info.error) {
2128 ERR_clear_error();
2129 /* the password callback has already set the error information */
2130 }
2131 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002132 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002133 PyErr_SetFromErrno(PyExc_IOError);
2134 }
2135 else {
2136 _setSSLError(NULL, 0, __FILE__, __LINE__);
2137 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138 goto error;
2139 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002140 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002141 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002142 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2143 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002144 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2145 Py_CLEAR(keyfile_bytes);
2146 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002147 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002148 if (pw_info.error) {
2149 ERR_clear_error();
2150 /* the password callback has already set the error information */
2151 }
2152 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002153 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002154 PyErr_SetFromErrno(PyExc_IOError);
2155 }
2156 else {
2157 _setSSLError(NULL, 0, __FILE__, __LINE__);
2158 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002161 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002162 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002163 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002164 if (r != 1) {
2165 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002166 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002167 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002168 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2169 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2170 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002171 Py_RETURN_NONE;
2172
2173error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002174 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2175 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2176 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002177 Py_XDECREF(keyfile_bytes);
2178 Py_XDECREF(certfile_bytes);
2179 return NULL;
2180}
2181
2182static PyObject *
2183load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2184{
2185 char *kwlist[] = {"cafile", "capath", NULL};
2186 PyObject *cafile = NULL, *capath = NULL;
2187 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2188 const char *cafile_buf = NULL, *capath_buf = NULL;
2189 int r;
2190
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002191 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2193 "|OO:load_verify_locations", kwlist,
2194 &cafile, &capath))
2195 return NULL;
2196 if (cafile == Py_None)
2197 cafile = NULL;
2198 if (capath == Py_None)
2199 capath = NULL;
2200 if (cafile == NULL && capath == NULL) {
2201 PyErr_SetString(PyExc_TypeError,
2202 "cafile and capath cannot be both omitted");
2203 return NULL;
2204 }
2205 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2206 PyErr_SetString(PyExc_TypeError,
2207 "cafile should be a valid filesystem path");
2208 return NULL;
2209 }
2210 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002211 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 PyErr_SetString(PyExc_TypeError,
2213 "capath should be a valid filesystem path");
2214 return NULL;
2215 }
2216 if (cafile)
2217 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2218 if (capath)
2219 capath_buf = PyBytes_AS_STRING(capath_bytes);
2220 PySSL_BEGIN_ALLOW_THREADS
2221 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2222 PySSL_END_ALLOW_THREADS
2223 Py_XDECREF(cafile_bytes);
2224 Py_XDECREF(capath_bytes);
2225 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002226 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002227 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002228 PyErr_SetFromErrno(PyExc_IOError);
2229 }
2230 else {
2231 _setSSLError(NULL, 0, __FILE__, __LINE__);
2232 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002233 return NULL;
2234 }
2235 Py_RETURN_NONE;
2236}
2237
2238static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002239load_dh_params(PySSLContext *self, PyObject *filepath)
2240{
2241 FILE *f;
2242 DH *dh;
2243
2244 f = _Py_fopen(filepath, "rb");
2245 if (f == NULL) {
2246 if (!PyErr_Occurred())
2247 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2248 return NULL;
2249 }
2250 errno = 0;
2251 PySSL_BEGIN_ALLOW_THREADS
2252 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002253 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002254 PySSL_END_ALLOW_THREADS
2255 if (dh == NULL) {
2256 if (errno != 0) {
2257 ERR_clear_error();
2258 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2259 }
2260 else {
2261 _setSSLError(NULL, 0, __FILE__, __LINE__);
2262 }
2263 return NULL;
2264 }
2265 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2266 _setSSLError(NULL, 0, __FILE__, __LINE__);
2267 DH_free(dh);
2268 Py_RETURN_NONE;
2269}
2270
2271static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002272context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2273{
Antoine Pitroud5323212010-10-22 18:19:07 +00002274 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002275 PySocketSockObject *sock;
2276 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002277 char *hostname = NULL;
2278 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002279
Antoine Pitroud5323212010-10-22 18:19:07 +00002280 /* server_hostname is either None (or absent), or to be encoded
2281 using the idna encoding. */
2282 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002283 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002284 &sock, &server_side,
2285 Py_TYPE(Py_None), &hostname_obj)) {
2286 PyErr_Clear();
2287 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2288 PySocketModule.Sock_Type,
2289 &sock, &server_side,
2290 "idna", &hostname))
2291 return NULL;
2292#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2293 PyMem_Free(hostname);
2294 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2295 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002297#endif
2298 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002299
Antoine Pitroud5323212010-10-22 18:19:07 +00002300 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2301 hostname);
2302 if (hostname != NULL)
2303 PyMem_Free(hostname);
2304 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002305}
2306
Antoine Pitroub0182c82010-10-12 20:09:02 +00002307static PyObject *
2308session_stats(PySSLContext *self, PyObject *unused)
2309{
2310 int r;
2311 PyObject *value, *stats = PyDict_New();
2312 if (!stats)
2313 return NULL;
2314
2315#define ADD_STATS(SSL_NAME, KEY_NAME) \
2316 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2317 if (value == NULL) \
2318 goto error; \
2319 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2320 Py_DECREF(value); \
2321 if (r < 0) \
2322 goto error;
2323
2324 ADD_STATS(number, "number");
2325 ADD_STATS(connect, "connect");
2326 ADD_STATS(connect_good, "connect_good");
2327 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2328 ADD_STATS(accept, "accept");
2329 ADD_STATS(accept_good, "accept_good");
2330 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2331 ADD_STATS(accept, "accept");
2332 ADD_STATS(hits, "hits");
2333 ADD_STATS(misses, "misses");
2334 ADD_STATS(timeouts, "timeouts");
2335 ADD_STATS(cache_full, "cache_full");
2336
2337#undef ADD_STATS
2338
2339 return stats;
2340
2341error:
2342 Py_DECREF(stats);
2343 return NULL;
2344}
2345
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002346static PyObject *
2347set_default_verify_paths(PySSLContext *self, PyObject *unused)
2348{
2349 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2350 _setSSLError(NULL, 0, __FILE__, __LINE__);
2351 return NULL;
2352 }
2353 Py_RETURN_NONE;
2354}
2355
Antoine Pitrou501da612011-12-21 09:27:41 +01002356#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002357static PyObject *
2358set_ecdh_curve(PySSLContext *self, PyObject *name)
2359{
2360 PyObject *name_bytes;
2361 int nid;
2362 EC_KEY *key;
2363
2364 if (!PyUnicode_FSConverter(name, &name_bytes))
2365 return NULL;
2366 assert(PyBytes_Check(name_bytes));
2367 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2368 Py_DECREF(name_bytes);
2369 if (nid == 0) {
2370 PyErr_Format(PyExc_ValueError,
2371 "unknown elliptic curve name %R", name);
2372 return NULL;
2373 }
2374 key = EC_KEY_new_by_curve_name(nid);
2375 if (key == NULL) {
2376 _setSSLError(NULL, 0, __FILE__, __LINE__);
2377 return NULL;
2378 }
2379 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2380 EC_KEY_free(key);
2381 Py_RETURN_NONE;
2382}
Antoine Pitrou501da612011-12-21 09:27:41 +01002383#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002384
Antoine Pitrou152efa22010-05-16 18:19:27 +00002385static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002386 {"options", (getter) get_options,
2387 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002388 {"verify_mode", (getter) get_verify_mode,
2389 (setter) set_verify_mode, NULL},
2390 {NULL}, /* sentinel */
2391};
2392
2393static struct PyMethodDef context_methods[] = {
2394 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2395 METH_VARARGS | METH_KEYWORDS, NULL},
2396 {"set_ciphers", (PyCFunction) set_ciphers,
2397 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002398 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2399 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 {"load_cert_chain", (PyCFunction) load_cert_chain,
2401 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002402 {"load_dh_params", (PyCFunction) load_dh_params,
2403 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002404 {"load_verify_locations", (PyCFunction) load_verify_locations,
2405 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002406 {"session_stats", (PyCFunction) session_stats,
2407 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002408 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2409 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002410#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002411 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2412 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002413#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414 {NULL, NULL} /* sentinel */
2415};
2416
2417static PyTypeObject PySSLContext_Type = {
2418 PyVarObject_HEAD_INIT(NULL, 0)
2419 "_ssl._SSLContext", /*tp_name*/
2420 sizeof(PySSLContext), /*tp_basicsize*/
2421 0, /*tp_itemsize*/
2422 (destructor)context_dealloc, /*tp_dealloc*/
2423 0, /*tp_print*/
2424 0, /*tp_getattr*/
2425 0, /*tp_setattr*/
2426 0, /*tp_reserved*/
2427 0, /*tp_repr*/
2428 0, /*tp_as_number*/
2429 0, /*tp_as_sequence*/
2430 0, /*tp_as_mapping*/
2431 0, /*tp_hash*/
2432 0, /*tp_call*/
2433 0, /*tp_str*/
2434 0, /*tp_getattro*/
2435 0, /*tp_setattro*/
2436 0, /*tp_as_buffer*/
2437 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2438 0, /*tp_doc*/
2439 0, /*tp_traverse*/
2440 0, /*tp_clear*/
2441 0, /*tp_richcompare*/
2442 0, /*tp_weaklistoffset*/
2443 0, /*tp_iter*/
2444 0, /*tp_iternext*/
2445 context_methods, /*tp_methods*/
2446 0, /*tp_members*/
2447 context_getsetlist, /*tp_getset*/
2448 0, /*tp_base*/
2449 0, /*tp_dict*/
2450 0, /*tp_descr_get*/
2451 0, /*tp_descr_set*/
2452 0, /*tp_dictoffset*/
2453 0, /*tp_init*/
2454 0, /*tp_alloc*/
2455 context_new, /*tp_new*/
2456};
2457
2458
2459
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460#ifdef HAVE_OPENSSL_RAND
2461
2462/* helper routines for seeding the SSL PRNG */
2463static PyObject *
2464PySSL_RAND_add(PyObject *self, PyObject *args)
2465{
2466 char *buf;
2467 int len;
2468 double entropy;
2469
2470 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002472 RAND_add(buf, len, entropy);
2473 Py_INCREF(Py_None);
2474 return Py_None;
2475}
2476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002477PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002478"RAND_add(string, entropy)\n\
2479\n\
2480Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002481bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482
2483static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002484PySSL_RAND(int len, int pseudo)
2485{
2486 int ok;
2487 PyObject *bytes;
2488 unsigned long err;
2489 const char *errstr;
2490 PyObject *v;
2491
2492 bytes = PyBytes_FromStringAndSize(NULL, len);
2493 if (bytes == NULL)
2494 return NULL;
2495 if (pseudo) {
2496 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2497 if (ok == 0 || ok == 1)
2498 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2499 }
2500 else {
2501 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2502 if (ok == 1)
2503 return bytes;
2504 }
2505 Py_DECREF(bytes);
2506
2507 err = ERR_get_error();
2508 errstr = ERR_reason_error_string(err);
2509 v = Py_BuildValue("(ks)", err, errstr);
2510 if (v != NULL) {
2511 PyErr_SetObject(PySSLErrorObject, v);
2512 Py_DECREF(v);
2513 }
2514 return NULL;
2515}
2516
2517static PyObject *
2518PySSL_RAND_bytes(PyObject *self, PyObject *args)
2519{
2520 int len;
2521 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2522 return NULL;
2523 return PySSL_RAND(len, 0);
2524}
2525
2526PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2527"RAND_bytes(n) -> bytes\n\
2528\n\
2529Generate n cryptographically strong pseudo-random bytes.");
2530
2531static PyObject *
2532PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2533{
2534 int len;
2535 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2536 return NULL;
2537 return PySSL_RAND(len, 1);
2538}
2539
2540PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2541"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2542\n\
2543Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2544generated are cryptographically strong.");
2545
2546static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002547PySSL_RAND_status(PyObject *self)
2548{
Christian Heimes217cfd12007-12-02 14:31:20 +00002549 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002550}
2551
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002552PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002553"RAND_status() -> 0 or 1\n\
2554\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002555Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2556It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2557using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002558
2559static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002560PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002561{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002562 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002563 int bytes;
2564
Jesus Ceac8754a12012-09-11 02:00:58 +02002565 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002566 PyUnicode_FSConverter, &path))
2567 return NULL;
2568
2569 bytes = RAND_egd(PyBytes_AsString(path));
2570 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002571 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002572 PyErr_SetString(PySSLErrorObject,
2573 "EGD connection failed or EGD did not return "
2574 "enough data to seed the PRNG");
2575 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002576 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002577 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002578}
2579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002580PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002581"RAND_egd(path) -> bytes\n\
2582\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002583Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2584Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002585fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002586
Christian Heimesf77b4b22013-08-21 13:26:05 +02002587/* Seed OpenSSL's PRNG at fork(), http://bugs.python.org/issue18747
2588 *
Christian Heimes80c5de92013-08-22 13:19:48 +02002589 * The parent handler seeds the PRNG from pseudo-random data like pid, the
Christian Heimes61636e72013-08-25 14:19:16 +02002590 * current time (miliseconds or seconds) and an uninitialized array.
Christian Heimes80c5de92013-08-22 13:19:48 +02002591 * The array contains stack variables that are impossible to predict
Christian Heimesf77b4b22013-08-21 13:26:05 +02002592 * on most systems, e.g. function return address (subject to ASLR), the
2593 * stack protection canary and automatic variables.
2594 * The code is inspired by Apache's ssl_rand_seed() function.
2595 *
2596 * Note:
2597 * The code uses pthread_atfork() until Python has a proper atfork API. The
Christian Heimes80c5de92013-08-22 13:19:48 +02002598 * handlers are not removed from the child process. A parent handler is used
Christian Heimes61636e72013-08-25 14:19:16 +02002599 * instead of a child handler because fork() is supposed to be async-signal
Christian Heimes80c5de92013-08-22 13:19:48 +02002600 * safe but the handler calls unsafe functions.
Christian Heimesf77b4b22013-08-21 13:26:05 +02002601 */
2602
2603#if defined(HAVE_PTHREAD_ATFORK) && defined(WITH_THREAD)
2604#define PYSSL_RAND_ATFORK 1
2605
2606static void
Christian Heimes80c5de92013-08-22 13:19:48 +02002607PySSL_RAND_atfork_parent(void)
Christian Heimesf77b4b22013-08-21 13:26:05 +02002608{
2609 struct {
2610 char stack[128]; /* uninitialized (!) stack data, 128 is an
2611 arbitrary number. */
2612 pid_t pid; /* current pid */
2613 _PyTime_timeval tp; /* current time */
2614 } seed;
2615
2616#ifdef WITH_VALGRIND
2617 VALGRIND_MAKE_MEM_DEFINED(seed.stack, sizeof(seed.stack));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002618#endif
Christian Heimesf77b4b22013-08-21 13:26:05 +02002619 seed.pid = getpid();
2620 _PyTime_gettimeofday(&(seed.tp));
Christian Heimesf77b4b22013-08-21 13:26:05 +02002621 RAND_add((unsigned char *)&seed, sizeof(seed), 0.0);
2622}
2623
2624static int
2625PySSL_RAND_atfork(void)
2626{
2627 static int registered = 0;
2628 int retval;
2629
2630 if (registered)
2631 return 0;
2632
2633 retval = pthread_atfork(NULL, /* prepare */
Christian Heimes80c5de92013-08-22 13:19:48 +02002634 PySSL_RAND_atfork_parent, /* parent */
2635 NULL); /* child */
Christian Heimesf77b4b22013-08-21 13:26:05 +02002636 if (retval != 0) {
2637 PyErr_SetFromErrno(PyExc_OSError);
2638 return -1;
2639 }
2640 registered = 1;
2641 return 0;
2642}
2643#endif /* HAVE_PTHREAD_ATFORK */
2644
2645#endif /* HAVE_OPENSSL_RAND */
2646
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002647
Bill Janssen40a0f662008-08-12 16:56:25 +00002648
2649
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002650/* List of functions exported by this module. */
2651
2652static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002653 {"_test_decode_cert", PySSL_test_decode_certificate,
2654 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002655#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002656 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2657 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002658 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2659 PySSL_RAND_bytes_doc},
2660 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2661 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002662 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002663 PySSL_RAND_egd_doc},
2664 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2665 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002666#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002667 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002668};
2669
2670
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002671#ifdef WITH_THREAD
2672
2673/* an implementation of OpenSSL threading operations in terms
2674 of the Python C thread library */
2675
2676static PyThread_type_lock *_ssl_locks = NULL;
2677
Christian Heimes4d98ca92013-08-19 17:36:29 +02002678#if OPENSSL_VERSION_NUMBER >= 0x10000000
2679/* use new CRYPTO_THREADID API. */
2680static void
2681_ssl_threadid_callback(CRYPTO_THREADID *id)
2682{
2683 CRYPTO_THREADID_set_numeric(id,
2684 (unsigned long)PyThread_get_thread_ident());
2685}
2686#else
2687/* deprecated CRYPTO_set_id_callback() API. */
2688static unsigned long
2689_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002690 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002691}
Christian Heimes4d98ca92013-08-19 17:36:29 +02002692#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002693
Bill Janssen6e027db2007-11-15 22:23:56 +00002694static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002695 (int mode, int n, const char *file, int line) {
2696 /* this function is needed to perform locking on shared data
2697 structures. (Note that OpenSSL uses a number of global data
2698 structures that will be implicitly shared whenever multiple
2699 threads use OpenSSL.) Multi-threaded applications will
2700 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 locking_function() must be able to handle up to
2703 CRYPTO_num_locks() different mutex locks. It sets the n-th
2704 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002705
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002706 file and line are the file number of the function setting the
2707 lock. They can be useful for debugging.
2708 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002710 if ((_ssl_locks == NULL) ||
2711 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2712 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002714 if (mode & CRYPTO_LOCK) {
2715 PyThread_acquire_lock(_ssl_locks[n], 1);
2716 } else {
2717 PyThread_release_lock(_ssl_locks[n]);
2718 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002719}
2720
2721static int _setup_ssl_threads(void) {
2722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002723 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002725 if (_ssl_locks == NULL) {
2726 _ssl_locks_count = CRYPTO_num_locks();
2727 _ssl_locks = (PyThread_type_lock *)
2728 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2729 if (_ssl_locks == NULL)
2730 return 0;
2731 memset(_ssl_locks, 0,
2732 sizeof(PyThread_type_lock) * _ssl_locks_count);
2733 for (i = 0; i < _ssl_locks_count; i++) {
2734 _ssl_locks[i] = PyThread_allocate_lock();
2735 if (_ssl_locks[i] == NULL) {
2736 unsigned int j;
2737 for (j = 0; j < i; j++) {
2738 PyThread_free_lock(_ssl_locks[j]);
2739 }
2740 free(_ssl_locks);
2741 return 0;
2742 }
2743 }
2744 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002745#if OPENSSL_VERSION_NUMBER >= 0x10000000
2746 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
2747#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002748 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002749#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002750 }
2751 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002752}
2753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002754#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002756PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002757"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002758for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002759
Martin v. Löwis1a214512008-06-11 05:26:20 +00002760
2761static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002762 PyModuleDef_HEAD_INIT,
2763 "_ssl",
2764 module_doc,
2765 -1,
2766 PySSL_methods,
2767 NULL,
2768 NULL,
2769 NULL,
2770 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002771};
2772
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002773
2774static void
2775parse_openssl_version(unsigned long libver,
2776 unsigned int *major, unsigned int *minor,
2777 unsigned int *fix, unsigned int *patch,
2778 unsigned int *status)
2779{
2780 *status = libver & 0xF;
2781 libver >>= 4;
2782 *patch = libver & 0xFF;
2783 libver >>= 8;
2784 *fix = libver & 0xFF;
2785 libver >>= 8;
2786 *minor = libver & 0xFF;
2787 libver >>= 8;
2788 *major = libver & 0xFF;
2789}
2790
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002791PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002792PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002793{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002794 PyObject *m, *d, *r;
2795 unsigned long libver;
2796 unsigned int major, minor, fix, patch, status;
2797 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002798 struct py_ssl_error_code *errcode;
2799 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002800
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 if (PyType_Ready(&PySSLContext_Type) < 0)
2802 return NULL;
2803 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002804 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002806 m = PyModule_Create(&_sslmodule);
2807 if (m == NULL)
2808 return NULL;
2809 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002811 /* Load _socket module and its C API */
2812 socket_api = PySocketModule_ImportModuleAndAPI();
2813 if (!socket_api)
2814 return NULL;
2815 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002817 /* Init OpenSSL */
2818 SSL_load_error_strings();
2819 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002820#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002821 /* note that this will start threading if not already started */
2822 if (!_setup_ssl_threads()) {
2823 return NULL;
2824 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002825#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002826 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002828 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002829 sslerror_type_slots[0].pfunc = PyExc_OSError;
2830 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002831 if (PySSLErrorObject == NULL)
2832 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002833
Antoine Pitrou41032a62011-10-27 23:56:55 +02002834 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2835 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2836 PySSLErrorObject, NULL);
2837 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2838 "ssl.SSLWantReadError", SSLWantReadError_doc,
2839 PySSLErrorObject, NULL);
2840 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2841 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2842 PySSLErrorObject, NULL);
2843 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2844 "ssl.SSLSyscallError", SSLSyscallError_doc,
2845 PySSLErrorObject, NULL);
2846 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2847 "ssl.SSLEOFError", SSLEOFError_doc,
2848 PySSLErrorObject, NULL);
2849 if (PySSLZeroReturnErrorObject == NULL
2850 || PySSLWantReadErrorObject == NULL
2851 || PySSLWantWriteErrorObject == NULL
2852 || PySSLSyscallErrorObject == NULL
2853 || PySSLEOFErrorObject == NULL)
2854 return NULL;
2855 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2856 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2857 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2858 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2859 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2860 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002861 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002862 if (PyDict_SetItemString(d, "_SSLContext",
2863 (PyObject *)&PySSLContext_Type) != 0)
2864 return NULL;
2865 if (PyDict_SetItemString(d, "_SSLSocket",
2866 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002867 return NULL;
2868 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2869 PY_SSL_ERROR_ZERO_RETURN);
2870 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2871 PY_SSL_ERROR_WANT_READ);
2872 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2873 PY_SSL_ERROR_WANT_WRITE);
2874 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2875 PY_SSL_ERROR_WANT_X509_LOOKUP);
2876 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2877 PY_SSL_ERROR_SYSCALL);
2878 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2879 PY_SSL_ERROR_SSL);
2880 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2881 PY_SSL_ERROR_WANT_CONNECT);
2882 /* non ssl.h errorcodes */
2883 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2884 PY_SSL_ERROR_EOF);
2885 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2886 PY_SSL_ERROR_INVALID_ERROR_CODE);
2887 /* cert requirements */
2888 PyModule_AddIntConstant(m, "CERT_NONE",
2889 PY_SSL_CERT_NONE);
2890 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2891 PY_SSL_CERT_OPTIONAL);
2892 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2893 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002894
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002895 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002896#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002897 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2898 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002899#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002900 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2901 PY_SSL_VERSION_SSL3);
2902 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2903 PY_SSL_VERSION_SSL23);
2904 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2905 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002906
Antoine Pitroub5218772010-05-21 09:56:06 +00002907 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002908 PyModule_AddIntConstant(m, "OP_ALL",
2909 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002910 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2911 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2912 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002913 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2914 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002915 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002916#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002917 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002918#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002919#ifdef SSL_OP_NO_COMPRESSION
2920 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2921 SSL_OP_NO_COMPRESSION);
2922#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002923
Antoine Pitroud5323212010-10-22 18:19:07 +00002924#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2925 r = Py_True;
2926#else
2927 r = Py_False;
2928#endif
2929 Py_INCREF(r);
2930 PyModule_AddObject(m, "HAS_SNI", r);
2931
Antoine Pitroud6494802011-07-21 01:11:30 +02002932#if HAVE_OPENSSL_FINISHED
2933 r = Py_True;
2934#else
2935 r = Py_False;
2936#endif
2937 Py_INCREF(r);
2938 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2939
Antoine Pitrou501da612011-12-21 09:27:41 +01002940#ifdef OPENSSL_NO_ECDH
2941 r = Py_False;
2942#else
2943 r = Py_True;
2944#endif
2945 Py_INCREF(r);
2946 PyModule_AddObject(m, "HAS_ECDH", r);
2947
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002948#ifdef OPENSSL_NPN_NEGOTIATED
2949 r = Py_True;
2950#else
2951 r = Py_False;
2952#endif
2953 Py_INCREF(r);
2954 PyModule_AddObject(m, "HAS_NPN", r);
2955
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002956 /* Mappings for error codes */
2957 err_codes_to_names = PyDict_New();
2958 err_names_to_codes = PyDict_New();
2959 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2960 return NULL;
2961 errcode = error_codes;
2962 while (errcode->mnemonic != NULL) {
2963 PyObject *mnemo, *key;
2964 mnemo = PyUnicode_FromString(errcode->mnemonic);
2965 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2966 if (mnemo == NULL || key == NULL)
2967 return NULL;
2968 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2969 return NULL;
2970 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2971 return NULL;
2972 Py_DECREF(key);
2973 Py_DECREF(mnemo);
2974 errcode++;
2975 }
2976 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2977 return NULL;
2978 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2979 return NULL;
2980
2981 lib_codes_to_names = PyDict_New();
2982 if (lib_codes_to_names == NULL)
2983 return NULL;
2984 libcode = library_codes;
2985 while (libcode->library != NULL) {
2986 PyObject *mnemo, *key;
2987 key = PyLong_FromLong(libcode->code);
2988 mnemo = PyUnicode_FromString(libcode->library);
2989 if (key == NULL || mnemo == NULL)
2990 return NULL;
2991 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2992 return NULL;
2993 Py_DECREF(key);
2994 Py_DECREF(mnemo);
2995 libcode++;
2996 }
2997 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2998 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003000 /* OpenSSL version */
3001 /* SSLeay() gives us the version of the library linked against,
3002 which could be different from the headers version.
3003 */
3004 libver = SSLeay();
3005 r = PyLong_FromUnsignedLong(libver);
3006 if (r == NULL)
3007 return NULL;
3008 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3009 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003010 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003011 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3012 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3013 return NULL;
3014 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3015 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3016 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003017
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003018 libver = OPENSSL_VERSION_NUMBER;
3019 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3020 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3021 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3022 return NULL;
3023
Christian Heimesf77b4b22013-08-21 13:26:05 +02003024#ifdef PYSSL_RAND_ATFORK
3025 if (PySSL_RAND_atfork() == -1)
3026 return NULL;
3027#endif
3028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003029 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003030}