blob: 1ae543f155a701b53786a61fc3cae7cc0815ab45 [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;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 /* Make sure the SSL error state is initialized */
460 (void) ERR_get_state();
461 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000464 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000467#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000469#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000470
Antoine Pitroud5323212010-10-22 18:19:07 +0000471#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
472 if (server_hostname != NULL)
473 SSL_set_tlsext_host_name(self->ssl, server_hostname);
474#endif
475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 /* If the socket is in non-blocking mode or timeout mode, set the BIO
477 * to non-blocking mode (blocking is the default)
478 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000480 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
481 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
482 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000484 PySSL_BEGIN_ALLOW_THREADS
485 if (socket_type == PY_SSL_CLIENT)
486 SSL_set_connect_state(self->ssl);
487 else
488 SSL_set_accept_state(self->ssl);
489 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000490
Antoine Pitroud6494802011-07-21 01:11:30 +0200491 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000494}
495
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000496/* SSL object methods */
497
Antoine Pitrou152efa22010-05-16 18:19:27 +0000498static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000499{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 int ret;
501 int err;
502 int sockstate, nonblocking;
503 PySocketSockObject *sock
504 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000506 if (((PyObject*)sock) == Py_None) {
507 _setSSLError("Underlying socket connection gone",
508 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
509 return NULL;
510 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000511 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 /* just in case the blocking state of the socket has been changed */
514 nonblocking = (sock->sock_timeout >= 0.0);
515 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
516 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 /* Actually negotiate SSL connection */
519 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000521 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 ret = SSL_do_handshake(self->ssl);
523 err = SSL_get_error(self->ssl, ret);
524 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000525 if (PyErr_CheckSignals())
526 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 if (err == SSL_ERROR_WANT_READ) {
528 sockstate = check_socket_and_wait_for_timeout(sock, 0);
529 } else if (err == SSL_ERROR_WANT_WRITE) {
530 sockstate = check_socket_and_wait_for_timeout(sock, 1);
531 } else {
532 sockstate = SOCKET_OPERATION_OK;
533 }
534 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000535 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000536 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000537 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
539 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000540 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000541 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
543 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000544 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000545 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
547 break;
548 }
549 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000550 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 if (ret < 1)
552 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 if (self->peer_cert)
555 X509_free (self->peer_cert);
556 PySSL_BEGIN_ALLOW_THREADS
557 self->peer_cert = SSL_get_peer_certificate(self->ssl);
558 PySSL_END_ALLOW_THREADS
559
560 Py_INCREF(Py_None);
561 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000562
563error:
564 Py_DECREF(sock);
565 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000566}
567
Thomas Woutersed03b412007-08-28 21:37:11 +0000568static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 char namebuf[X509_NAME_MAXLEN];
572 int buflen;
573 PyObject *name_obj;
574 PyObject *value_obj;
575 PyObject *attr;
576 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
579 if (buflen < 0) {
580 _setSSLError(NULL, 0, __FILE__, __LINE__);
581 goto fail;
582 }
583 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
584 if (name_obj == NULL)
585 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
588 if (buflen < 0) {
589 _setSSLError(NULL, 0, __FILE__, __LINE__);
590 Py_DECREF(name_obj);
591 goto fail;
592 }
593 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000594 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 OPENSSL_free(valuebuf);
596 if (value_obj == NULL) {
597 Py_DECREF(name_obj);
598 goto fail;
599 }
600 attr = PyTuple_New(2);
601 if (attr == NULL) {
602 Py_DECREF(name_obj);
603 Py_DECREF(value_obj);
604 goto fail;
605 }
606 PyTuple_SET_ITEM(attr, 0, name_obj);
607 PyTuple_SET_ITEM(attr, 1, value_obj);
608 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000609
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000612}
613
614static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000616{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
618 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
619 PyObject *rdnt;
620 PyObject *attr = NULL; /* tuple to hold an attribute */
621 int entry_count = X509_NAME_entry_count(xname);
622 X509_NAME_ENTRY *entry;
623 ASN1_OBJECT *name;
624 ASN1_STRING *value;
625 int index_counter;
626 int rdn_level = -1;
627 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 dn = PyList_New(0);
630 if (dn == NULL)
631 return NULL;
632 /* now create another tuple to hold the top-level RDN */
633 rdn = PyList_New(0);
634 if (rdn == NULL)
635 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 for (index_counter = 0;
638 index_counter < entry_count;
639 index_counter++)
640 {
641 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* check to see if we've gotten to a new RDN */
644 if (rdn_level >= 0) {
645 if (rdn_level != entry->set) {
646 /* yes, new RDN */
647 /* add old RDN to DN */
648 rdnt = PyList_AsTuple(rdn);
649 Py_DECREF(rdn);
650 if (rdnt == NULL)
651 goto fail0;
652 retcode = PyList_Append(dn, rdnt);
653 Py_DECREF(rdnt);
654 if (retcode < 0)
655 goto fail0;
656 /* create new RDN */
657 rdn = PyList_New(0);
658 if (rdn == NULL)
659 goto fail0;
660 }
661 }
662 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 /* now add this attribute to the current RDN */
665 name = X509_NAME_ENTRY_get_object(entry);
666 value = X509_NAME_ENTRY_get_data(entry);
667 attr = _create_tuple_for_attribute(name, value);
668 /*
669 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
670 entry->set,
671 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
672 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
673 */
674 if (attr == NULL)
675 goto fail1;
676 retcode = PyList_Append(rdn, attr);
677 Py_DECREF(attr);
678 if (retcode < 0)
679 goto fail1;
680 }
681 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100682 if (rdn != NULL) {
683 if (PyList_GET_SIZE(rdn) > 0) {
684 rdnt = PyList_AsTuple(rdn);
685 Py_DECREF(rdn);
686 if (rdnt == NULL)
687 goto fail0;
688 retcode = PyList_Append(dn, rdnt);
689 Py_DECREF(rdnt);
690 if (retcode < 0)
691 goto fail0;
692 }
693 else {
694 Py_DECREF(rdn);
695 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 /* convert list to tuple */
699 rdnt = PyList_AsTuple(dn);
700 Py_DECREF(dn);
701 if (rdnt == NULL)
702 return NULL;
703 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704
705 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707
708 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 Py_XDECREF(dn);
710 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711}
712
713static PyObject *
714_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 /* this code follows the procedure outlined in
717 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
718 function to extract the STACK_OF(GENERAL_NAME),
719 then iterates through the stack to add the
720 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 int i, j;
723 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200724 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 X509_EXTENSION *ext = NULL;
726 GENERAL_NAMES *names = NULL;
727 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000728 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 BIO *biobuf = NULL;
730 char buf[2048];
731 char *vptr;
732 int len;
733 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000734#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000736#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000738#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 if (certificate == NULL)
741 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 /* get a memory buffer */
744 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200746 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 while ((i = X509_get_ext_by_NID(
748 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 if (peer_alt_names == Py_None) {
751 peer_alt_names = PyList_New(0);
752 if (peer_alt_names == NULL)
753 goto fail;
754 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 /* now decode the altName */
757 ext = X509_get_ext(certificate, i);
758 if(!(method = X509V3_EXT_get(ext))) {
759 PyErr_SetString
760 (PySSLErrorObject,
761 ERRSTR("No method for internalizing subjectAltName!"));
762 goto fail;
763 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 p = ext->value->data;
766 if (method->it)
767 names = (GENERAL_NAMES*)
768 (ASN1_item_d2i(NULL,
769 &p,
770 ext->value->length,
771 ASN1_ITEM_ptr(method->it)));
772 else
773 names = (GENERAL_NAMES*)
774 (method->d2i(NULL,
775 &p,
776 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000777
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200780 int gntype;
781 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200784 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200785 switch (gntype) {
786 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 /* we special-case DirName as a tuple of
788 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 t = PyTuple_New(2);
791 if (t == NULL) {
792 goto fail;
793 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 v = PyUnicode_FromString("DirName");
796 if (v == NULL) {
797 Py_DECREF(t);
798 goto fail;
799 }
800 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 v = _create_tuple_for_X509_NAME (name->d.dirn);
803 if (v == NULL) {
804 Py_DECREF(t);
805 goto fail;
806 }
807 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200808 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000809
Christian Heimes824f7f32013-08-17 00:54:47 +0200810 case GEN_EMAIL:
811 case GEN_DNS:
812 case GEN_URI:
813 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
814 correctly, CVE-2013-4238 */
815 t = PyTuple_New(2);
816 if (t == NULL)
817 goto fail;
818 switch (gntype) {
819 case GEN_EMAIL:
820 v = PyUnicode_FromString("email");
821 as = name->d.rfc822Name;
822 break;
823 case GEN_DNS:
824 v = PyUnicode_FromString("DNS");
825 as = name->d.dNSName;
826 break;
827 case GEN_URI:
828 v = PyUnicode_FromString("URI");
829 as = name->d.uniformResourceIdentifier;
830 break;
831 }
832 if (v == NULL) {
833 Py_DECREF(t);
834 goto fail;
835 }
836 PyTuple_SET_ITEM(t, 0, v);
837 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
838 ASN1_STRING_length(as));
839 if (v == NULL) {
840 Py_DECREF(t);
841 goto fail;
842 }
843 PyTuple_SET_ITEM(t, 1, v);
844 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845
Christian Heimes824f7f32013-08-17 00:54:47 +0200846 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200848 switch (gntype) {
849 /* check for new general name type */
850 case GEN_OTHERNAME:
851 case GEN_X400:
852 case GEN_EDIPARTY:
853 case GEN_IPADD:
854 case GEN_RID:
855 break;
856 default:
857 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
858 "Unknown general name type %d",
859 gntype) == -1) {
860 goto fail;
861 }
862 break;
863 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 (void) BIO_reset(biobuf);
865 GENERAL_NAME_print(biobuf, name);
866 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
867 if (len < 0) {
868 _setSSLError(NULL, 0, __FILE__, __LINE__);
869 goto fail;
870 }
871 vptr = strchr(buf, ':');
872 if (vptr == NULL)
873 goto fail;
874 t = PyTuple_New(2);
875 if (t == NULL)
876 goto fail;
877 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
878 if (v == NULL) {
879 Py_DECREF(t);
880 goto fail;
881 }
882 PyTuple_SET_ITEM(t, 0, v);
883 v = PyUnicode_FromStringAndSize((vptr + 1),
884 (len - (vptr - buf + 1)));
885 if (v == NULL) {
886 Py_DECREF(t);
887 goto fail;
888 }
889 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200890 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 if (PyList_Append(peer_alt_names, t) < 0) {
896 Py_DECREF(t);
897 goto fail;
898 }
899 Py_DECREF(t);
900 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100901 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 }
903 BIO_free(biobuf);
904 if (peer_alt_names != Py_None) {
905 v = PyList_AsTuple(peer_alt_names);
906 Py_DECREF(peer_alt_names);
907 return v;
908 } else {
909 return peer_alt_names;
910 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000911
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
913 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 if (biobuf != NULL)
915 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 if (peer_alt_names != Py_None) {
918 Py_XDECREF(peer_alt_names);
919 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922}
923
924static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000925_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 PyObject *retval = NULL;
928 BIO *biobuf = NULL;
929 PyObject *peer;
930 PyObject *peer_alt_names = NULL;
931 PyObject *issuer;
932 PyObject *version;
933 PyObject *sn_obj;
934 ASN1_INTEGER *serialNumber;
935 char buf[2048];
936 int len;
937 ASN1_TIME *notBefore, *notAfter;
938 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 retval = PyDict_New();
941 if (retval == NULL)
942 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 peer = _create_tuple_for_X509_NAME(
945 X509_get_subject_name(certificate));
946 if (peer == NULL)
947 goto fail0;
948 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
949 Py_DECREF(peer);
950 goto fail0;
951 }
952 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000953
Antoine Pitroufb046912010-11-09 20:21:19 +0000954 issuer = _create_tuple_for_X509_NAME(
955 X509_get_issuer_name(certificate));
956 if (issuer == NULL)
957 goto fail0;
958 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000960 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000962 Py_DECREF(issuer);
963
964 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200965 if (version == NULL)
966 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000967 if (PyDict_SetItemString(retval, "version", version) < 0) {
968 Py_DECREF(version);
969 goto fail0;
970 }
971 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 /* get a memory buffer */
974 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000975
Antoine Pitroufb046912010-11-09 20:21:19 +0000976 (void) BIO_reset(biobuf);
977 serialNumber = X509_get_serialNumber(certificate);
978 /* should not exceed 20 octets, 160 bits, so buf is big enough */
979 i2a_ASN1_INTEGER(biobuf, serialNumber);
980 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
981 if (len < 0) {
982 _setSSLError(NULL, 0, __FILE__, __LINE__);
983 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000985 sn_obj = PyUnicode_FromStringAndSize(buf, len);
986 if (sn_obj == NULL)
987 goto fail1;
988 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
989 Py_DECREF(sn_obj);
990 goto fail1;
991 }
992 Py_DECREF(sn_obj);
993
994 (void) BIO_reset(biobuf);
995 notBefore = X509_get_notBefore(certificate);
996 ASN1_TIME_print(biobuf, notBefore);
997 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
998 if (len < 0) {
999 _setSSLError(NULL, 0, __FILE__, __LINE__);
1000 goto fail1;
1001 }
1002 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1003 if (pnotBefore == NULL)
1004 goto fail1;
1005 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1006 Py_DECREF(pnotBefore);
1007 goto fail1;
1008 }
1009 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 (void) BIO_reset(biobuf);
1012 notAfter = X509_get_notAfter(certificate);
1013 ASN1_TIME_print(biobuf, notAfter);
1014 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1015 if (len < 0) {
1016 _setSSLError(NULL, 0, __FILE__, __LINE__);
1017 goto fail1;
1018 }
1019 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1020 if (pnotAfter == NULL)
1021 goto fail1;
1022 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1023 Py_DECREF(pnotAfter);
1024 goto fail1;
1025 }
1026 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 peer_alt_names = _get_peer_alt_names(certificate);
1031 if (peer_alt_names == NULL)
1032 goto fail1;
1033 else if (peer_alt_names != Py_None) {
1034 if (PyDict_SetItemString(retval, "subjectAltName",
1035 peer_alt_names) < 0) {
1036 Py_DECREF(peer_alt_names);
1037 goto fail1;
1038 }
1039 Py_DECREF(peer_alt_names);
1040 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 BIO_free(biobuf);
1043 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001044
1045 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 if (biobuf != NULL)
1047 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001048 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 Py_XDECREF(retval);
1050 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001051}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001052
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053
1054static PyObject *
1055PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001058 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 X509 *x=NULL;
1060 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Antoine Pitroufb046912010-11-09 20:21:19 +00001062 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1063 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1067 PyErr_SetString(PySSLErrorObject,
1068 "Can't malloc memory to read file");
1069 goto fail0;
1070 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071
Victor Stinner3800e1e2010-05-16 21:23:48 +00001072 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 PyErr_SetString(PySSLErrorObject,
1074 "Can't open file");
1075 goto fail0;
1076 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1079 if (x == NULL) {
1080 PyErr_SetString(PySSLErrorObject,
1081 "Error decoding PEM-encoded file");
1082 goto fail0;
1083 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroufb046912010-11-09 20:21:19 +00001085 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001086 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001087
1088 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001089 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 if (cert != NULL) BIO_free(cert);
1091 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092}
1093
1094
1095static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001096PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001097{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 PyObject *retval = NULL;
1099 int len;
1100 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001101 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102
Antoine Pitrou721738f2012-08-15 23:20:39 +02001103 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 if (!self->peer_cert)
1107 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108
Antoine Pitrou721738f2012-08-15 23:20:39 +02001109 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 bytes_buf = NULL;
1115 len = i2d_X509(self->peer_cert, &bytes_buf);
1116 if (len < 0) {
1117 PySSL_SetError(self, len, __FILE__, __LINE__);
1118 return NULL;
1119 }
1120 /* this is actually an immutable bytes sequence */
1121 retval = PyBytes_FromStringAndSize
1122 ((const char *) bytes_buf, len);
1123 OPENSSL_free(bytes_buf);
1124 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001127 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 if ((verification & SSL_VERIFY_PEER) == 0)
1129 return PyDict_New();
1130 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001131 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001132 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133}
1134
1135PyDoc_STRVAR(PySSL_peercert_doc,
1136"peer_certificate([der=False]) -> certificate\n\
1137\n\
1138Returns the certificate for the peer. If no certificate was provided,\n\
1139returns None. If a certificate was provided, but not validated, returns\n\
1140an empty dictionary. Otherwise returns a dict containing information\n\
1141about the peer certificate.\n\
1142\n\
1143If the optional argument is True, returns a DER-encoded copy of the\n\
1144peer certificate, or None if no certificate was provided. This will\n\
1145return the certificate even if it wasn't validated.");
1146
Antoine Pitrou152efa22010-05-16 18:19:27 +00001147static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001150 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 char *cipher_name;
1152 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001155 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 current = SSL_get_current_cipher(self->ssl);
1157 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001158 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 retval = PyTuple_New(3);
1161 if (retval == NULL)
1162 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 cipher_name = (char *) SSL_CIPHER_get_name(current);
1165 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001166 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 PyTuple_SET_ITEM(retval, 0, Py_None);
1168 } else {
1169 v = PyUnicode_FromString(cipher_name);
1170 if (v == NULL)
1171 goto fail0;
1172 PyTuple_SET_ITEM(retval, 0, v);
1173 }
1174 cipher_protocol = SSL_CIPHER_get_version(current);
1175 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001176 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 PyTuple_SET_ITEM(retval, 1, Py_None);
1178 } else {
1179 v = PyUnicode_FromString(cipher_protocol);
1180 if (v == NULL)
1181 goto fail0;
1182 PyTuple_SET_ITEM(retval, 1, v);
1183 }
1184 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1185 if (v == NULL)
1186 goto fail0;
1187 PyTuple_SET_ITEM(retval, 2, v);
1188 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001189
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 Py_DECREF(retval);
1192 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193}
1194
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001195#ifdef OPENSSL_NPN_NEGOTIATED
1196static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1197 const unsigned char *out;
1198 unsigned int outlen;
1199
Victor Stinner4569cd52013-06-23 14:58:43 +02001200 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001201 &out, &outlen);
1202
1203 if (out == NULL)
1204 Py_RETURN_NONE;
1205 return PyUnicode_FromStringAndSize((char *) out, outlen);
1206}
1207#endif
1208
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001209static PyObject *PySSL_compression(PySSLSocket *self) {
1210#ifdef OPENSSL_NO_COMP
1211 Py_RETURN_NONE;
1212#else
1213 const COMP_METHOD *comp_method;
1214 const char *short_name;
1215
1216 if (self->ssl == NULL)
1217 Py_RETURN_NONE;
1218 comp_method = SSL_get_current_compression(self->ssl);
1219 if (comp_method == NULL || comp_method->type == NID_undef)
1220 Py_RETURN_NONE;
1221 short_name = OBJ_nid2sn(comp_method->type);
1222 if (short_name == NULL)
1223 Py_RETURN_NONE;
1224 return PyUnicode_DecodeFSDefault(short_name);
1225#endif
1226}
1227
Antoine Pitrou152efa22010-05-16 18:19:27 +00001228static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001229{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 if (self->peer_cert) /* Possible not to have one? */
1231 X509_free (self->peer_cert);
1232 if (self->ssl)
1233 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 Py_XDECREF(self->Socket);
1235 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001236}
1237
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001238/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001239 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001240 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001241 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001242
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001243static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001244check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001245{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 fd_set fds;
1247 struct timeval tv;
1248 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1251 if (s->sock_timeout < 0.0)
1252 return SOCKET_IS_BLOCKING;
1253 else if (s->sock_timeout == 0.0)
1254 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 /* Guard against closed socket */
1257 if (s->sock_fd < 0)
1258 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* Prefer poll, if available, since you can poll() any fd
1261 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001262#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 {
1264 struct pollfd pollfd;
1265 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 pollfd.fd = s->sock_fd;
1268 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 /* s->sock_timeout is in seconds, timeout in ms */
1271 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1272 PySSL_BEGIN_ALLOW_THREADS
1273 rc = poll(&pollfd, 1, timeout);
1274 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 goto normal_return;
1277 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001278#endif
1279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001281 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 /* Construct the arguments to select */
1285 tv.tv_sec = (int)s->sock_timeout;
1286 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1287 FD_ZERO(&fds);
1288 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 /* See if the socket is ready */
1291 PySSL_BEGIN_ALLOW_THREADS
1292 if (writing)
1293 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1294 else
1295 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1296 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001297
Bill Janssen6e027db2007-11-15 22:23:56 +00001298#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001299normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001300#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1302 (when we are able to write or when there's something to read) */
1303 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001304}
1305
Antoine Pitrou152efa22010-05-16 18:19:27 +00001306static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001307{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 Py_buffer buf;
1309 int len;
1310 int sockstate;
1311 int err;
1312 int nonblocking;
1313 PySocketSockObject *sock
1314 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 if (((PyObject*)sock) == Py_None) {
1317 _setSSLError("Underlying socket connection gone",
1318 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1319 return NULL;
1320 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001321 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001322
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001323 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1324 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001326 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327
Victor Stinner6efa9652013-06-25 00:42:31 +02001328 if (buf.len > INT_MAX) {
1329 PyErr_Format(PyExc_OverflowError,
1330 "string longer than %d bytes", INT_MAX);
1331 goto error;
1332 }
1333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* just in case the blocking state of the socket has been changed */
1335 nonblocking = (sock->sock_timeout >= 0.0);
1336 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1337 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1338
1339 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1340 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001341 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 "The write operation timed out");
1343 goto error;
1344 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1345 PyErr_SetString(PySSLErrorObject,
1346 "Underlying socket has been closed.");
1347 goto error;
1348 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1349 PyErr_SetString(PySSLErrorObject,
1350 "Underlying socket too large for select().");
1351 goto error;
1352 }
1353 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001355 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 err = SSL_get_error(self->ssl, len);
1357 PySSL_END_ALLOW_THREADS
1358 if (PyErr_CheckSignals()) {
1359 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001360 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001362 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001364 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 } else {
1366 sockstate = SOCKET_OPERATION_OK;
1367 }
1368 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001369 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 "The write operation timed out");
1371 goto error;
1372 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1373 PyErr_SetString(PySSLErrorObject,
1374 "Underlying socket has been closed.");
1375 goto error;
1376 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1377 break;
1378 }
1379 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001380
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001381 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 PyBuffer_Release(&buf);
1383 if (len > 0)
1384 return PyLong_FromLong(len);
1385 else
1386 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001387
1388error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001389 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 PyBuffer_Release(&buf);
1391 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001392}
1393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001394PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395"write(s) -> len\n\
1396\n\
1397Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001399
Antoine Pitrou152efa22010-05-16 18:19:27 +00001400static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001401{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 PySSL_BEGIN_ALLOW_THREADS
1405 count = SSL_pending(self->ssl);
1406 PySSL_END_ALLOW_THREADS
1407 if (count < 0)
1408 return PySSL_SetError(self, count, __FILE__, __LINE__);
1409 else
1410 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001411}
1412
1413PyDoc_STRVAR(PySSL_SSLpending_doc,
1414"pending() -> count\n\
1415\n\
1416Returns the number of already decrypted bytes available for read,\n\
1417pending on the connection.\n");
1418
Antoine Pitrou152efa22010-05-16 18:19:27 +00001419static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001420{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 PyObject *dest = NULL;
1422 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001424 int len, count;
1425 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 int sockstate;
1427 int err;
1428 int nonblocking;
1429 PySocketSockObject *sock
1430 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001431
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 if (((PyObject*)sock) == Py_None) {
1433 _setSSLError("Underlying socket connection gone",
1434 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1435 return NULL;
1436 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001437 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001439 buf.obj = NULL;
1440 buf.buf = NULL;
1441 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001442 goto error;
1443
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001444 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1445 dest = PyBytes_FromStringAndSize(NULL, len);
1446 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001447 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001448 mem = PyBytes_AS_STRING(dest);
1449 }
1450 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001452 mem = buf.buf;
1453 if (len <= 0 || len > buf.len) {
1454 len = (int) buf.len;
1455 if (buf.len != len) {
1456 PyErr_SetString(PyExc_OverflowError,
1457 "maximum length can't fit in a C 'int'");
1458 goto error;
1459 }
1460 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 }
1462
1463 /* just in case the blocking state of the socket has been changed */
1464 nonblocking = (sock->sock_timeout >= 0.0);
1465 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1466 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1467
1468 /* first check if there are bytes ready to be read */
1469 PySSL_BEGIN_ALLOW_THREADS
1470 count = SSL_pending(self->ssl);
1471 PySSL_END_ALLOW_THREADS
1472
1473 if (!count) {
1474 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1475 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001476 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 "The read operation timed out");
1478 goto error;
1479 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1480 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001481 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 goto error;
1483 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1484 count = 0;
1485 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001486 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 }
1488 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 PySSL_BEGIN_ALLOW_THREADS
1490 count = SSL_read(self->ssl, mem, len);
1491 err = SSL_get_error(self->ssl, count);
1492 PySSL_END_ALLOW_THREADS
1493 if (PyErr_CheckSignals())
1494 goto error;
1495 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001496 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001498 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1500 (SSL_get_shutdown(self->ssl) ==
1501 SSL_RECEIVED_SHUTDOWN))
1502 {
1503 count = 0;
1504 goto done;
1505 } else {
1506 sockstate = SOCKET_OPERATION_OK;
1507 }
1508 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001509 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001510 "The read operation timed out");
1511 goto error;
1512 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1513 break;
1514 }
1515 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1516 if (count <= 0) {
1517 PySSL_SetError(self, count, __FILE__, __LINE__);
1518 goto error;
1519 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001520
1521done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001522 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001524 _PyBytes_Resize(&dest, count);
1525 return dest;
1526 }
1527 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 PyBuffer_Release(&buf);
1529 return PyLong_FromLong(count);
1530 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001531
1532error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001533 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001534 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001535 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001536 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001539}
1540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001541PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001542"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001543\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001544Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001545
Antoine Pitrou152efa22010-05-16 18:19:27 +00001546static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001547{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 int err, ssl_err, sockstate, nonblocking;
1549 int zeros = 0;
1550 PySocketSockObject *sock
1551 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001552
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 /* Guard against closed socket */
1554 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1555 _setSSLError("Underlying socket connection gone",
1556 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1557 return NULL;
1558 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001559 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560
1561 /* Just in case the blocking state of the socket has been changed */
1562 nonblocking = (sock->sock_timeout >= 0.0);
1563 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1564 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1565
1566 while (1) {
1567 PySSL_BEGIN_ALLOW_THREADS
1568 /* Disable read-ahead so that unwrap can work correctly.
1569 * Otherwise OpenSSL might read in too much data,
1570 * eating clear text data that happens to be
1571 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001572 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 * function is used and the shutdown_seen_zero != 0
1574 * condition is met.
1575 */
1576 if (self->shutdown_seen_zero)
1577 SSL_set_read_ahead(self->ssl, 0);
1578 err = SSL_shutdown(self->ssl);
1579 PySSL_END_ALLOW_THREADS
1580 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1581 if (err > 0)
1582 break;
1583 if (err == 0) {
1584 /* Don't loop endlessly; instead preserve legacy
1585 behaviour of trying SSL_shutdown() only twice.
1586 This looks necessary for OpenSSL < 0.9.8m */
1587 if (++zeros > 1)
1588 break;
1589 /* Shutdown was sent, now try receiving */
1590 self->shutdown_seen_zero = 1;
1591 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001592 }
1593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001594 /* Possibly retry shutdown until timeout or failure */
1595 ssl_err = SSL_get_error(self->ssl, err);
1596 if (ssl_err == SSL_ERROR_WANT_READ)
1597 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1598 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1599 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1600 else
1601 break;
1602 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1603 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001604 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 "The read operation timed out");
1606 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001607 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001608 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001609 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 }
1611 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1612 PyErr_SetString(PySSLErrorObject,
1613 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001614 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 }
1616 else if (sockstate != SOCKET_OPERATION_OK)
1617 /* Retain the SSL error code */
1618 break;
1619 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001620
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001621 if (err < 0) {
1622 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001625 else
1626 /* It's already INCREF'ed */
1627 return (PyObject *) sock;
1628
1629error:
1630 Py_DECREF(sock);
1631 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001632}
1633
1634PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1635"shutdown(s) -> socket\n\
1636\n\
1637Does the SSL shutdown handshake with the remote end, and returns\n\
1638the underlying socket object.");
1639
Antoine Pitroud6494802011-07-21 01:11:30 +02001640#if HAVE_OPENSSL_FINISHED
1641static PyObject *
1642PySSL_tls_unique_cb(PySSLSocket *self)
1643{
1644 PyObject *retval = NULL;
1645 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001646 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001647
1648 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1649 /* if session is resumed XOR we are the client */
1650 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1651 }
1652 else {
1653 /* if a new session XOR we are the server */
1654 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1655 }
1656
1657 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001658 if (len == 0)
1659 Py_RETURN_NONE;
1660
1661 retval = PyBytes_FromStringAndSize(buf, len);
1662
1663 return retval;
1664}
1665
1666PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1667"tls_unique_cb() -> bytes\n\
1668\n\
1669Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1670\n\
1671If the TLS handshake is not yet complete, None is returned");
1672
1673#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001674
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1677 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1678 PySSL_SSLwrite_doc},
1679 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1680 PySSL_SSLread_doc},
1681 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1682 PySSL_SSLpending_doc},
1683 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1684 PySSL_peercert_doc},
1685 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001686#ifdef OPENSSL_NPN_NEGOTIATED
1687 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1688#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001689 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1691 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001692#if HAVE_OPENSSL_FINISHED
1693 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1694 PySSL_tls_unique_cb_doc},
1695#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001697};
1698
Antoine Pitrou152efa22010-05-16 18:19:27 +00001699static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001701 "_ssl._SSLSocket", /*tp_name*/
1702 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 0, /*tp_itemsize*/
1704 /* methods */
1705 (destructor)PySSL_dealloc, /*tp_dealloc*/
1706 0, /*tp_print*/
1707 0, /*tp_getattr*/
1708 0, /*tp_setattr*/
1709 0, /*tp_reserved*/
1710 0, /*tp_repr*/
1711 0, /*tp_as_number*/
1712 0, /*tp_as_sequence*/
1713 0, /*tp_as_mapping*/
1714 0, /*tp_hash*/
1715 0, /*tp_call*/
1716 0, /*tp_str*/
1717 0, /*tp_getattro*/
1718 0, /*tp_setattro*/
1719 0, /*tp_as_buffer*/
1720 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1721 0, /*tp_doc*/
1722 0, /*tp_traverse*/
1723 0, /*tp_clear*/
1724 0, /*tp_richcompare*/
1725 0, /*tp_weaklistoffset*/
1726 0, /*tp_iter*/
1727 0, /*tp_iternext*/
1728 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001729};
1730
Antoine Pitrou152efa22010-05-16 18:19:27 +00001731
1732/*
1733 * _SSLContext objects
1734 */
1735
1736static PyObject *
1737context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1738{
1739 char *kwlist[] = {"protocol", NULL};
1740 PySSLContext *self;
1741 int proto_version = PY_SSL_VERSION_SSL23;
1742 SSL_CTX *ctx = NULL;
1743
1744 if (!PyArg_ParseTupleAndKeywords(
1745 args, kwds, "i:_SSLContext", kwlist,
1746 &proto_version))
1747 return NULL;
1748
1749 PySSL_BEGIN_ALLOW_THREADS
1750 if (proto_version == PY_SSL_VERSION_TLS1)
1751 ctx = SSL_CTX_new(TLSv1_method());
1752 else if (proto_version == PY_SSL_VERSION_SSL3)
1753 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001754#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001755 else if (proto_version == PY_SSL_VERSION_SSL2)
1756 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001757#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001758 else if (proto_version == PY_SSL_VERSION_SSL23)
1759 ctx = SSL_CTX_new(SSLv23_method());
1760 else
1761 proto_version = -1;
1762 PySSL_END_ALLOW_THREADS
1763
1764 if (proto_version == -1) {
1765 PyErr_SetString(PyExc_ValueError,
1766 "invalid protocol version");
1767 return NULL;
1768 }
1769 if (ctx == NULL) {
1770 PyErr_SetString(PySSLErrorObject,
1771 "failed to allocate SSL context");
1772 return NULL;
1773 }
1774
1775 assert(type != NULL && type->tp_alloc != NULL);
1776 self = (PySSLContext *) type->tp_alloc(type, 0);
1777 if (self == NULL) {
1778 SSL_CTX_free(ctx);
1779 return NULL;
1780 }
1781 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001782#ifdef OPENSSL_NPN_NEGOTIATED
1783 self->npn_protocols = NULL;
1784#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001785 /* Defaults */
1786 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001787 SSL_CTX_set_options(self->ctx,
1788 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001789
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001790#define SID_CTX "Python"
1791 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1792 sizeof(SID_CTX));
1793#undef SID_CTX
1794
Antoine Pitrou152efa22010-05-16 18:19:27 +00001795 return (PyObject *)self;
1796}
1797
1798static void
1799context_dealloc(PySSLContext *self)
1800{
1801 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001802#ifdef OPENSSL_NPN_NEGOTIATED
1803 PyMem_Free(self->npn_protocols);
1804#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001805 Py_TYPE(self)->tp_free(self);
1806}
1807
1808static PyObject *
1809set_ciphers(PySSLContext *self, PyObject *args)
1810{
1811 int ret;
1812 const char *cipherlist;
1813
1814 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1815 return NULL;
1816 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1817 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001818 /* Clearing the error queue is necessary on some OpenSSL versions,
1819 otherwise the error will be reported again when another SSL call
1820 is done. */
1821 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001822 PyErr_SetString(PySSLErrorObject,
1823 "No cipher can be selected.");
1824 return NULL;
1825 }
1826 Py_RETURN_NONE;
1827}
1828
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001829#ifdef OPENSSL_NPN_NEGOTIATED
1830/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1831static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001832_advertiseNPN_cb(SSL *s,
1833 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001834 void *args)
1835{
1836 PySSLContext *ssl_ctx = (PySSLContext *) args;
1837
1838 if (ssl_ctx->npn_protocols == NULL) {
1839 *data = (unsigned char *) "";
1840 *len = 0;
1841 } else {
1842 *data = (unsigned char *) ssl_ctx->npn_protocols;
1843 *len = ssl_ctx->npn_protocols_len;
1844 }
1845
1846 return SSL_TLSEXT_ERR_OK;
1847}
1848/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1849static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001850_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001851 unsigned char **out, unsigned char *outlen,
1852 const unsigned char *server, unsigned int server_len,
1853 void *args)
1854{
1855 PySSLContext *ssl_ctx = (PySSLContext *) args;
1856
1857 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1858 int client_len;
1859
1860 if (client == NULL) {
1861 client = (unsigned char *) "";
1862 client_len = 0;
1863 } else {
1864 client_len = ssl_ctx->npn_protocols_len;
1865 }
1866
1867 SSL_select_next_proto(out, outlen,
1868 server, server_len,
1869 client, client_len);
1870
1871 return SSL_TLSEXT_ERR_OK;
1872}
1873#endif
1874
1875static PyObject *
1876_set_npn_protocols(PySSLContext *self, PyObject *args)
1877{
1878#ifdef OPENSSL_NPN_NEGOTIATED
1879 Py_buffer protos;
1880
1881 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1882 return NULL;
1883
Christian Heimes5cb31c92012-09-20 12:42:54 +02001884 if (self->npn_protocols != NULL) {
1885 PyMem_Free(self->npn_protocols);
1886 }
1887
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001888 self->npn_protocols = PyMem_Malloc(protos.len);
1889 if (self->npn_protocols == NULL) {
1890 PyBuffer_Release(&protos);
1891 return PyErr_NoMemory();
1892 }
1893 memcpy(self->npn_protocols, protos.buf, protos.len);
1894 self->npn_protocols_len = (int) protos.len;
1895
1896 /* set both server and client callbacks, because the context can
1897 * be used to create both types of sockets */
1898 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1899 _advertiseNPN_cb,
1900 self);
1901 SSL_CTX_set_next_proto_select_cb(self->ctx,
1902 _selectNPN_cb,
1903 self);
1904
1905 PyBuffer_Release(&protos);
1906 Py_RETURN_NONE;
1907#else
1908 PyErr_SetString(PyExc_NotImplementedError,
1909 "The NPN extension requires OpenSSL 1.0.1 or later.");
1910 return NULL;
1911#endif
1912}
1913
Antoine Pitrou152efa22010-05-16 18:19:27 +00001914static PyObject *
1915get_verify_mode(PySSLContext *self, void *c)
1916{
1917 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1918 case SSL_VERIFY_NONE:
1919 return PyLong_FromLong(PY_SSL_CERT_NONE);
1920 case SSL_VERIFY_PEER:
1921 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1922 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1923 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1924 }
1925 PyErr_SetString(PySSLErrorObject,
1926 "invalid return value from SSL_CTX_get_verify_mode");
1927 return NULL;
1928}
1929
1930static int
1931set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1932{
1933 int n, mode;
1934 if (!PyArg_Parse(arg, "i", &n))
1935 return -1;
1936 if (n == PY_SSL_CERT_NONE)
1937 mode = SSL_VERIFY_NONE;
1938 else if (n == PY_SSL_CERT_OPTIONAL)
1939 mode = SSL_VERIFY_PEER;
1940 else if (n == PY_SSL_CERT_REQUIRED)
1941 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1942 else {
1943 PyErr_SetString(PyExc_ValueError,
1944 "invalid value for verify_mode");
1945 return -1;
1946 }
1947 SSL_CTX_set_verify(self->ctx, mode, NULL);
1948 return 0;
1949}
1950
1951static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001952get_options(PySSLContext *self, void *c)
1953{
1954 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1955}
1956
1957static int
1958set_options(PySSLContext *self, PyObject *arg, void *c)
1959{
1960 long new_opts, opts, set, clear;
1961 if (!PyArg_Parse(arg, "l", &new_opts))
1962 return -1;
1963 opts = SSL_CTX_get_options(self->ctx);
1964 clear = opts & ~new_opts;
1965 set = ~opts & new_opts;
1966 if (clear) {
1967#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1968 SSL_CTX_clear_options(self->ctx, clear);
1969#else
1970 PyErr_SetString(PyExc_ValueError,
1971 "can't clear options before OpenSSL 0.9.8m");
1972 return -1;
1973#endif
1974 }
1975 if (set)
1976 SSL_CTX_set_options(self->ctx, set);
1977 return 0;
1978}
1979
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001980typedef struct {
1981 PyThreadState *thread_state;
1982 PyObject *callable;
1983 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001984 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001985 int error;
1986} _PySSLPasswordInfo;
1987
1988static int
1989_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1990 const char *bad_type_error)
1991{
1992 /* Set the password and size fields of a _PySSLPasswordInfo struct
1993 from a unicode, bytes, or byte array object.
1994 The password field will be dynamically allocated and must be freed
1995 by the caller */
1996 PyObject *password_bytes = NULL;
1997 const char *data = NULL;
1998 Py_ssize_t size;
1999
2000 if (PyUnicode_Check(password)) {
2001 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2002 if (!password_bytes) {
2003 goto error;
2004 }
2005 data = PyBytes_AS_STRING(password_bytes);
2006 size = PyBytes_GET_SIZE(password_bytes);
2007 } else if (PyBytes_Check(password)) {
2008 data = PyBytes_AS_STRING(password);
2009 size = PyBytes_GET_SIZE(password);
2010 } else if (PyByteArray_Check(password)) {
2011 data = PyByteArray_AS_STRING(password);
2012 size = PyByteArray_GET_SIZE(password);
2013 } else {
2014 PyErr_SetString(PyExc_TypeError, bad_type_error);
2015 goto error;
2016 }
2017
Victor Stinner9ee02032013-06-23 15:08:23 +02002018 if (size > (Py_ssize_t)INT_MAX) {
2019 PyErr_Format(PyExc_ValueError,
2020 "password cannot be longer than %d bytes", INT_MAX);
2021 goto error;
2022 }
2023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002024 free(pw_info->password);
2025 pw_info->password = malloc(size);
2026 if (!pw_info->password) {
2027 PyErr_SetString(PyExc_MemoryError,
2028 "unable to allocate password buffer");
2029 goto error;
2030 }
2031 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002032 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002033
2034 Py_XDECREF(password_bytes);
2035 return 1;
2036
2037error:
2038 Py_XDECREF(password_bytes);
2039 return 0;
2040}
2041
2042static int
2043_password_callback(char *buf, int size, int rwflag, void *userdata)
2044{
2045 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2046 PyObject *fn_ret = NULL;
2047
2048 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2049
2050 if (pw_info->callable) {
2051 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2052 if (!fn_ret) {
2053 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2054 core python API, so we could use it to add a frame here */
2055 goto error;
2056 }
2057
2058 if (!_pwinfo_set(pw_info, fn_ret,
2059 "password callback must return a string")) {
2060 goto error;
2061 }
2062 Py_CLEAR(fn_ret);
2063 }
2064
2065 if (pw_info->size > size) {
2066 PyErr_Format(PyExc_ValueError,
2067 "password cannot be longer than %d bytes", size);
2068 goto error;
2069 }
2070
2071 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2072 memcpy(buf, pw_info->password, pw_info->size);
2073 return pw_info->size;
2074
2075error:
2076 Py_XDECREF(fn_ret);
2077 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2078 pw_info->error = 1;
2079 return -1;
2080}
2081
Antoine Pitroub5218772010-05-21 09:56:06 +00002082static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002083load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2084{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002085 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2086 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002087 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002088 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2089 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2090 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002091 int r;
2092
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002093 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002094 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002095 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002096 "O|OO:load_cert_chain", kwlist,
2097 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002098 return NULL;
2099 if (keyfile == Py_None)
2100 keyfile = NULL;
2101 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2102 PyErr_SetString(PyExc_TypeError,
2103 "certfile should be a valid filesystem path");
2104 return NULL;
2105 }
2106 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2107 PyErr_SetString(PyExc_TypeError,
2108 "keyfile should be a valid filesystem path");
2109 goto error;
2110 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002111 if (password && password != Py_None) {
2112 if (PyCallable_Check(password)) {
2113 pw_info.callable = password;
2114 } else if (!_pwinfo_set(&pw_info, password,
2115 "password should be a string or callable")) {
2116 goto error;
2117 }
2118 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2119 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2120 }
2121 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002122 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2123 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002124 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002125 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002126 if (pw_info.error) {
2127 ERR_clear_error();
2128 /* the password callback has already set the error information */
2129 }
2130 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002131 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002132 PyErr_SetFromErrno(PyExc_IOError);
2133 }
2134 else {
2135 _setSSLError(NULL, 0, __FILE__, __LINE__);
2136 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002137 goto error;
2138 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002139 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002140 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002141 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2142 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002143 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2144 Py_CLEAR(keyfile_bytes);
2145 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002146 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002147 if (pw_info.error) {
2148 ERR_clear_error();
2149 /* the password callback has already set the error information */
2150 }
2151 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002152 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002153 PyErr_SetFromErrno(PyExc_IOError);
2154 }
2155 else {
2156 _setSSLError(NULL, 0, __FILE__, __LINE__);
2157 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002158 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002159 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002160 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002161 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002162 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002163 if (r != 1) {
2164 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002165 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002166 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002167 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2168 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2169 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002170 Py_RETURN_NONE;
2171
2172error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002173 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2174 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2175 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002176 Py_XDECREF(keyfile_bytes);
2177 Py_XDECREF(certfile_bytes);
2178 return NULL;
2179}
2180
2181static PyObject *
2182load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2183{
2184 char *kwlist[] = {"cafile", "capath", NULL};
2185 PyObject *cafile = NULL, *capath = NULL;
2186 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2187 const char *cafile_buf = NULL, *capath_buf = NULL;
2188 int r;
2189
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002190 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002191 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2192 "|OO:load_verify_locations", kwlist,
2193 &cafile, &capath))
2194 return NULL;
2195 if (cafile == Py_None)
2196 cafile = NULL;
2197 if (capath == Py_None)
2198 capath = NULL;
2199 if (cafile == NULL && capath == NULL) {
2200 PyErr_SetString(PyExc_TypeError,
2201 "cafile and capath cannot be both omitted");
2202 return NULL;
2203 }
2204 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2205 PyErr_SetString(PyExc_TypeError,
2206 "cafile should be a valid filesystem path");
2207 return NULL;
2208 }
2209 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002210 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 PyErr_SetString(PyExc_TypeError,
2212 "capath should be a valid filesystem path");
2213 return NULL;
2214 }
2215 if (cafile)
2216 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2217 if (capath)
2218 capath_buf = PyBytes_AS_STRING(capath_bytes);
2219 PySSL_BEGIN_ALLOW_THREADS
2220 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2221 PySSL_END_ALLOW_THREADS
2222 Py_XDECREF(cafile_bytes);
2223 Py_XDECREF(capath_bytes);
2224 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002225 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002226 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002227 PyErr_SetFromErrno(PyExc_IOError);
2228 }
2229 else {
2230 _setSSLError(NULL, 0, __FILE__, __LINE__);
2231 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232 return NULL;
2233 }
2234 Py_RETURN_NONE;
2235}
2236
2237static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002238load_dh_params(PySSLContext *self, PyObject *filepath)
2239{
2240 FILE *f;
2241 DH *dh;
2242
2243 f = _Py_fopen(filepath, "rb");
2244 if (f == NULL) {
2245 if (!PyErr_Occurred())
2246 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2247 return NULL;
2248 }
2249 errno = 0;
2250 PySSL_BEGIN_ALLOW_THREADS
2251 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002252 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002253 PySSL_END_ALLOW_THREADS
2254 if (dh == NULL) {
2255 if (errno != 0) {
2256 ERR_clear_error();
2257 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2258 }
2259 else {
2260 _setSSLError(NULL, 0, __FILE__, __LINE__);
2261 }
2262 return NULL;
2263 }
2264 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2265 _setSSLError(NULL, 0, __FILE__, __LINE__);
2266 DH_free(dh);
2267 Py_RETURN_NONE;
2268}
2269
2270static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002271context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2272{
Antoine Pitroud5323212010-10-22 18:19:07 +00002273 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002274 PySocketSockObject *sock;
2275 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002276 char *hostname = NULL;
2277 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002278
Antoine Pitroud5323212010-10-22 18:19:07 +00002279 /* server_hostname is either None (or absent), or to be encoded
2280 using the idna encoding. */
2281 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002282 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002283 &sock, &server_side,
2284 Py_TYPE(Py_None), &hostname_obj)) {
2285 PyErr_Clear();
2286 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2287 PySocketModule.Sock_Type,
2288 &sock, &server_side,
2289 "idna", &hostname))
2290 return NULL;
2291#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2292 PyMem_Free(hostname);
2293 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2294 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002295 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002296#endif
2297 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002298
Antoine Pitroud5323212010-10-22 18:19:07 +00002299 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2300 hostname);
2301 if (hostname != NULL)
2302 PyMem_Free(hostname);
2303 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002304}
2305
Antoine Pitroub0182c82010-10-12 20:09:02 +00002306static PyObject *
2307session_stats(PySSLContext *self, PyObject *unused)
2308{
2309 int r;
2310 PyObject *value, *stats = PyDict_New();
2311 if (!stats)
2312 return NULL;
2313
2314#define ADD_STATS(SSL_NAME, KEY_NAME) \
2315 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2316 if (value == NULL) \
2317 goto error; \
2318 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2319 Py_DECREF(value); \
2320 if (r < 0) \
2321 goto error;
2322
2323 ADD_STATS(number, "number");
2324 ADD_STATS(connect, "connect");
2325 ADD_STATS(connect_good, "connect_good");
2326 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2327 ADD_STATS(accept, "accept");
2328 ADD_STATS(accept_good, "accept_good");
2329 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2330 ADD_STATS(accept, "accept");
2331 ADD_STATS(hits, "hits");
2332 ADD_STATS(misses, "misses");
2333 ADD_STATS(timeouts, "timeouts");
2334 ADD_STATS(cache_full, "cache_full");
2335
2336#undef ADD_STATS
2337
2338 return stats;
2339
2340error:
2341 Py_DECREF(stats);
2342 return NULL;
2343}
2344
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002345static PyObject *
2346set_default_verify_paths(PySSLContext *self, PyObject *unused)
2347{
2348 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2349 _setSSLError(NULL, 0, __FILE__, __LINE__);
2350 return NULL;
2351 }
2352 Py_RETURN_NONE;
2353}
2354
Antoine Pitrou501da612011-12-21 09:27:41 +01002355#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002356static PyObject *
2357set_ecdh_curve(PySSLContext *self, PyObject *name)
2358{
2359 PyObject *name_bytes;
2360 int nid;
2361 EC_KEY *key;
2362
2363 if (!PyUnicode_FSConverter(name, &name_bytes))
2364 return NULL;
2365 assert(PyBytes_Check(name_bytes));
2366 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2367 Py_DECREF(name_bytes);
2368 if (nid == 0) {
2369 PyErr_Format(PyExc_ValueError,
2370 "unknown elliptic curve name %R", name);
2371 return NULL;
2372 }
2373 key = EC_KEY_new_by_curve_name(nid);
2374 if (key == NULL) {
2375 _setSSLError(NULL, 0, __FILE__, __LINE__);
2376 return NULL;
2377 }
2378 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2379 EC_KEY_free(key);
2380 Py_RETURN_NONE;
2381}
Antoine Pitrou501da612011-12-21 09:27:41 +01002382#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002383
Antoine Pitrou152efa22010-05-16 18:19:27 +00002384static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002385 {"options", (getter) get_options,
2386 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002387 {"verify_mode", (getter) get_verify_mode,
2388 (setter) set_verify_mode, NULL},
2389 {NULL}, /* sentinel */
2390};
2391
2392static struct PyMethodDef context_methods[] = {
2393 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2394 METH_VARARGS | METH_KEYWORDS, NULL},
2395 {"set_ciphers", (PyCFunction) set_ciphers,
2396 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002397 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2398 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002399 {"load_cert_chain", (PyCFunction) load_cert_chain,
2400 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002401 {"load_dh_params", (PyCFunction) load_dh_params,
2402 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002403 {"load_verify_locations", (PyCFunction) load_verify_locations,
2404 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002405 {"session_stats", (PyCFunction) session_stats,
2406 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002407 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2408 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002409#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002410 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2411 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002412#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002413 {NULL, NULL} /* sentinel */
2414};
2415
2416static PyTypeObject PySSLContext_Type = {
2417 PyVarObject_HEAD_INIT(NULL, 0)
2418 "_ssl._SSLContext", /*tp_name*/
2419 sizeof(PySSLContext), /*tp_basicsize*/
2420 0, /*tp_itemsize*/
2421 (destructor)context_dealloc, /*tp_dealloc*/
2422 0, /*tp_print*/
2423 0, /*tp_getattr*/
2424 0, /*tp_setattr*/
2425 0, /*tp_reserved*/
2426 0, /*tp_repr*/
2427 0, /*tp_as_number*/
2428 0, /*tp_as_sequence*/
2429 0, /*tp_as_mapping*/
2430 0, /*tp_hash*/
2431 0, /*tp_call*/
2432 0, /*tp_str*/
2433 0, /*tp_getattro*/
2434 0, /*tp_setattro*/
2435 0, /*tp_as_buffer*/
2436 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2437 0, /*tp_doc*/
2438 0, /*tp_traverse*/
2439 0, /*tp_clear*/
2440 0, /*tp_richcompare*/
2441 0, /*tp_weaklistoffset*/
2442 0, /*tp_iter*/
2443 0, /*tp_iternext*/
2444 context_methods, /*tp_methods*/
2445 0, /*tp_members*/
2446 context_getsetlist, /*tp_getset*/
2447 0, /*tp_base*/
2448 0, /*tp_dict*/
2449 0, /*tp_descr_get*/
2450 0, /*tp_descr_set*/
2451 0, /*tp_dictoffset*/
2452 0, /*tp_init*/
2453 0, /*tp_alloc*/
2454 context_new, /*tp_new*/
2455};
2456
2457
2458
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002459#ifdef HAVE_OPENSSL_RAND
2460
2461/* helper routines for seeding the SSL PRNG */
2462static PyObject *
2463PySSL_RAND_add(PyObject *self, PyObject *args)
2464{
2465 char *buf;
2466 int len;
2467 double entropy;
2468
2469 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002470 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002471 RAND_add(buf, len, entropy);
2472 Py_INCREF(Py_None);
2473 return Py_None;
2474}
2475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002476PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002477"RAND_add(string, entropy)\n\
2478\n\
2479Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002480bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002481
2482static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002483PySSL_RAND(int len, int pseudo)
2484{
2485 int ok;
2486 PyObject *bytes;
2487 unsigned long err;
2488 const char *errstr;
2489 PyObject *v;
2490
2491 bytes = PyBytes_FromStringAndSize(NULL, len);
2492 if (bytes == NULL)
2493 return NULL;
2494 if (pseudo) {
2495 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2496 if (ok == 0 || ok == 1)
2497 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2498 }
2499 else {
2500 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2501 if (ok == 1)
2502 return bytes;
2503 }
2504 Py_DECREF(bytes);
2505
2506 err = ERR_get_error();
2507 errstr = ERR_reason_error_string(err);
2508 v = Py_BuildValue("(ks)", err, errstr);
2509 if (v != NULL) {
2510 PyErr_SetObject(PySSLErrorObject, v);
2511 Py_DECREF(v);
2512 }
2513 return NULL;
2514}
2515
2516static PyObject *
2517PySSL_RAND_bytes(PyObject *self, PyObject *args)
2518{
2519 int len;
2520 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2521 return NULL;
2522 return PySSL_RAND(len, 0);
2523}
2524
2525PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2526"RAND_bytes(n) -> bytes\n\
2527\n\
2528Generate n cryptographically strong pseudo-random bytes.");
2529
2530static PyObject *
2531PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2532{
2533 int len;
2534 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2535 return NULL;
2536 return PySSL_RAND(len, 1);
2537}
2538
2539PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2540"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2541\n\
2542Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2543generated are cryptographically strong.");
2544
2545static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002546PySSL_RAND_status(PyObject *self)
2547{
Christian Heimes217cfd12007-12-02 14:31:20 +00002548 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002549}
2550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002551PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002552"RAND_status() -> 0 or 1\n\
2553\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002554Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2555It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2556using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002557
2558static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002559PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002560{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002561 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002562 int bytes;
2563
Jesus Ceac8754a12012-09-11 02:00:58 +02002564 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002565 PyUnicode_FSConverter, &path))
2566 return NULL;
2567
2568 bytes = RAND_egd(PyBytes_AsString(path));
2569 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002570 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002571 PyErr_SetString(PySSLErrorObject,
2572 "EGD connection failed or EGD did not return "
2573 "enough data to seed the PRNG");
2574 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002575 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002576 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002577}
2578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002579PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002580"RAND_egd(path) -> bytes\n\
2581\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002582Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2583Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002584fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002585
Christian Heimesf77b4b22013-08-21 13:26:05 +02002586/* Seed OpenSSL's PRNG at fork(), http://bugs.python.org/issue18747
2587 *
Christian Heimes80c5de92013-08-22 13:19:48 +02002588 * The parent handler seeds the PRNG from pseudo-random data like pid, the
Christian Heimes61636e72013-08-25 14:19:16 +02002589 * current time (miliseconds or seconds) and an uninitialized array.
Christian Heimes80c5de92013-08-22 13:19:48 +02002590 * The array contains stack variables that are impossible to predict
Christian Heimesf77b4b22013-08-21 13:26:05 +02002591 * on most systems, e.g. function return address (subject to ASLR), the
2592 * stack protection canary and automatic variables.
2593 * The code is inspired by Apache's ssl_rand_seed() function.
2594 *
2595 * Note:
2596 * The code uses pthread_atfork() until Python has a proper atfork API. The
Christian Heimes80c5de92013-08-22 13:19:48 +02002597 * handlers are not removed from the child process. A parent handler is used
Christian Heimes61636e72013-08-25 14:19:16 +02002598 * instead of a child handler because fork() is supposed to be async-signal
Christian Heimes80c5de92013-08-22 13:19:48 +02002599 * safe but the handler calls unsafe functions.
Christian Heimesf77b4b22013-08-21 13:26:05 +02002600 */
2601
2602#if defined(HAVE_PTHREAD_ATFORK) && defined(WITH_THREAD)
2603#define PYSSL_RAND_ATFORK 1
2604
2605static void
Christian Heimes80c5de92013-08-22 13:19:48 +02002606PySSL_RAND_atfork_parent(void)
Christian Heimesf77b4b22013-08-21 13:26:05 +02002607{
2608 struct {
2609 char stack[128]; /* uninitialized (!) stack data, 128 is an
2610 arbitrary number. */
2611 pid_t pid; /* current pid */
2612 _PyTime_timeval tp; /* current time */
2613 } seed;
2614
2615#ifdef WITH_VALGRIND
2616 VALGRIND_MAKE_MEM_DEFINED(seed.stack, sizeof(seed.stack));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002617#endif
Christian Heimesf77b4b22013-08-21 13:26:05 +02002618 seed.pid = getpid();
2619 _PyTime_gettimeofday(&(seed.tp));
Christian Heimesf77b4b22013-08-21 13:26:05 +02002620 RAND_add((unsigned char *)&seed, sizeof(seed), 0.0);
2621}
2622
2623static int
2624PySSL_RAND_atfork(void)
2625{
2626 static int registered = 0;
2627 int retval;
2628
2629 if (registered)
2630 return 0;
2631
2632 retval = pthread_atfork(NULL, /* prepare */
Christian Heimes80c5de92013-08-22 13:19:48 +02002633 PySSL_RAND_atfork_parent, /* parent */
2634 NULL); /* child */
Christian Heimesf77b4b22013-08-21 13:26:05 +02002635 if (retval != 0) {
2636 PyErr_SetFromErrno(PyExc_OSError);
2637 return -1;
2638 }
2639 registered = 1;
2640 return 0;
2641}
2642#endif /* HAVE_PTHREAD_ATFORK */
2643
2644#endif /* HAVE_OPENSSL_RAND */
2645
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002646
Bill Janssen40a0f662008-08-12 16:56:25 +00002647
2648
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002649/* List of functions exported by this module. */
2650
2651static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002652 {"_test_decode_cert", PySSL_test_decode_certificate,
2653 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002654#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2656 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002657 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2658 PySSL_RAND_bytes_doc},
2659 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2660 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002661 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002662 PySSL_RAND_egd_doc},
2663 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2664 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002665#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002666 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002667};
2668
2669
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002670#ifdef WITH_THREAD
2671
2672/* an implementation of OpenSSL threading operations in terms
2673 of the Python C thread library */
2674
2675static PyThread_type_lock *_ssl_locks = NULL;
2676
Christian Heimes4d98ca92013-08-19 17:36:29 +02002677#if OPENSSL_VERSION_NUMBER >= 0x10000000
2678/* use new CRYPTO_THREADID API. */
2679static void
2680_ssl_threadid_callback(CRYPTO_THREADID *id)
2681{
2682 CRYPTO_THREADID_set_numeric(id,
2683 (unsigned long)PyThread_get_thread_ident());
2684}
2685#else
2686/* deprecated CRYPTO_set_id_callback() API. */
2687static unsigned long
2688_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002690}
Christian Heimes4d98ca92013-08-19 17:36:29 +02002691#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002692
Bill Janssen6e027db2007-11-15 22:23:56 +00002693static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002694 (int mode, int n, const char *file, int line) {
2695 /* this function is needed to perform locking on shared data
2696 structures. (Note that OpenSSL uses a number of global data
2697 structures that will be implicitly shared whenever multiple
2698 threads use OpenSSL.) Multi-threaded applications will
2699 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002701 locking_function() must be able to handle up to
2702 CRYPTO_num_locks() different mutex locks. It sets the n-th
2703 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002705 file and line are the file number of the function setting the
2706 lock. They can be useful for debugging.
2707 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 if ((_ssl_locks == NULL) ||
2710 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2711 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002713 if (mode & CRYPTO_LOCK) {
2714 PyThread_acquire_lock(_ssl_locks[n], 1);
2715 } else {
2716 PyThread_release_lock(_ssl_locks[n]);
2717 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002718}
2719
2720static int _setup_ssl_threads(void) {
2721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002722 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002724 if (_ssl_locks == NULL) {
2725 _ssl_locks_count = CRYPTO_num_locks();
2726 _ssl_locks = (PyThread_type_lock *)
2727 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2728 if (_ssl_locks == NULL)
2729 return 0;
2730 memset(_ssl_locks, 0,
2731 sizeof(PyThread_type_lock) * _ssl_locks_count);
2732 for (i = 0; i < _ssl_locks_count; i++) {
2733 _ssl_locks[i] = PyThread_allocate_lock();
2734 if (_ssl_locks[i] == NULL) {
2735 unsigned int j;
2736 for (j = 0; j < i; j++) {
2737 PyThread_free_lock(_ssl_locks[j]);
2738 }
2739 free(_ssl_locks);
2740 return 0;
2741 }
2742 }
2743 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002744#if OPENSSL_VERSION_NUMBER >= 0x10000000
2745 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
2746#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002747 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002748#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002749 }
2750 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002751}
2752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002753#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002755PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002756"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002757for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002758
Martin v. Löwis1a214512008-06-11 05:26:20 +00002759
2760static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002761 PyModuleDef_HEAD_INIT,
2762 "_ssl",
2763 module_doc,
2764 -1,
2765 PySSL_methods,
2766 NULL,
2767 NULL,
2768 NULL,
2769 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002770};
2771
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002772
2773static void
2774parse_openssl_version(unsigned long libver,
2775 unsigned int *major, unsigned int *minor,
2776 unsigned int *fix, unsigned int *patch,
2777 unsigned int *status)
2778{
2779 *status = libver & 0xF;
2780 libver >>= 4;
2781 *patch = libver & 0xFF;
2782 libver >>= 8;
2783 *fix = libver & 0xFF;
2784 libver >>= 8;
2785 *minor = libver & 0xFF;
2786 libver >>= 8;
2787 *major = libver & 0xFF;
2788}
2789
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002790PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002791PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002792{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002793 PyObject *m, *d, *r;
2794 unsigned long libver;
2795 unsigned int major, minor, fix, patch, status;
2796 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002797 struct py_ssl_error_code *errcode;
2798 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002799
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800 if (PyType_Ready(&PySSLContext_Type) < 0)
2801 return NULL;
2802 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002803 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002805 m = PyModule_Create(&_sslmodule);
2806 if (m == NULL)
2807 return NULL;
2808 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002810 /* Load _socket module and its C API */
2811 socket_api = PySocketModule_ImportModuleAndAPI();
2812 if (!socket_api)
2813 return NULL;
2814 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002816 /* Init OpenSSL */
2817 SSL_load_error_strings();
2818 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002820 /* note that this will start threading if not already started */
2821 if (!_setup_ssl_threads()) {
2822 return NULL;
2823 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002824#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002825 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002827 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002828 sslerror_type_slots[0].pfunc = PyExc_OSError;
2829 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002830 if (PySSLErrorObject == NULL)
2831 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002832
Antoine Pitrou41032a62011-10-27 23:56:55 +02002833 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2834 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2835 PySSLErrorObject, NULL);
2836 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2837 "ssl.SSLWantReadError", SSLWantReadError_doc,
2838 PySSLErrorObject, NULL);
2839 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2840 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2841 PySSLErrorObject, NULL);
2842 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2843 "ssl.SSLSyscallError", SSLSyscallError_doc,
2844 PySSLErrorObject, NULL);
2845 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2846 "ssl.SSLEOFError", SSLEOFError_doc,
2847 PySSLErrorObject, NULL);
2848 if (PySSLZeroReturnErrorObject == NULL
2849 || PySSLWantReadErrorObject == NULL
2850 || PySSLWantWriteErrorObject == NULL
2851 || PySSLSyscallErrorObject == NULL
2852 || PySSLEOFErrorObject == NULL)
2853 return NULL;
2854 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2855 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2856 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2857 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2858 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2859 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002860 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002861 if (PyDict_SetItemString(d, "_SSLContext",
2862 (PyObject *)&PySSLContext_Type) != 0)
2863 return NULL;
2864 if (PyDict_SetItemString(d, "_SSLSocket",
2865 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002866 return NULL;
2867 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2868 PY_SSL_ERROR_ZERO_RETURN);
2869 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2870 PY_SSL_ERROR_WANT_READ);
2871 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2872 PY_SSL_ERROR_WANT_WRITE);
2873 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2874 PY_SSL_ERROR_WANT_X509_LOOKUP);
2875 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2876 PY_SSL_ERROR_SYSCALL);
2877 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2878 PY_SSL_ERROR_SSL);
2879 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2880 PY_SSL_ERROR_WANT_CONNECT);
2881 /* non ssl.h errorcodes */
2882 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2883 PY_SSL_ERROR_EOF);
2884 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2885 PY_SSL_ERROR_INVALID_ERROR_CODE);
2886 /* cert requirements */
2887 PyModule_AddIntConstant(m, "CERT_NONE",
2888 PY_SSL_CERT_NONE);
2889 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2890 PY_SSL_CERT_OPTIONAL);
2891 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2892 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002894 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002895#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002896 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2897 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002898#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002899 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2900 PY_SSL_VERSION_SSL3);
2901 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2902 PY_SSL_VERSION_SSL23);
2903 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2904 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002905
Antoine Pitroub5218772010-05-21 09:56:06 +00002906 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002907 PyModule_AddIntConstant(m, "OP_ALL",
2908 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002909 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2910 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2911 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002912 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2913 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002914 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002915#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002916 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002917#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002918#ifdef SSL_OP_NO_COMPRESSION
2919 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2920 SSL_OP_NO_COMPRESSION);
2921#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002922
Antoine Pitroud5323212010-10-22 18:19:07 +00002923#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2924 r = Py_True;
2925#else
2926 r = Py_False;
2927#endif
2928 Py_INCREF(r);
2929 PyModule_AddObject(m, "HAS_SNI", r);
2930
Antoine Pitroud6494802011-07-21 01:11:30 +02002931#if HAVE_OPENSSL_FINISHED
2932 r = Py_True;
2933#else
2934 r = Py_False;
2935#endif
2936 Py_INCREF(r);
2937 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2938
Antoine Pitrou501da612011-12-21 09:27:41 +01002939#ifdef OPENSSL_NO_ECDH
2940 r = Py_False;
2941#else
2942 r = Py_True;
2943#endif
2944 Py_INCREF(r);
2945 PyModule_AddObject(m, "HAS_ECDH", r);
2946
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002947#ifdef OPENSSL_NPN_NEGOTIATED
2948 r = Py_True;
2949#else
2950 r = Py_False;
2951#endif
2952 Py_INCREF(r);
2953 PyModule_AddObject(m, "HAS_NPN", r);
2954
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002955 /* Mappings for error codes */
2956 err_codes_to_names = PyDict_New();
2957 err_names_to_codes = PyDict_New();
2958 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2959 return NULL;
2960 errcode = error_codes;
2961 while (errcode->mnemonic != NULL) {
2962 PyObject *mnemo, *key;
2963 mnemo = PyUnicode_FromString(errcode->mnemonic);
2964 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2965 if (mnemo == NULL || key == NULL)
2966 return NULL;
2967 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2968 return NULL;
2969 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2970 return NULL;
2971 Py_DECREF(key);
2972 Py_DECREF(mnemo);
2973 errcode++;
2974 }
2975 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2976 return NULL;
2977 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2978 return NULL;
2979
2980 lib_codes_to_names = PyDict_New();
2981 if (lib_codes_to_names == NULL)
2982 return NULL;
2983 libcode = library_codes;
2984 while (libcode->library != NULL) {
2985 PyObject *mnemo, *key;
2986 key = PyLong_FromLong(libcode->code);
2987 mnemo = PyUnicode_FromString(libcode->library);
2988 if (key == NULL || mnemo == NULL)
2989 return NULL;
2990 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2991 return NULL;
2992 Py_DECREF(key);
2993 Py_DECREF(mnemo);
2994 libcode++;
2995 }
2996 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2997 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002999 /* OpenSSL version */
3000 /* SSLeay() gives us the version of the library linked against,
3001 which could be different from the headers version.
3002 */
3003 libver = SSLeay();
3004 r = PyLong_FromUnsignedLong(libver);
3005 if (r == NULL)
3006 return NULL;
3007 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3008 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003009 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003010 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3011 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3012 return NULL;
3013 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3014 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3015 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003016
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003017 libver = OPENSSL_VERSION_NUMBER;
3018 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3019 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3020 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3021 return NULL;
3022
Christian Heimesf77b4b22013-08-21 13:26:05 +02003023#ifdef PYSSL_RAND_ATFORK
3024 if (PySSL_RAND_atfork() == -1)
3025 return NULL;
3026#endif
3027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003028 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003029}