blob: c9c556e83234bfe497483db3d6405bfcd6edeb05 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +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
Benjamin Petersondaeb9252014-08-20 14:14:50 -050017#define PY_SSIZE_T_CLEAN
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000018#include "Python.h"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000019
Bill Janssen98d19da2007-09-10 21:51:02 +000020#ifdef WITH_THREAD
21#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020022
Christian Heimes0d604cf2013-08-21 13:26:05 +020023
Benjamin Petersondaeb9252014-08-20 14:14:50 -050024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Bill Janssen98d19da2007-09-10 21:51:02 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000029 PyThreadState *_save = NULL; \
Benjamin Petersondaeb9252014-08-20 14:14:50 -050030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Bill Janssen98d19da2007-09-10 21:51:02 +000034
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000035#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000036
Benjamin Petersondaeb9252014-08-20 14:14:50 -050037#define PySSL_BEGIN_ALLOW_THREADS_S(save)
38#define PySSL_END_ALLOW_THREADS_S(save)
Bill Janssen98d19da2007-09-10 21:51:02 +000039#define PySSL_BEGIN_ALLOW_THREADS
40#define PySSL_BLOCK_THREADS
41#define PySSL_UNBLOCK_THREADS
42#define PySSL_END_ALLOW_THREADS
43
44#endif
45
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000046/* Include symbols from _socket module */
47#include "socketmodule.h"
48
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000049#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000050#include <poll.h>
51#elif defined(HAVE_SYS_POLL_H)
52#include <sys/poll.h>
53#endif
54
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000055/* Include OpenSSL header files */
56#include "openssl/rsa.h"
57#include "openssl/crypto.h"
58#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000059#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000060#include "openssl/pem.h"
61#include "openssl/ssl.h"
62#include "openssl/err.h"
63#include "openssl/rand.h"
64
65/* SSL error object */
66static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050067static PyObject *PySSLZeroReturnErrorObject;
68static PyObject *PySSLWantReadErrorObject;
69static PyObject *PySSLWantWriteErrorObject;
70static PyObject *PySSLSyscallErrorObject;
71static PyObject *PySSLEOFErrorObject;
72
73/* Error mappings */
74static PyObject *err_codes_to_names;
75static PyObject *err_names_to_codes;
76static PyObject *lib_codes_to_names;
77
78struct py_ssl_error_code {
79 const char *mnemonic;
80 int library, reason;
81};
82struct py_ssl_library_code {
83 const char *library;
84 int code;
85};
86
87/* Include generated data (error codes) */
88#include "_ssl_data.h"
89
90/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
91 http://www.openssl.org/news/changelog.html
92 */
93#if OPENSSL_VERSION_NUMBER >= 0x10001000L
94# define HAVE_TLSv1_2 1
95#else
96# define HAVE_TLSv1_2 0
97#endif
98
99/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
100 * This includes the SSL_set_SSL_CTX() function.
101 */
102#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
103# define HAVE_SNI 1
104#else
105# define HAVE_SNI 0
106#endif
107
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500108/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500109#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500110# define HAVE_ALPN
111#endif
112
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500113enum py_ssl_error {
114 /* these mirror ssl.h */
115 PY_SSL_ERROR_NONE,
116 PY_SSL_ERROR_SSL,
117 PY_SSL_ERROR_WANT_READ,
118 PY_SSL_ERROR_WANT_WRITE,
119 PY_SSL_ERROR_WANT_X509_LOOKUP,
120 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
121 PY_SSL_ERROR_ZERO_RETURN,
122 PY_SSL_ERROR_WANT_CONNECT,
123 /* start of non ssl.h errorcodes */
124 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
125 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
126 PY_SSL_ERROR_INVALID_ERROR_CODE
127};
128
129enum py_ssl_server_or_client {
130 PY_SSL_CLIENT,
131 PY_SSL_SERVER
132};
133
134enum py_ssl_cert_requirements {
135 PY_SSL_CERT_NONE,
136 PY_SSL_CERT_OPTIONAL,
137 PY_SSL_CERT_REQUIRED
138};
139
140enum py_ssl_version {
141 PY_SSL_VERSION_SSL2,
142 PY_SSL_VERSION_SSL3=1,
143 PY_SSL_VERSION_SSL23,
144#if HAVE_TLSv1_2
145 PY_SSL_VERSION_TLS1,
146 PY_SSL_VERSION_TLS1_1,
147 PY_SSL_VERSION_TLS1_2
148#else
149 PY_SSL_VERSION_TLS1
150#endif
151};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000152
Bill Janssen98d19da2007-09-10 21:51:02 +0000153#ifdef WITH_THREAD
154
155/* serves as a flag to see whether we've initialized the SSL thread support. */
156/* 0 means no, greater than 0 means yes */
157
158static unsigned int _ssl_locks_count = 0;
159
160#endif /* def WITH_THREAD */
161
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000162/* SSL socket object */
163
164#define X509_NAME_MAXLEN 256
165
166/* RAND_* APIs got added to OpenSSL in 0.9.5 */
167#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
168# define HAVE_OPENSSL_RAND 1
169#else
170# undef HAVE_OPENSSL_RAND
171#endif
172
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500173/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
174 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
175 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
176#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
177# define HAVE_SSL_CTX_CLEAR_OPTIONS
178#else
179# undef HAVE_SSL_CTX_CLEAR_OPTIONS
180#endif
181
182/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
183 * older SSL, but let's be safe */
184#define PySSL_CB_MAXLEN 128
185
186/* SSL_get_finished got added to OpenSSL in 0.9.5 */
187#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
188# define HAVE_OPENSSL_FINISHED 1
189#else
190# define HAVE_OPENSSL_FINISHED 0
191#endif
192
193/* ECDH support got added to OpenSSL in 0.9.8 */
194#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
195# define OPENSSL_NO_ECDH
196#endif
197
198/* compression support got added to OpenSSL in 0.9.8 */
199#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
200# define OPENSSL_NO_COMP
201#endif
202
203/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
204#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
205# define HAVE_OPENSSL_VERIFY_PARAM
206#endif
207
208
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000209typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000210 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500211 SSL_CTX *ctx;
212#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500213 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500214 int npn_protocols_len;
215#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500216#ifdef HAVE_ALPN
217 unsigned char *alpn_protocols;
218 int alpn_protocols_len;
219#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500220#ifndef OPENSSL_NO_TLSEXT
221 PyObject *set_hostname;
222#endif
223 int check_hostname;
224} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500226typedef struct {
227 PyObject_HEAD
228 PySocketSockObject *Socket;
229 PyObject *ssl_sock;
230 SSL *ssl;
231 PySSLContext *ctx; /* weakref to SSL context */
232 X509 *peer_cert;
233 char shutdown_seen_zero;
234 char handshake_done;
235 enum py_ssl_server_or_client socket_type;
236} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500238static PyTypeObject PySSLContext_Type;
239static PyTypeObject PySSLSocket_Type;
240
241static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
242static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000243static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000244 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500245static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
246static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000247
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500248#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
249#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000250
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000251typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000252 SOCKET_IS_NONBLOCKING,
253 SOCKET_IS_BLOCKING,
254 SOCKET_HAS_TIMED_OUT,
255 SOCKET_HAS_BEEN_CLOSED,
256 SOCKET_TOO_LARGE_FOR_SELECT,
257 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000258} timeout_state;
259
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000260/* Wrap error strings with filename and line # */
261#define STRINGIFY1(x) #x
262#define STRINGIFY2(x) STRINGIFY1(x)
263#define ERRSTR1(x,y,z) (x ":" y ": " z)
264#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
265
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500266
267/*
268 * SSL errors.
269 */
270
271PyDoc_STRVAR(SSLError_doc,
272"An error occurred in the SSL implementation.");
273
274PyDoc_STRVAR(SSLZeroReturnError_doc,
275"SSL/TLS session closed cleanly.");
276
277PyDoc_STRVAR(SSLWantReadError_doc,
278"Non-blocking SSL socket needs to read more data\n"
279"before the requested operation can be completed.");
280
281PyDoc_STRVAR(SSLWantWriteError_doc,
282"Non-blocking SSL socket needs to write more data\n"
283"before the requested operation can be completed.");
284
285PyDoc_STRVAR(SSLSyscallError_doc,
286"System error when attempting SSL operation.");
287
288PyDoc_STRVAR(SSLEOFError_doc,
289"SSL/TLS connection terminated abruptly.");
290
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000291
292static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500293SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000294{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500295 if (self->strerror != NULL) {
296 Py_INCREF(self->strerror);
297 return self->strerror;
298 }
299 else
300 return PyObject_Str(self->args);
301}
302
303static void
304fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
305 int lineno, unsigned long errcode)
306{
307 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
308 PyObject *init_value, *msg, *key;
309
310 if (errcode != 0) {
311 int lib, reason;
312
313 lib = ERR_GET_LIB(errcode);
314 reason = ERR_GET_REASON(errcode);
315 key = Py_BuildValue("ii", lib, reason);
316 if (key == NULL)
317 goto fail;
318 reason_obj = PyDict_GetItem(err_codes_to_names, key);
319 Py_DECREF(key);
320 if (reason_obj == NULL) {
321 /* XXX if reason < 100, it might reflect a library number (!!) */
322 PyErr_Clear();
323 }
324 key = PyLong_FromLong(lib);
325 if (key == NULL)
326 goto fail;
327 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
328 Py_DECREF(key);
329 if (lib_obj == NULL) {
330 PyErr_Clear();
331 }
332 if (errstr == NULL)
333 errstr = ERR_reason_error_string(errcode);
334 }
335 if (errstr == NULL)
336 errstr = "unknown error";
337
338 if (reason_obj && lib_obj)
339 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
340 lib_obj, reason_obj, errstr, lineno);
341 else if (lib_obj)
342 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
343 lib_obj, errstr, lineno);
344 else
345 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
346 if (msg == NULL)
347 goto fail;
348
349 init_value = Py_BuildValue("iN", ssl_errno, msg);
350 if (init_value == NULL)
351 goto fail;
352
353 err_value = PyObject_CallObject(type, init_value);
354 Py_DECREF(init_value);
355 if (err_value == NULL)
356 goto fail;
357
358 if (reason_obj == NULL)
359 reason_obj = Py_None;
360 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
361 goto fail;
362 if (lib_obj == NULL)
363 lib_obj = Py_None;
364 if (PyObject_SetAttrString(err_value, "library", lib_obj))
365 goto fail;
366 PyErr_SetObject(type, err_value);
367fail:
368 Py_XDECREF(err_value);
369}
370
371static PyObject *
372PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
373{
374 PyObject *type = PySSLErrorObject;
375 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000376 int err;
377 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500378 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000380 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500381 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000382
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000383 if (obj->ssl != NULL) {
384 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000385
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000386 switch (err) {
387 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500388 errstr = "TLS/SSL connection has been closed (EOF)";
389 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000390 p = PY_SSL_ERROR_ZERO_RETURN;
391 break;
392 case SSL_ERROR_WANT_READ:
393 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500394 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000395 p = PY_SSL_ERROR_WANT_READ;
396 break;
397 case SSL_ERROR_WANT_WRITE:
398 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500399 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000400 errstr = "The operation did not complete (write)";
401 break;
402 case SSL_ERROR_WANT_X509_LOOKUP:
403 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000404 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000405 break;
406 case SSL_ERROR_WANT_CONNECT:
407 p = PY_SSL_ERROR_WANT_CONNECT;
408 errstr = "The operation did not complete (connect)";
409 break;
410 case SSL_ERROR_SYSCALL:
411 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000412 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500413 PySocketSockObject *s = obj->Socket;
414 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000415 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500416 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000417 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000418 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000419 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500420 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000421 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500422 s->errorhandler();
423 Py_DECREF(s);
424 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000425 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000426 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500427 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000428 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000429 }
430 } else {
431 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000432 }
433 break;
434 }
435 case SSL_ERROR_SSL:
436 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000437 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500438 if (e == 0)
439 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000440 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000441 break;
442 }
443 default:
444 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
445 errstr = "Invalid error code";
446 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000447 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500448 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000449 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000450 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451}
452
Bill Janssen98d19da2007-09-10 21:51:02 +0000453static PyObject *
454_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
455
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500456 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000457 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500458 else
459 errcode = 0;
460 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000461 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000462 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000463}
464
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500465/*
466 * SSL objects
467 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000468
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500469static PySSLSocket *
470newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
471 enum py_ssl_server_or_client socket_type,
472 char *server_hostname, PyObject *ssl_sock)
473{
474 PySSLSocket *self;
475 SSL_CTX *ctx = sslctx->ctx;
476 long mode;
477
478 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000479 if (self == NULL)
480 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500481
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000482 self->peer_cert = NULL;
483 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000484 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500485 self->ssl_sock = NULL;
486 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200487 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500488 self->handshake_done = 0;
489 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000490
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000491 /* Make sure the SSL error state is initialized */
492 (void) ERR_get_state();
493 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000494
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000495 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500496 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000497 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500498 SSL_set_app_data(self->ssl,self);
499 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
500 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000501#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500502 mode |= SSL_MODE_AUTO_RETRY;
503#endif
504 SSL_set_mode(self->ssl, mode);
505
506#if HAVE_SNI
507 if (server_hostname != NULL)
508 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000509#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000510
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000511 /* If the socket is in non-blocking mode or timeout mode, set the BIO
512 * to non-blocking mode (blocking is the default)
513 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500514 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000515 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
516 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
517 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000518
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000519 PySSL_BEGIN_ALLOW_THREADS
520 if (socket_type == PY_SSL_CLIENT)
521 SSL_set_connect_state(self->ssl);
522 else
523 SSL_set_accept_state(self->ssl);
524 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000525
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500526 self->socket_type = socket_type;
527 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000528 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400529 if (ssl_sock != Py_None) {
530 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
531 if (self->ssl_sock == NULL) {
532 Py_DECREF(self);
533 return NULL;
534 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500535 }
536 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000537}
538
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000539
540/* SSL object methods */
541
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500542static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000543{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000544 int ret;
545 int err;
546 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500547 PySocketSockObject *sock = self->Socket;
548
549 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000550
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000551 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000553 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
554 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000555
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000556 /* Actually negotiate SSL connection */
557 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
558 do {
559 PySSL_BEGIN_ALLOW_THREADS
560 ret = SSL_do_handshake(self->ssl);
561 err = SSL_get_error(self->ssl, ret);
562 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500563 if (PyErr_CheckSignals())
564 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000565 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500566 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000567 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500568 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000569 } else {
570 sockstate = SOCKET_OPERATION_OK;
571 }
572 if (sockstate == SOCKET_HAS_TIMED_OUT) {
573 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000574 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500575 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000576 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
577 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000578 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500579 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000580 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
581 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000582 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500583 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000584 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
585 break;
586 }
587 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500588 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000589 if (ret < 1)
590 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000591
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000592 if (self->peer_cert)
593 X509_free (self->peer_cert);
594 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500595 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000596 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500597 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 Py_INCREF(Py_None);
600 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000601
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500602error:
603 Py_DECREF(sock);
604 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000605}
606
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000607static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000608_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000609
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000610 char namebuf[X509_NAME_MAXLEN];
611 int buflen;
612 PyObject *name_obj;
613 PyObject *value_obj;
614 PyObject *attr;
615 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000616
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000617 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
618 if (buflen < 0) {
619 _setSSLError(NULL, 0, __FILE__, __LINE__);
620 goto fail;
621 }
622 name_obj = PyString_FromStringAndSize(namebuf, buflen);
623 if (name_obj == NULL)
624 goto fail;
625
626 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
627 if (buflen < 0) {
628 _setSSLError(NULL, 0, __FILE__, __LINE__);
629 Py_DECREF(name_obj);
630 goto fail;
631 }
632 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000633 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000634 OPENSSL_free(valuebuf);
635 if (value_obj == NULL) {
636 Py_DECREF(name_obj);
637 goto fail;
638 }
639 attr = PyTuple_New(2);
640 if (attr == NULL) {
641 Py_DECREF(name_obj);
642 Py_DECREF(value_obj);
643 goto fail;
644 }
645 PyTuple_SET_ITEM(attr, 0, name_obj);
646 PyTuple_SET_ITEM(attr, 1, value_obj);
647 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000648
Bill Janssen98d19da2007-09-10 21:51:02 +0000649 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000650 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000651}
652
653static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000654_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000655{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000656 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
657 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
658 PyObject *rdnt;
659 PyObject *attr = NULL; /* tuple to hold an attribute */
660 int entry_count = X509_NAME_entry_count(xname);
661 X509_NAME_ENTRY *entry;
662 ASN1_OBJECT *name;
663 ASN1_STRING *value;
664 int index_counter;
665 int rdn_level = -1;
666 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000667
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000668 dn = PyList_New(0);
669 if (dn == NULL)
670 return NULL;
671 /* now create another tuple to hold the top-level RDN */
672 rdn = PyList_New(0);
673 if (rdn == NULL)
674 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000675
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000676 for (index_counter = 0;
677 index_counter < entry_count;
678 index_counter++)
679 {
680 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000681
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000682 /* check to see if we've gotten to a new RDN */
683 if (rdn_level >= 0) {
684 if (rdn_level != entry->set) {
685 /* yes, new RDN */
686 /* add old RDN to DN */
687 rdnt = PyList_AsTuple(rdn);
688 Py_DECREF(rdn);
689 if (rdnt == NULL)
690 goto fail0;
691 retcode = PyList_Append(dn, rdnt);
692 Py_DECREF(rdnt);
693 if (retcode < 0)
694 goto fail0;
695 /* create new RDN */
696 rdn = PyList_New(0);
697 if (rdn == NULL)
698 goto fail0;
699 }
700 }
701 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000702
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000703 /* now add this attribute to the current RDN */
704 name = X509_NAME_ENTRY_get_object(entry);
705 value = X509_NAME_ENTRY_get_data(entry);
706 attr = _create_tuple_for_attribute(name, value);
707 /*
708 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
709 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500710 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
711 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000712 */
713 if (attr == NULL)
714 goto fail1;
715 retcode = PyList_Append(rdn, attr);
716 Py_DECREF(attr);
717 if (retcode < 0)
718 goto fail1;
719 }
720 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100721 if (rdn != NULL) {
722 if (PyList_GET_SIZE(rdn) > 0) {
723 rdnt = PyList_AsTuple(rdn);
724 Py_DECREF(rdn);
725 if (rdnt == NULL)
726 goto fail0;
727 retcode = PyList_Append(dn, rdnt);
728 Py_DECREF(rdnt);
729 if (retcode < 0)
730 goto fail0;
731 }
732 else {
733 Py_DECREF(rdn);
734 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000735 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000736
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000737 /* convert list to tuple */
738 rdnt = PyList_AsTuple(dn);
739 Py_DECREF(dn);
740 if (rdnt == NULL)
741 return NULL;
742 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
744 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000745 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000746
747 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000748 Py_XDECREF(dn);
749 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000750}
751
752static PyObject *
753_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000754
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000755 /* this code follows the procedure outlined in
756 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
757 function to extract the STACK_OF(GENERAL_NAME),
758 then iterates through the stack to add the
759 names. */
760
761 int i, j;
762 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200763 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000764 X509_EXTENSION *ext = NULL;
765 GENERAL_NAMES *names = NULL;
766 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000767 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000768 BIO *biobuf = NULL;
769 char buf[2048];
770 char *vptr;
771 int len;
772 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000773#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000774 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000775#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000776 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000777#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000778
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000779 if (certificate == NULL)
780 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000781
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000782 /* get a memory buffer */
783 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000784
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200785 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000786 while ((i = X509_get_ext_by_NID(
787 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000788
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000789 if (peer_alt_names == Py_None) {
790 peer_alt_names = PyList_New(0);
791 if (peer_alt_names == NULL)
792 goto fail;
793 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000794
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000795 /* now decode the altName */
796 ext = X509_get_ext(certificate, i);
797 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500798 PyErr_SetString
799 (PySSLErrorObject,
800 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000801 goto fail;
802 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000803
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000804 p = ext->value->data;
805 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500806 names = (GENERAL_NAMES*)
807 (ASN1_item_d2i(NULL,
808 &p,
809 ext->value->length,
810 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000811 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500812 names = (GENERAL_NAMES*)
813 (method->d2i(NULL,
814 &p,
815 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000816
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000817 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000818 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200819 int gntype;
820 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000822 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200823 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200824 switch (gntype) {
825 case GEN_DIRNAME:
826 /* we special-case DirName as a tuple of
827 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000828
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000829 t = PyTuple_New(2);
830 if (t == NULL) {
831 goto fail;
832 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000833
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000834 v = PyString_FromString("DirName");
835 if (v == NULL) {
836 Py_DECREF(t);
837 goto fail;
838 }
839 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000840
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000841 v = _create_tuple_for_X509_NAME (name->d.dirn);
842 if (v == NULL) {
843 Py_DECREF(t);
844 goto fail;
845 }
846 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200847 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000848
Christian Heimes88b174c2013-08-17 00:54:47 +0200849 case GEN_EMAIL:
850 case GEN_DNS:
851 case GEN_URI:
852 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
853 correctly, CVE-2013-4238 */
854 t = PyTuple_New(2);
855 if (t == NULL)
856 goto fail;
857 switch (gntype) {
858 case GEN_EMAIL:
859 v = PyString_FromString("email");
860 as = name->d.rfc822Name;
861 break;
862 case GEN_DNS:
863 v = PyString_FromString("DNS");
864 as = name->d.dNSName;
865 break;
866 case GEN_URI:
867 v = PyString_FromString("URI");
868 as = name->d.uniformResourceIdentifier;
869 break;
870 }
871 if (v == NULL) {
872 Py_DECREF(t);
873 goto fail;
874 }
875 PyTuple_SET_ITEM(t, 0, v);
876 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
877 ASN1_STRING_length(as));
878 if (v == NULL) {
879 Py_DECREF(t);
880 goto fail;
881 }
882 PyTuple_SET_ITEM(t, 1, v);
883 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000884
Christian Heimes88b174c2013-08-17 00:54:47 +0200885 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000886 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200887 switch (gntype) {
888 /* check for new general name type */
889 case GEN_OTHERNAME:
890 case GEN_X400:
891 case GEN_EDIPARTY:
892 case GEN_IPADD:
893 case GEN_RID:
894 break;
895 default:
896 if (PyErr_Warn(PyExc_RuntimeWarning,
897 "Unknown general name type") == -1) {
898 goto fail;
899 }
900 break;
901 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000902 (void) BIO_reset(biobuf);
903 GENERAL_NAME_print(biobuf, name);
904 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
905 if (len < 0) {
906 _setSSLError(NULL, 0, __FILE__, __LINE__);
907 goto fail;
908 }
909 vptr = strchr(buf, ':');
910 if (vptr == NULL)
911 goto fail;
912 t = PyTuple_New(2);
913 if (t == NULL)
914 goto fail;
915 v = PyString_FromStringAndSize(buf, (vptr - buf));
916 if (v == NULL) {
917 Py_DECREF(t);
918 goto fail;
919 }
920 PyTuple_SET_ITEM(t, 0, v);
921 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
922 if (v == NULL) {
923 Py_DECREF(t);
924 goto fail;
925 }
926 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200927 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 }
929
930 /* and add that rendering to the list */
931
932 if (PyList_Append(peer_alt_names, t) < 0) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 Py_DECREF(t);
937 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +0100938 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000939 }
940 BIO_free(biobuf);
941 if (peer_alt_names != Py_None) {
942 v = PyList_AsTuple(peer_alt_names);
943 Py_DECREF(peer_alt_names);
944 return v;
945 } else {
946 return peer_alt_names;
947 }
948
Bill Janssen98d19da2007-09-10 21:51:02 +0000949
950 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000951 if (biobuf != NULL)
952 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000953
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000954 if (peer_alt_names != Py_None) {
955 Py_XDECREF(peer_alt_names);
956 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000957
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000958 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000959}
960
961static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500962_get_aia_uri(X509 *certificate, int nid) {
963 PyObject *lst = NULL, *ostr = NULL;
964 int i, result;
965 AUTHORITY_INFO_ACCESS *info;
966
967 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
968 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
969 return Py_None;
970 }
971
972 if ((lst = PyList_New(0)) == NULL) {
973 goto fail;
974 }
975
976 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
977 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
978 ASN1_IA5STRING *uri;
979
980 if ((OBJ_obj2nid(ad->method) != nid) ||
981 (ad->location->type != GEN_URI)) {
982 continue;
983 }
984 uri = ad->location->d.uniformResourceIdentifier;
985 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
986 uri->length);
987 if (ostr == NULL) {
988 goto fail;
989 }
990 result = PyList_Append(lst, ostr);
991 Py_DECREF(ostr);
992 if (result < 0) {
993 goto fail;
994 }
995 }
996 AUTHORITY_INFO_ACCESS_free(info);
997
998 /* convert to tuple or None */
999 if (PyList_Size(lst) == 0) {
1000 Py_DECREF(lst);
1001 return Py_None;
1002 } else {
1003 PyObject *tup;
1004 tup = PyList_AsTuple(lst);
1005 Py_DECREF(lst);
1006 return tup;
1007 }
1008
1009 fail:
1010 AUTHORITY_INFO_ACCESS_free(info);
1011 Py_XDECREF(lst);
1012 return NULL;
1013}
1014
1015static PyObject *
1016_get_crl_dp(X509 *certificate) {
1017 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001018 int i, j;
1019 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001020
1021#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001022 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001023#else
1024 /* Calls x509v3_cache_extensions and sets up crldp */
1025 X509_check_ca(certificate);
1026 dps = certificate->crldp;
1027#endif
1028
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001029 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001030 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001031
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001032 lst = PyList_New(0);
1033 if (lst == NULL)
1034 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001035
1036 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1037 DIST_POINT *dp;
1038 STACK_OF(GENERAL_NAME) *gns;
1039
1040 dp = sk_DIST_POINT_value(dps, i);
1041 gns = dp->distpoint->name.fullname;
1042
1043 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1044 GENERAL_NAME *gn;
1045 ASN1_IA5STRING *uri;
1046 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001047 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001048
1049 gn = sk_GENERAL_NAME_value(gns, j);
1050 if (gn->type != GEN_URI) {
1051 continue;
1052 }
1053 uri = gn->d.uniformResourceIdentifier;
1054 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1055 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001056 if (ouri == NULL)
1057 goto done;
1058
1059 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001060 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001061 if (err < 0)
1062 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001063 }
1064 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001065
1066 /* Convert to tuple. */
1067 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1068
1069 done:
1070 Py_XDECREF(lst);
1071#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersonb1c1e672015-11-14 00:09:22 -08001072 sk_DIST_POINT_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001073#endif
1074 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001075}
1076
1077static PyObject *
1078_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001079
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001080 PyObject *retval = NULL;
1081 BIO *biobuf = NULL;
1082 PyObject *peer;
1083 PyObject *peer_alt_names = NULL;
1084 PyObject *issuer;
1085 PyObject *version;
1086 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001087 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001088 ASN1_INTEGER *serialNumber;
1089 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001090 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001091 ASN1_TIME *notBefore, *notAfter;
1092 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001093
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001094 retval = PyDict_New();
1095 if (retval == NULL)
1096 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001097
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001098 peer = _create_tuple_for_X509_NAME(
1099 X509_get_subject_name(certificate));
1100 if (peer == NULL)
1101 goto fail0;
1102 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1103 Py_DECREF(peer);
1104 goto fail0;
1105 }
1106 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001107
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001108 issuer = _create_tuple_for_X509_NAME(
1109 X509_get_issuer_name(certificate));
1110 if (issuer == NULL)
1111 goto fail0;
1112 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001113 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001114 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001115 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001116 Py_DECREF(issuer);
1117
1118 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1119 if (version == NULL)
1120 goto fail0;
1121 if (PyDict_SetItemString(retval, "version", version) < 0) {
1122 Py_DECREF(version);
1123 goto fail0;
1124 }
1125 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001126
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001127 /* get a memory buffer */
1128 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001129
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001130 (void) BIO_reset(biobuf);
1131 serialNumber = X509_get_serialNumber(certificate);
1132 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1133 i2a_ASN1_INTEGER(biobuf, serialNumber);
1134 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1135 if (len < 0) {
1136 _setSSLError(NULL, 0, __FILE__, __LINE__);
1137 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001138 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001139 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1140 if (sn_obj == NULL)
1141 goto fail1;
1142 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1143 Py_DECREF(sn_obj);
1144 goto fail1;
1145 }
1146 Py_DECREF(sn_obj);
1147
1148 (void) BIO_reset(biobuf);
1149 notBefore = X509_get_notBefore(certificate);
1150 ASN1_TIME_print(biobuf, notBefore);
1151 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1152 if (len < 0) {
1153 _setSSLError(NULL, 0, __FILE__, __LINE__);
1154 goto fail1;
1155 }
1156 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1157 if (pnotBefore == NULL)
1158 goto fail1;
1159 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1160 Py_DECREF(pnotBefore);
1161 goto fail1;
1162 }
1163 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001164
1165 (void) BIO_reset(biobuf);
1166 notAfter = X509_get_notAfter(certificate);
1167 ASN1_TIME_print(biobuf, notAfter);
1168 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1169 if (len < 0) {
1170 _setSSLError(NULL, 0, __FILE__, __LINE__);
1171 goto fail1;
1172 }
1173 pnotAfter = PyString_FromStringAndSize(buf, len);
1174 if (pnotAfter == NULL)
1175 goto fail1;
1176 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1177 Py_DECREF(pnotAfter);
1178 goto fail1;
1179 }
1180 Py_DECREF(pnotAfter);
1181
1182 /* Now look for subjectAltName */
1183
1184 peer_alt_names = _get_peer_alt_names(certificate);
1185 if (peer_alt_names == NULL)
1186 goto fail1;
1187 else if (peer_alt_names != Py_None) {
1188 if (PyDict_SetItemString(retval, "subjectAltName",
1189 peer_alt_names) < 0) {
1190 Py_DECREF(peer_alt_names);
1191 goto fail1;
1192 }
1193 Py_DECREF(peer_alt_names);
1194 }
1195
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001196 /* Authority Information Access: OCSP URIs */
1197 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1198 if (obj == NULL) {
1199 goto fail1;
1200 } else if (obj != Py_None) {
1201 result = PyDict_SetItemString(retval, "OCSP", obj);
1202 Py_DECREF(obj);
1203 if (result < 0) {
1204 goto fail1;
1205 }
1206 }
1207
1208 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1209 if (obj == NULL) {
1210 goto fail1;
1211 } else if (obj != Py_None) {
1212 result = PyDict_SetItemString(retval, "caIssuers", obj);
1213 Py_DECREF(obj);
1214 if (result < 0) {
1215 goto fail1;
1216 }
1217 }
1218
1219 /* CDP (CRL distribution points) */
1220 obj = _get_crl_dp(certificate);
1221 if (obj == NULL) {
1222 goto fail1;
1223 } else if (obj != Py_None) {
1224 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1225 Py_DECREF(obj);
1226 if (result < 0) {
1227 goto fail1;
1228 }
1229 }
1230
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001231 BIO_free(biobuf);
1232 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001233
1234 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001235 if (biobuf != NULL)
1236 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001237 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001238 Py_XDECREF(retval);
1239 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001240}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001241
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001242static PyObject *
1243_certificate_to_der(X509 *certificate)
1244{
1245 unsigned char *bytes_buf = NULL;
1246 int len;
1247 PyObject *retval;
1248
1249 bytes_buf = NULL;
1250 len = i2d_X509(certificate, &bytes_buf);
1251 if (len < 0) {
1252 _setSSLError(NULL, 0, __FILE__, __LINE__);
1253 return NULL;
1254 }
1255 /* this is actually an immutable bytes sequence */
1256 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1257 OPENSSL_free(bytes_buf);
1258 return retval;
1259}
Bill Janssen98d19da2007-09-10 21:51:02 +00001260
1261static PyObject *
1262PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1263
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001264 PyObject *retval = NULL;
1265 char *filename = NULL;
1266 X509 *x=NULL;
1267 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001268
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001269 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001270 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001271
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001272 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001273 PyErr_SetString(PySSLErrorObject,
1274 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001275 goto fail0;
1276 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001277
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001278 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001279 PyErr_SetString(PySSLErrorObject,
1280 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001281 goto fail0;
1282 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001283
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001284 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1285 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001286 PyErr_SetString(PySSLErrorObject,
1287 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001288 goto fail0;
1289 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001290
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001291 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001292 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001293
1294 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001295
1296 if (cert != NULL) BIO_free(cert);
1297 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001298}
1299
1300
1301static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001302PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001303{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001304 int verification;
1305 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001306 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001307
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001308 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1309 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001310
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001311 if (!self->handshake_done) {
1312 PyErr_SetString(PyExc_ValueError,
1313 "handshake not done yet");
1314 return NULL;
1315 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001316 if (!self->peer_cert)
1317 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001318
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001319 b = PyObject_IsTrue(binary_mode);
1320 if (b < 0)
1321 return NULL;
1322 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001323 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001324 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001325 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001326 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001327 if ((verification & SSL_VERIFY_PEER) == 0)
1328 return PyDict_New();
1329 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001330 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001331 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001332}
1333
1334PyDoc_STRVAR(PySSL_peercert_doc,
1335"peer_certificate([der=False]) -> certificate\n\
1336\n\
1337Returns the certificate for the peer. If no certificate was provided,\n\
1338returns None. If a certificate was provided, but not validated, returns\n\
1339an empty dictionary. Otherwise returns a dict containing information\n\
1340about the peer certificate.\n\
1341\n\
1342If the optional argument is True, returns a DER-encoded copy of the\n\
1343peer certificate, or None if no certificate was provided. This will\n\
1344return the certificate even if it wasn't validated.");
1345
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001346static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001347
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001348 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001349 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001350 char *cipher_name;
1351 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001352
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001353 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001354 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001355 current = SSL_get_current_cipher(self->ssl);
1356 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001357 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001358
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001359 retval = PyTuple_New(3);
1360 if (retval == NULL)
1361 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001362
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001363 cipher_name = (char *) SSL_CIPHER_get_name(current);
1364 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001365 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001366 PyTuple_SET_ITEM(retval, 0, Py_None);
1367 } else {
1368 v = PyString_FromString(cipher_name);
1369 if (v == NULL)
1370 goto fail0;
1371 PyTuple_SET_ITEM(retval, 0, v);
1372 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001373 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001374 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001375 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001376 PyTuple_SET_ITEM(retval, 1, Py_None);
1377 } else {
1378 v = PyString_FromString(cipher_protocol);
1379 if (v == NULL)
1380 goto fail0;
1381 PyTuple_SET_ITEM(retval, 1, v);
1382 }
1383 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1384 if (v == NULL)
1385 goto fail0;
1386 PyTuple_SET_ITEM(retval, 2, v);
1387 return retval;
1388
Bill Janssen98d19da2007-09-10 21:51:02 +00001389 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001390 Py_DECREF(retval);
1391 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001392}
1393
Alex Gaynore98205d2014-09-04 13:33:22 -07001394static PyObject *PySSL_version(PySSLSocket *self)
1395{
1396 const char *version;
1397
1398 if (self->ssl == NULL)
1399 Py_RETURN_NONE;
1400 version = SSL_get_version(self->ssl);
1401 if (!strcmp(version, "unknown"))
1402 Py_RETURN_NONE;
1403 return PyUnicode_FromString(version);
1404}
1405
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001406#ifdef OPENSSL_NPN_NEGOTIATED
1407static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1408 const unsigned char *out;
1409 unsigned int outlen;
1410
1411 SSL_get0_next_proto_negotiated(self->ssl,
1412 &out, &outlen);
1413
1414 if (out == NULL)
1415 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001416 return PyString_FromStringAndSize((char *)out, outlen);
1417}
1418#endif
1419
1420#ifdef HAVE_ALPN
1421static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1422 const unsigned char *out;
1423 unsigned int outlen;
1424
1425 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1426
1427 if (out == NULL)
1428 Py_RETURN_NONE;
1429 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001430}
1431#endif
1432
1433static PyObject *PySSL_compression(PySSLSocket *self) {
1434#ifdef OPENSSL_NO_COMP
1435 Py_RETURN_NONE;
1436#else
1437 const COMP_METHOD *comp_method;
1438 const char *short_name;
1439
1440 if (self->ssl == NULL)
1441 Py_RETURN_NONE;
1442 comp_method = SSL_get_current_compression(self->ssl);
1443 if (comp_method == NULL || comp_method->type == NID_undef)
1444 Py_RETURN_NONE;
1445 short_name = OBJ_nid2sn(comp_method->type);
1446 if (short_name == NULL)
1447 Py_RETURN_NONE;
1448 return PyBytes_FromString(short_name);
1449#endif
1450}
1451
1452static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1453 Py_INCREF(self->ctx);
1454 return self->ctx;
1455}
1456
1457static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1458 void *closure) {
1459
1460 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1461#if !HAVE_SNI
1462 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1463 "context is not supported by your OpenSSL library");
1464 return -1;
1465#else
1466 Py_INCREF(value);
1467 Py_DECREF(self->ctx);
1468 self->ctx = (PySSLContext *) value;
1469 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1470#endif
1471 } else {
1472 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1473 return -1;
1474 }
1475
1476 return 0;
1477}
1478
1479PyDoc_STRVAR(PySSL_set_context_doc,
1480"_setter_context(ctx)\n\
1481\
1482This changes the context associated with the SSLSocket. This is typically\n\
1483used from within a callback function set by the set_servername_callback\n\
1484on the SSLContext to change the certificate information associated with the\n\
1485SSLSocket before the cryptographic exchange handshake messages\n");
1486
1487
1488
1489static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001490{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001491 if (self->peer_cert) /* Possible not to have one? */
1492 X509_free (self->peer_cert);
1493 if (self->ssl)
1494 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001495 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001496 Py_XDECREF(self->ssl_sock);
1497 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001498 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001499}
1500
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001501/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001502 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001503 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001504 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001505
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001506static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001507check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001508{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001509 fd_set fds;
1510 struct timeval tv;
1511 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001512
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001513 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1514 if (s->sock_timeout < 0.0)
1515 return SOCKET_IS_BLOCKING;
1516 else if (s->sock_timeout == 0.0)
1517 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001518
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001519 /* Guard against closed socket */
1520 if (s->sock_fd < 0)
1521 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001522
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001523 /* Prefer poll, if available, since you can poll() any fd
1524 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001525#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001526 {
1527 struct pollfd pollfd;
1528 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001529
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001530 pollfd.fd = s->sock_fd;
1531 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001532
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001533 /* s->sock_timeout is in seconds, timeout in ms */
1534 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1535 PySSL_BEGIN_ALLOW_THREADS
1536 rc = poll(&pollfd, 1, timeout);
1537 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001538
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001539 goto normal_return;
1540 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001541#endif
1542
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001543 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001544 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001545 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001546
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001547 /* Construct the arguments to select */
1548 tv.tv_sec = (int)s->sock_timeout;
1549 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1550 FD_ZERO(&fds);
1551 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001552
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001553 /* See if the socket is ready */
1554 PySSL_BEGIN_ALLOW_THREADS
1555 if (writing)
1556 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1557 else
1558 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1559 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001560
Bill Janssen934b16d2008-06-28 22:19:33 +00001561#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001562normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001563#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001564 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1565 (when we are able to write or when there's something to read) */
1566 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001567}
1568
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001569static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001570{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001571 Py_buffer buf;
1572 int len;
1573 int sockstate;
1574 int err;
1575 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001576 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001577
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001578 Py_INCREF(sock);
1579
1580 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1581 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001582 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001583 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001584
Victor Stinnerc1a44262013-06-25 00:48:02 +02001585 if (buf.len > INT_MAX) {
1586 PyErr_Format(PyExc_OverflowError,
1587 "string longer than %d bytes", INT_MAX);
1588 goto error;
1589 }
1590
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001591 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001592 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001593 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1594 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001595
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001596 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001597 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1598 PyErr_SetString(PySSLErrorObject,
1599 "The write operation timed out");
1600 goto error;
1601 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1602 PyErr_SetString(PySSLErrorObject,
1603 "Underlying socket has been closed.");
1604 goto error;
1605 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1606 PyErr_SetString(PySSLErrorObject,
1607 "Underlying socket too large for select().");
1608 goto error;
1609 }
1610 do {
1611 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001612 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001613 err = SSL_get_error(self->ssl, len);
1614 PySSL_END_ALLOW_THREADS
1615 if (PyErr_CheckSignals()) {
1616 goto error;
1617 }
1618 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001619 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001620 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001621 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001622 } else {
1623 sockstate = SOCKET_OPERATION_OK;
1624 }
1625 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1626 PyErr_SetString(PySSLErrorObject,
1627 "The write operation timed out");
1628 goto error;
1629 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1630 PyErr_SetString(PySSLErrorObject,
1631 "Underlying socket has been closed.");
1632 goto error;
1633 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1634 break;
1635 }
1636 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001637
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001638 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001639 PyBuffer_Release(&buf);
1640 if (len > 0)
1641 return PyInt_FromLong(len);
1642 else
1643 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001644
1645error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001646 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001647 PyBuffer_Release(&buf);
1648 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001649}
1650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001651PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001652"write(s) -> len\n\
1653\n\
1654Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001655of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001656
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001657static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001658{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001659 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001660
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001661 PySSL_BEGIN_ALLOW_THREADS
1662 count = SSL_pending(self->ssl);
1663 PySSL_END_ALLOW_THREADS
1664 if (count < 0)
1665 return PySSL_SetError(self, count, __FILE__, __LINE__);
1666 else
1667 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001668}
1669
1670PyDoc_STRVAR(PySSL_SSLpending_doc,
1671"pending() -> count\n\
1672\n\
1673Returns the number of already decrypted bytes available for read,\n\
1674pending on the connection.\n");
1675
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001676static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001677{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001678 PyObject *dest = NULL;
1679 Py_buffer buf;
1680 char *mem;
1681 int len, count;
1682 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001683 int sockstate;
1684 int err;
1685 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001686 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001687
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001688 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 buf.obj = NULL;
1691 buf.buf = NULL;
1692 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1693 goto error;
1694
1695 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1696 dest = PyBytes_FromStringAndSize(NULL, len);
1697 if (dest == NULL)
1698 goto error;
1699 mem = PyBytes_AS_STRING(dest);
1700 }
1701 else {
1702 buf_passed = 1;
1703 mem = buf.buf;
1704 if (len <= 0 || len > buf.len) {
1705 len = (int) buf.len;
1706 if (buf.len != len) {
1707 PyErr_SetString(PyExc_OverflowError,
1708 "maximum length can't fit in a C 'int'");
1709 goto error;
1710 }
1711 }
1712 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001713
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001714 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001715 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001716 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1717 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001718
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001719 do {
1720 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001721 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001722 err = SSL_get_error(self->ssl, count);
1723 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001724 if (PyErr_CheckSignals())
1725 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001726 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001727 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001729 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001730 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1731 (SSL_get_shutdown(self->ssl) ==
1732 SSL_RECEIVED_SHUTDOWN))
1733 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001734 count = 0;
1735 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001736 } else {
1737 sockstate = SOCKET_OPERATION_OK;
1738 }
1739 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1740 PyErr_SetString(PySSLErrorObject,
1741 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001742 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001743 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1744 break;
1745 }
1746 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1747 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001748 PySSL_SetError(self, count, __FILE__, __LINE__);
1749 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001750 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001751
1752done:
1753 Py_DECREF(sock);
1754 if (!buf_passed) {
1755 _PyBytes_Resize(&dest, count);
1756 return dest;
1757 }
1758 else {
1759 PyBuffer_Release(&buf);
1760 return PyLong_FromLong(count);
1761 }
1762
1763error:
1764 Py_DECREF(sock);
1765 if (!buf_passed)
1766 Py_XDECREF(dest);
1767 else
1768 PyBuffer_Release(&buf);
1769 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001770}
1771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001772PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001773"read([len]) -> string\n\
1774\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001775Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001776
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001777static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001778{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001779 int err, ssl_err, sockstate, nonblocking;
1780 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001781 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001782
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001783 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001784 if (sock->sock_fd < 0) {
1785 _setSSLError("Underlying socket connection gone",
1786 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001787 return NULL;
1788 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001789 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001790
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001791 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001792 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001793 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1794 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001795
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001796 while (1) {
1797 PySSL_BEGIN_ALLOW_THREADS
1798 /* Disable read-ahead so that unwrap can work correctly.
1799 * Otherwise OpenSSL might read in too much data,
1800 * eating clear text data that happens to be
1801 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001802 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001803 * function is used and the shutdown_seen_zero != 0
1804 * condition is met.
1805 */
1806 if (self->shutdown_seen_zero)
1807 SSL_set_read_ahead(self->ssl, 0);
1808 err = SSL_shutdown(self->ssl);
1809 PySSL_END_ALLOW_THREADS
1810 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1811 if (err > 0)
1812 break;
1813 if (err == 0) {
1814 /* Don't loop endlessly; instead preserve legacy
1815 behaviour of trying SSL_shutdown() only twice.
1816 This looks necessary for OpenSSL < 0.9.8m */
1817 if (++zeros > 1)
1818 break;
1819 /* Shutdown was sent, now try receiving */
1820 self->shutdown_seen_zero = 1;
1821 continue;
1822 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001823
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001824 /* Possibly retry shutdown until timeout or failure */
1825 ssl_err = SSL_get_error(self->ssl, err);
1826 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001827 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001828 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001829 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001830 else
1831 break;
1832 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1833 if (ssl_err == SSL_ERROR_WANT_READ)
1834 PyErr_SetString(PySSLErrorObject,
1835 "The read operation timed out");
1836 else
1837 PyErr_SetString(PySSLErrorObject,
1838 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001840 }
1841 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1842 PyErr_SetString(PySSLErrorObject,
1843 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001845 }
1846 else if (sockstate != SOCKET_OPERATION_OK)
1847 /* Retain the SSL error code */
1848 break;
1849 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001850
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001851 if (err < 0) {
1852 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001853 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001854 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001855 else
1856 /* It's already INCREF'ed */
1857 return (PyObject *) sock;
1858
1859error:
1860 Py_DECREF(sock);
1861 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001862}
1863
1864PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1865"shutdown(s) -> socket\n\
1866\n\
1867Does the SSL shutdown handshake with the remote end, and returns\n\
1868the underlying socket object.");
1869
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001870#if HAVE_OPENSSL_FINISHED
1871static PyObject *
1872PySSL_tls_unique_cb(PySSLSocket *self)
1873{
1874 PyObject *retval = NULL;
1875 char buf[PySSL_CB_MAXLEN];
1876 size_t len;
1877
1878 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1879 /* if session is resumed XOR we are the client */
1880 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1881 }
1882 else {
1883 /* if a new session XOR we are the server */
1884 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1885 }
1886
1887 /* It cannot be negative in current OpenSSL version as of July 2011 */
1888 if (len == 0)
1889 Py_RETURN_NONE;
1890
1891 retval = PyBytes_FromStringAndSize(buf, len);
1892
1893 return retval;
1894}
1895
1896PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1897"tls_unique_cb() -> bytes\n\
1898\n\
1899Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1900\n\
1901If the TLS handshake is not yet complete, None is returned");
1902
1903#endif /* HAVE_OPENSSL_FINISHED */
1904
1905static PyGetSetDef ssl_getsetlist[] = {
1906 {"context", (getter) PySSL_get_context,
1907 (setter) PySSL_set_context, PySSL_set_context_doc},
1908 {NULL}, /* sentinel */
1909};
1910
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001911static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001912 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1913 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1914 PySSL_SSLwrite_doc},
1915 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1916 PySSL_SSLread_doc},
1917 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1918 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001919 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1920 PySSL_peercert_doc},
1921 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07001922 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001923#ifdef OPENSSL_NPN_NEGOTIATED
1924 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1925#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001926#ifdef HAVE_ALPN
1927 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
1928#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001929 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001930 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1931 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001932#if HAVE_OPENSSL_FINISHED
1933 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1934 PySSL_tls_unique_cb_doc},
1935#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001936 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937};
1938
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001939static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001940 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001941 "_ssl._SSLSocket", /*tp_name*/
1942 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001943 0, /*tp_itemsize*/
1944 /* methods */
1945 (destructor)PySSL_dealloc, /*tp_dealloc*/
1946 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001947 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001948 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001949 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001950 0, /*tp_repr*/
1951 0, /*tp_as_number*/
1952 0, /*tp_as_sequence*/
1953 0, /*tp_as_mapping*/
1954 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001955 0, /*tp_call*/
1956 0, /*tp_str*/
1957 0, /*tp_getattro*/
1958 0, /*tp_setattro*/
1959 0, /*tp_as_buffer*/
1960 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1961 0, /*tp_doc*/
1962 0, /*tp_traverse*/
1963 0, /*tp_clear*/
1964 0, /*tp_richcompare*/
1965 0, /*tp_weaklistoffset*/
1966 0, /*tp_iter*/
1967 0, /*tp_iternext*/
1968 PySSLMethods, /*tp_methods*/
1969 0, /*tp_members*/
1970 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001971};
1972
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001973
1974/*
1975 * _SSLContext objects
1976 */
1977
1978static PyObject *
1979context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1980{
1981 char *kwlist[] = {"protocol", NULL};
1982 PySSLContext *self;
1983 int proto_version = PY_SSL_VERSION_SSL23;
1984 long options;
1985 SSL_CTX *ctx = NULL;
1986
1987 if (!PyArg_ParseTupleAndKeywords(
1988 args, kwds, "i:_SSLContext", kwlist,
1989 &proto_version))
1990 return NULL;
1991
1992 PySSL_BEGIN_ALLOW_THREADS
1993 if (proto_version == PY_SSL_VERSION_TLS1)
1994 ctx = SSL_CTX_new(TLSv1_method());
1995#if HAVE_TLSv1_2
1996 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1997 ctx = SSL_CTX_new(TLSv1_1_method());
1998 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1999 ctx = SSL_CTX_new(TLSv1_2_method());
2000#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002001#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002002 else if (proto_version == PY_SSL_VERSION_SSL3)
2003 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002004#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002005#ifndef OPENSSL_NO_SSL2
2006 else if (proto_version == PY_SSL_VERSION_SSL2)
2007 ctx = SSL_CTX_new(SSLv2_method());
2008#endif
2009 else if (proto_version == PY_SSL_VERSION_SSL23)
2010 ctx = SSL_CTX_new(SSLv23_method());
2011 else
2012 proto_version = -1;
2013 PySSL_END_ALLOW_THREADS
2014
2015 if (proto_version == -1) {
2016 PyErr_SetString(PyExc_ValueError,
2017 "invalid protocol version");
2018 return NULL;
2019 }
2020 if (ctx == NULL) {
2021 PyErr_SetString(PySSLErrorObject,
2022 "failed to allocate SSL context");
2023 return NULL;
2024 }
2025
2026 assert(type != NULL && type->tp_alloc != NULL);
2027 self = (PySSLContext *) type->tp_alloc(type, 0);
2028 if (self == NULL) {
2029 SSL_CTX_free(ctx);
2030 return NULL;
2031 }
2032 self->ctx = ctx;
2033#ifdef OPENSSL_NPN_NEGOTIATED
2034 self->npn_protocols = NULL;
2035#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002036#ifdef HAVE_ALPN
2037 self->alpn_protocols = NULL;
2038#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002039#ifndef OPENSSL_NO_TLSEXT
2040 self->set_hostname = NULL;
2041#endif
2042 /* Don't check host name by default */
2043 self->check_hostname = 0;
2044 /* Defaults */
2045 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2046 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2047 if (proto_version != PY_SSL_VERSION_SSL2)
2048 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002049 if (proto_version != PY_SSL_VERSION_SSL3)
2050 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002051 SSL_CTX_set_options(self->ctx, options);
2052
2053#ifndef OPENSSL_NO_ECDH
2054 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2055 prime256v1 by default. This is Apache mod_ssl's initialization
2056 policy, so we should be safe. */
2057#if defined(SSL_CTX_set_ecdh_auto)
2058 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2059#else
2060 {
2061 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2062 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2063 EC_KEY_free(key);
2064 }
2065#endif
2066#endif
2067
2068#define SID_CTX "Python"
2069 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2070 sizeof(SID_CTX));
2071#undef SID_CTX
2072
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002073#ifdef X509_V_FLAG_TRUSTED_FIRST
2074 {
2075 /* Improve trust chain building when cross-signed intermediate
2076 certificates are present. See https://bugs.python.org/issue23476. */
2077 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2078 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2079 }
2080#endif
2081
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002082 return (PyObject *)self;
2083}
2084
2085static int
2086context_traverse(PySSLContext *self, visitproc visit, void *arg)
2087{
2088#ifndef OPENSSL_NO_TLSEXT
2089 Py_VISIT(self->set_hostname);
2090#endif
2091 return 0;
2092}
2093
2094static int
2095context_clear(PySSLContext *self)
2096{
2097#ifndef OPENSSL_NO_TLSEXT
2098 Py_CLEAR(self->set_hostname);
2099#endif
2100 return 0;
2101}
2102
2103static void
2104context_dealloc(PySSLContext *self)
2105{
2106 context_clear(self);
2107 SSL_CTX_free(self->ctx);
2108#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002109 PyMem_FREE(self->npn_protocols);
2110#endif
2111#ifdef HAVE_ALPN
2112 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002113#endif
2114 Py_TYPE(self)->tp_free(self);
2115}
2116
2117static PyObject *
2118set_ciphers(PySSLContext *self, PyObject *args)
2119{
2120 int ret;
2121 const char *cipherlist;
2122
2123 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2124 return NULL;
2125 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2126 if (ret == 0) {
2127 /* Clearing the error queue is necessary on some OpenSSL versions,
2128 otherwise the error will be reported again when another SSL call
2129 is done. */
2130 ERR_clear_error();
2131 PyErr_SetString(PySSLErrorObject,
2132 "No cipher can be selected.");
2133 return NULL;
2134 }
2135 Py_RETURN_NONE;
2136}
2137
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002138#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002139static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002140do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2141 const unsigned char *server_protocols, unsigned int server_protocols_len,
2142 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002143{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002144 int ret;
2145 if (client_protocols == NULL) {
2146 client_protocols = (unsigned char *)"";
2147 client_protocols_len = 0;
2148 }
2149 if (server_protocols == NULL) {
2150 server_protocols = (unsigned char *)"";
2151 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002152 }
2153
Benjamin Petersonaa707582015-01-23 17:30:26 -05002154 ret = SSL_select_next_proto(out, outlen,
2155 server_protocols, server_protocols_len,
2156 client_protocols, client_protocols_len);
2157 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2158 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002159
2160 return SSL_TLSEXT_ERR_OK;
2161}
2162
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002163/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2164static int
2165_advertiseNPN_cb(SSL *s,
2166 const unsigned char **data, unsigned int *len,
2167 void *args)
2168{
2169 PySSLContext *ssl_ctx = (PySSLContext *) args;
2170
2171 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002172 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002173 *len = 0;
2174 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002175 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002176 *len = ssl_ctx->npn_protocols_len;
2177 }
2178
2179 return SSL_TLSEXT_ERR_OK;
2180}
2181/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2182static int
2183_selectNPN_cb(SSL *s,
2184 unsigned char **out, unsigned char *outlen,
2185 const unsigned char *server, unsigned int server_len,
2186 void *args)
2187{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002188 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002189 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002190 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002191}
2192#endif
2193
2194static PyObject *
2195_set_npn_protocols(PySSLContext *self, PyObject *args)
2196{
2197#ifdef OPENSSL_NPN_NEGOTIATED
2198 Py_buffer protos;
2199
2200 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2201 return NULL;
2202
2203 if (self->npn_protocols != NULL) {
2204 PyMem_Free(self->npn_protocols);
2205 }
2206
2207 self->npn_protocols = PyMem_Malloc(protos.len);
2208 if (self->npn_protocols == NULL) {
2209 PyBuffer_Release(&protos);
2210 return PyErr_NoMemory();
2211 }
2212 memcpy(self->npn_protocols, protos.buf, protos.len);
2213 self->npn_protocols_len = (int) protos.len;
2214
2215 /* set both server and client callbacks, because the context can
2216 * be used to create both types of sockets */
2217 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2218 _advertiseNPN_cb,
2219 self);
2220 SSL_CTX_set_next_proto_select_cb(self->ctx,
2221 _selectNPN_cb,
2222 self);
2223
2224 PyBuffer_Release(&protos);
2225 Py_RETURN_NONE;
2226#else
2227 PyErr_SetString(PyExc_NotImplementedError,
2228 "The NPN extension requires OpenSSL 1.0.1 or later.");
2229 return NULL;
2230#endif
2231}
2232
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002233#ifdef HAVE_ALPN
2234static int
2235_selectALPN_cb(SSL *s,
2236 const unsigned char **out, unsigned char *outlen,
2237 const unsigned char *client_protocols, unsigned int client_protocols_len,
2238 void *args)
2239{
2240 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002241 return do_protocol_selection(1, (unsigned char **)out, outlen,
2242 ctx->alpn_protocols, ctx->alpn_protocols_len,
2243 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002244}
2245#endif
2246
2247static PyObject *
2248_set_alpn_protocols(PySSLContext *self, PyObject *args)
2249{
2250#ifdef HAVE_ALPN
2251 Py_buffer protos;
2252
2253 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2254 return NULL;
2255
2256 PyMem_FREE(self->alpn_protocols);
2257 self->alpn_protocols = PyMem_Malloc(protos.len);
2258 if (!self->alpn_protocols)
2259 return PyErr_NoMemory();
2260 memcpy(self->alpn_protocols, protos.buf, protos.len);
2261 self->alpn_protocols_len = protos.len;
2262 PyBuffer_Release(&protos);
2263
2264 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2265 return PyErr_NoMemory();
2266 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2267
2268 PyBuffer_Release(&protos);
2269 Py_RETURN_NONE;
2270#else
2271 PyErr_SetString(PyExc_NotImplementedError,
2272 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2273 return NULL;
2274#endif
2275}
2276
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002277static PyObject *
2278get_verify_mode(PySSLContext *self, void *c)
2279{
2280 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2281 case SSL_VERIFY_NONE:
2282 return PyLong_FromLong(PY_SSL_CERT_NONE);
2283 case SSL_VERIFY_PEER:
2284 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2285 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2286 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2287 }
2288 PyErr_SetString(PySSLErrorObject,
2289 "invalid return value from SSL_CTX_get_verify_mode");
2290 return NULL;
2291}
2292
2293static int
2294set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2295{
2296 int n, mode;
2297 if (!PyArg_Parse(arg, "i", &n))
2298 return -1;
2299 if (n == PY_SSL_CERT_NONE)
2300 mode = SSL_VERIFY_NONE;
2301 else if (n == PY_SSL_CERT_OPTIONAL)
2302 mode = SSL_VERIFY_PEER;
2303 else if (n == PY_SSL_CERT_REQUIRED)
2304 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2305 else {
2306 PyErr_SetString(PyExc_ValueError,
2307 "invalid value for verify_mode");
2308 return -1;
2309 }
2310 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2311 PyErr_SetString(PyExc_ValueError,
2312 "Cannot set verify_mode to CERT_NONE when "
2313 "check_hostname is enabled.");
2314 return -1;
2315 }
2316 SSL_CTX_set_verify(self->ctx, mode, NULL);
2317 return 0;
2318}
2319
2320#ifdef HAVE_OPENSSL_VERIFY_PARAM
2321static PyObject *
2322get_verify_flags(PySSLContext *self, void *c)
2323{
2324 X509_STORE *store;
2325 unsigned long flags;
2326
2327 store = SSL_CTX_get_cert_store(self->ctx);
2328 flags = X509_VERIFY_PARAM_get_flags(store->param);
2329 return PyLong_FromUnsignedLong(flags);
2330}
2331
2332static int
2333set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2334{
2335 X509_STORE *store;
2336 unsigned long new_flags, flags, set, clear;
2337
2338 if (!PyArg_Parse(arg, "k", &new_flags))
2339 return -1;
2340 store = SSL_CTX_get_cert_store(self->ctx);
2341 flags = X509_VERIFY_PARAM_get_flags(store->param);
2342 clear = flags & ~new_flags;
2343 set = ~flags & new_flags;
2344 if (clear) {
2345 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2346 _setSSLError(NULL, 0, __FILE__, __LINE__);
2347 return -1;
2348 }
2349 }
2350 if (set) {
2351 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2352 _setSSLError(NULL, 0, __FILE__, __LINE__);
2353 return -1;
2354 }
2355 }
2356 return 0;
2357}
2358#endif
2359
2360static PyObject *
2361get_options(PySSLContext *self, void *c)
2362{
2363 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2364}
2365
2366static int
2367set_options(PySSLContext *self, PyObject *arg, void *c)
2368{
2369 long new_opts, opts, set, clear;
2370 if (!PyArg_Parse(arg, "l", &new_opts))
2371 return -1;
2372 opts = SSL_CTX_get_options(self->ctx);
2373 clear = opts & ~new_opts;
2374 set = ~opts & new_opts;
2375 if (clear) {
2376#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2377 SSL_CTX_clear_options(self->ctx, clear);
2378#else
2379 PyErr_SetString(PyExc_ValueError,
2380 "can't clear options before OpenSSL 0.9.8m");
2381 return -1;
2382#endif
2383 }
2384 if (set)
2385 SSL_CTX_set_options(self->ctx, set);
2386 return 0;
2387}
2388
2389static PyObject *
2390get_check_hostname(PySSLContext *self, void *c)
2391{
2392 return PyBool_FromLong(self->check_hostname);
2393}
2394
2395static int
2396set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2397{
2398 PyObject *py_check_hostname;
2399 int check_hostname;
2400 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2401 return -1;
2402
2403 check_hostname = PyObject_IsTrue(py_check_hostname);
2404 if (check_hostname < 0)
2405 return -1;
2406 if (check_hostname &&
2407 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2408 PyErr_SetString(PyExc_ValueError,
2409 "check_hostname needs a SSL context with either "
2410 "CERT_OPTIONAL or CERT_REQUIRED");
2411 return -1;
2412 }
2413 self->check_hostname = check_hostname;
2414 return 0;
2415}
2416
2417
2418typedef struct {
2419 PyThreadState *thread_state;
2420 PyObject *callable;
2421 char *password;
2422 int size;
2423 int error;
2424} _PySSLPasswordInfo;
2425
2426static int
2427_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2428 const char *bad_type_error)
2429{
2430 /* Set the password and size fields of a _PySSLPasswordInfo struct
2431 from a unicode, bytes, or byte array object.
2432 The password field will be dynamically allocated and must be freed
2433 by the caller */
2434 PyObject *password_bytes = NULL;
2435 const char *data = NULL;
2436 Py_ssize_t size;
2437
2438 if (PyUnicode_Check(password)) {
2439 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2440 if (!password_bytes) {
2441 goto error;
2442 }
2443 data = PyBytes_AS_STRING(password_bytes);
2444 size = PyBytes_GET_SIZE(password_bytes);
2445 } else if (PyBytes_Check(password)) {
2446 data = PyBytes_AS_STRING(password);
2447 size = PyBytes_GET_SIZE(password);
2448 } else if (PyByteArray_Check(password)) {
2449 data = PyByteArray_AS_STRING(password);
2450 size = PyByteArray_GET_SIZE(password);
2451 } else {
2452 PyErr_SetString(PyExc_TypeError, bad_type_error);
2453 goto error;
2454 }
2455
2456 if (size > (Py_ssize_t)INT_MAX) {
2457 PyErr_Format(PyExc_ValueError,
2458 "password cannot be longer than %d bytes", INT_MAX);
2459 goto error;
2460 }
2461
2462 PyMem_Free(pw_info->password);
2463 pw_info->password = PyMem_Malloc(size);
2464 if (!pw_info->password) {
2465 PyErr_SetString(PyExc_MemoryError,
2466 "unable to allocate password buffer");
2467 goto error;
2468 }
2469 memcpy(pw_info->password, data, size);
2470 pw_info->size = (int)size;
2471
2472 Py_XDECREF(password_bytes);
2473 return 1;
2474
2475error:
2476 Py_XDECREF(password_bytes);
2477 return 0;
2478}
2479
2480static int
2481_password_callback(char *buf, int size, int rwflag, void *userdata)
2482{
2483 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2484 PyObject *fn_ret = NULL;
2485
2486 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2487
2488 if (pw_info->callable) {
2489 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2490 if (!fn_ret) {
2491 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2492 core python API, so we could use it to add a frame here */
2493 goto error;
2494 }
2495
2496 if (!_pwinfo_set(pw_info, fn_ret,
2497 "password callback must return a string")) {
2498 goto error;
2499 }
2500 Py_CLEAR(fn_ret);
2501 }
2502
2503 if (pw_info->size > size) {
2504 PyErr_Format(PyExc_ValueError,
2505 "password cannot be longer than %d bytes", size);
2506 goto error;
2507 }
2508
2509 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2510 memcpy(buf, pw_info->password, pw_info->size);
2511 return pw_info->size;
2512
2513error:
2514 Py_XDECREF(fn_ret);
2515 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2516 pw_info->error = 1;
2517 return -1;
2518}
2519
2520static PyObject *
2521load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2522{
2523 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002524 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2525 char *certfile_bytes = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002526 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2527 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2528 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2529 int r;
2530
2531 errno = 0;
2532 ERR_clear_error();
2533 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002534 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002535 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002536 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002537 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002538
2539 if (keyfile && keyfile != Py_None) {
2540 if (PyString_Check(keyfile)) {
2541 Py_INCREF(keyfile);
2542 keyfile_bytes = keyfile;
2543 } else {
2544 PyObject *u = PyUnicode_FromObject(keyfile);
2545 if (!u)
2546 goto error;
2547 keyfile_bytes = PyUnicode_AsEncodedString(
2548 u, Py_FileSystemDefaultEncoding, NULL);
2549 Py_DECREF(u);
2550 if (!keyfile_bytes)
2551 goto error;
2552 }
2553 }
2554
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002555 if (password && password != Py_None) {
2556 if (PyCallable_Check(password)) {
2557 pw_info.callable = password;
2558 } else if (!_pwinfo_set(&pw_info, password,
2559 "password should be a string or callable")) {
2560 goto error;
2561 }
2562 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2563 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2564 }
2565 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2566 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2567 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2568 if (r != 1) {
2569 if (pw_info.error) {
2570 ERR_clear_error();
2571 /* the password callback has already set the error information */
2572 }
2573 else if (errno != 0) {
2574 ERR_clear_error();
2575 PyErr_SetFromErrno(PyExc_IOError);
2576 }
2577 else {
2578 _setSSLError(NULL, 0, __FILE__, __LINE__);
2579 }
2580 goto error;
2581 }
2582 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2583 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002584 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002585 SSL_FILETYPE_PEM);
2586 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2587 if (r != 1) {
2588 if (pw_info.error) {
2589 ERR_clear_error();
2590 /* the password callback has already set the error information */
2591 }
2592 else if (errno != 0) {
2593 ERR_clear_error();
2594 PyErr_SetFromErrno(PyExc_IOError);
2595 }
2596 else {
2597 _setSSLError(NULL, 0, __FILE__, __LINE__);
2598 }
2599 goto error;
2600 }
2601 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2602 r = SSL_CTX_check_private_key(self->ctx);
2603 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2604 if (r != 1) {
2605 _setSSLError(NULL, 0, __FILE__, __LINE__);
2606 goto error;
2607 }
2608 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2609 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2610 PyMem_Free(pw_info.password);
2611 Py_RETURN_NONE;
2612
2613error:
2614 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2615 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002616 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002617 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002618 PyMem_Free(certfile_bytes);
2619 return NULL;
2620}
2621
2622/* internal helper function, returns -1 on error
2623 */
2624static int
2625_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2626 int filetype)
2627{
2628 BIO *biobuf = NULL;
2629 X509_STORE *store;
2630 int retval = 0, err, loaded = 0;
2631
2632 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2633
2634 if (len <= 0) {
2635 PyErr_SetString(PyExc_ValueError,
2636 "Empty certificate data");
2637 return -1;
2638 } else if (len > INT_MAX) {
2639 PyErr_SetString(PyExc_OverflowError,
2640 "Certificate data is too long.");
2641 return -1;
2642 }
2643
2644 biobuf = BIO_new_mem_buf(data, (int)len);
2645 if (biobuf == NULL) {
2646 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2647 return -1;
2648 }
2649
2650 store = SSL_CTX_get_cert_store(self->ctx);
2651 assert(store != NULL);
2652
2653 while (1) {
2654 X509 *cert = NULL;
2655 int r;
2656
2657 if (filetype == SSL_FILETYPE_ASN1) {
2658 cert = d2i_X509_bio(biobuf, NULL);
2659 } else {
2660 cert = PEM_read_bio_X509(biobuf, NULL,
2661 self->ctx->default_passwd_callback,
2662 self->ctx->default_passwd_callback_userdata);
2663 }
2664 if (cert == NULL) {
2665 break;
2666 }
2667 r = X509_STORE_add_cert(store, cert);
2668 X509_free(cert);
2669 if (!r) {
2670 err = ERR_peek_last_error();
2671 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2672 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2673 /* cert already in hash table, not an error */
2674 ERR_clear_error();
2675 } else {
2676 break;
2677 }
2678 }
2679 loaded++;
2680 }
2681
2682 err = ERR_peek_last_error();
2683 if ((filetype == SSL_FILETYPE_ASN1) &&
2684 (loaded > 0) &&
2685 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2686 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2687 /* EOF ASN1 file, not an error */
2688 ERR_clear_error();
2689 retval = 0;
2690 } else if ((filetype == SSL_FILETYPE_PEM) &&
2691 (loaded > 0) &&
2692 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2693 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2694 /* EOF PEM file, not an error */
2695 ERR_clear_error();
2696 retval = 0;
2697 } else {
2698 _setSSLError(NULL, 0, __FILE__, __LINE__);
2699 retval = -1;
2700 }
2701
2702 BIO_free(biobuf);
2703 return retval;
2704}
2705
2706
2707static PyObject *
2708load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2709{
2710 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2711 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2712 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2713 const char *cafile_buf = NULL, *capath_buf = NULL;
2714 int r = 0, ok = 1;
2715
2716 errno = 0;
2717 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2718 "|OOO:load_verify_locations", kwlist,
2719 &cafile, &capath, &cadata))
2720 return NULL;
2721
2722 if (cafile == Py_None)
2723 cafile = NULL;
2724 if (capath == Py_None)
2725 capath = NULL;
2726 if (cadata == Py_None)
2727 cadata = NULL;
2728
2729 if (cafile == NULL && capath == NULL && cadata == NULL) {
2730 PyErr_SetString(PyExc_TypeError,
2731 "cafile, capath and cadata cannot be all omitted");
2732 goto error;
2733 }
2734
2735 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002736 if (PyString_Check(cafile)) {
2737 Py_INCREF(cafile);
2738 cafile_bytes = cafile;
2739 } else {
2740 PyObject *u = PyUnicode_FromObject(cafile);
2741 if (!u)
2742 goto error;
2743 cafile_bytes = PyUnicode_AsEncodedString(
2744 u, Py_FileSystemDefaultEncoding, NULL);
2745 Py_DECREF(u);
2746 if (!cafile_bytes)
2747 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002748 }
2749 }
2750 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002751 if (PyString_Check(capath)) {
2752 Py_INCREF(capath);
2753 capath_bytes = capath;
2754 } else {
2755 PyObject *u = PyUnicode_FromObject(capath);
2756 if (!u)
2757 goto error;
2758 capath_bytes = PyUnicode_AsEncodedString(
2759 u, Py_FileSystemDefaultEncoding, NULL);
2760 Py_DECREF(u);
2761 if (!capath_bytes)
2762 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002763 }
2764 }
2765
2766 /* validata cadata type and load cadata */
2767 if (cadata) {
2768 Py_buffer buf;
2769 PyObject *cadata_ascii = NULL;
2770
2771 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2772 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2773 PyBuffer_Release(&buf);
2774 PyErr_SetString(PyExc_TypeError,
2775 "cadata should be a contiguous buffer with "
2776 "a single dimension");
2777 goto error;
2778 }
2779 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2780 PyBuffer_Release(&buf);
2781 if (r == -1) {
2782 goto error;
2783 }
2784 } else {
2785 PyErr_Clear();
2786 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2787 if (cadata_ascii == NULL) {
2788 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002789 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002790 "bytes-like object");
2791 goto error;
2792 }
2793 r = _add_ca_certs(self,
2794 PyBytes_AS_STRING(cadata_ascii),
2795 PyBytes_GET_SIZE(cadata_ascii),
2796 SSL_FILETYPE_PEM);
2797 Py_DECREF(cadata_ascii);
2798 if (r == -1) {
2799 goto error;
2800 }
2801 }
2802 }
2803
2804 /* load cafile or capath */
2805 if (cafile_bytes || capath_bytes) {
2806 if (cafile)
2807 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2808 if (capath)
2809 capath_buf = PyBytes_AS_STRING(capath_bytes);
2810 PySSL_BEGIN_ALLOW_THREADS
2811 r = SSL_CTX_load_verify_locations(
2812 self->ctx,
2813 cafile_buf,
2814 capath_buf);
2815 PySSL_END_ALLOW_THREADS
2816 if (r != 1) {
2817 ok = 0;
2818 if (errno != 0) {
2819 ERR_clear_error();
2820 PyErr_SetFromErrno(PyExc_IOError);
2821 }
2822 else {
2823 _setSSLError(NULL, 0, __FILE__, __LINE__);
2824 }
2825 goto error;
2826 }
2827 }
2828 goto end;
2829
2830 error:
2831 ok = 0;
2832 end:
2833 Py_XDECREF(cafile_bytes);
2834 Py_XDECREF(capath_bytes);
2835 if (ok) {
2836 Py_RETURN_NONE;
2837 } else {
2838 return NULL;
2839 }
2840}
2841
2842static PyObject *
2843load_dh_params(PySSLContext *self, PyObject *filepath)
2844{
2845 BIO *bio;
2846 DH *dh;
2847 char *path = PyBytes_AsString(filepath);
2848 if (!path) {
2849 return NULL;
2850 }
2851
2852 bio = BIO_new_file(path, "r");
2853 if (bio == NULL) {
2854 ERR_clear_error();
2855 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2856 return NULL;
2857 }
2858 errno = 0;
2859 PySSL_BEGIN_ALLOW_THREADS
2860 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2861 BIO_free(bio);
2862 PySSL_END_ALLOW_THREADS
2863 if (dh == NULL) {
2864 if (errno != 0) {
2865 ERR_clear_error();
2866 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2867 }
2868 else {
2869 _setSSLError(NULL, 0, __FILE__, __LINE__);
2870 }
2871 return NULL;
2872 }
2873 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2874 _setSSLError(NULL, 0, __FILE__, __LINE__);
2875 DH_free(dh);
2876 Py_RETURN_NONE;
2877}
2878
2879static PyObject *
2880context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2881{
2882 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2883 PySocketSockObject *sock;
2884 int server_side = 0;
2885 char *hostname = NULL;
2886 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2887
2888 /* server_hostname is either None (or absent), or to be encoded
2889 using the idna encoding. */
2890 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2891 PySocketModule.Sock_Type,
2892 &sock, &server_side,
2893 Py_TYPE(Py_None), &hostname_obj,
2894 &ssl_sock)) {
2895 PyErr_Clear();
2896 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2897 PySocketModule.Sock_Type,
2898 &sock, &server_side,
2899 "idna", &hostname, &ssl_sock))
2900 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002901 }
2902
2903 res = (PyObject *) newPySSLSocket(self, sock, server_side,
2904 hostname, ssl_sock);
2905 if (hostname != NULL)
2906 PyMem_Free(hostname);
2907 return res;
2908}
2909
2910static PyObject *
2911session_stats(PySSLContext *self, PyObject *unused)
2912{
2913 int r;
2914 PyObject *value, *stats = PyDict_New();
2915 if (!stats)
2916 return NULL;
2917
2918#define ADD_STATS(SSL_NAME, KEY_NAME) \
2919 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2920 if (value == NULL) \
2921 goto error; \
2922 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2923 Py_DECREF(value); \
2924 if (r < 0) \
2925 goto error;
2926
2927 ADD_STATS(number, "number");
2928 ADD_STATS(connect, "connect");
2929 ADD_STATS(connect_good, "connect_good");
2930 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2931 ADD_STATS(accept, "accept");
2932 ADD_STATS(accept_good, "accept_good");
2933 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2934 ADD_STATS(accept, "accept");
2935 ADD_STATS(hits, "hits");
2936 ADD_STATS(misses, "misses");
2937 ADD_STATS(timeouts, "timeouts");
2938 ADD_STATS(cache_full, "cache_full");
2939
2940#undef ADD_STATS
2941
2942 return stats;
2943
2944error:
2945 Py_DECREF(stats);
2946 return NULL;
2947}
2948
2949static PyObject *
2950set_default_verify_paths(PySSLContext *self, PyObject *unused)
2951{
2952 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2953 _setSSLError(NULL, 0, __FILE__, __LINE__);
2954 return NULL;
2955 }
2956 Py_RETURN_NONE;
2957}
2958
2959#ifndef OPENSSL_NO_ECDH
2960static PyObject *
2961set_ecdh_curve(PySSLContext *self, PyObject *name)
2962{
2963 char *name_bytes;
2964 int nid;
2965 EC_KEY *key;
2966
2967 name_bytes = PyBytes_AsString(name);
2968 if (!name_bytes) {
2969 return NULL;
2970 }
2971 nid = OBJ_sn2nid(name_bytes);
2972 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002973 PyObject *r = PyObject_Repr(name);
2974 if (!r)
2975 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002976 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002977 "unknown elliptic curve name %s", PyString_AS_STRING(r));
2978 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002979 return NULL;
2980 }
2981 key = EC_KEY_new_by_curve_name(nid);
2982 if (key == NULL) {
2983 _setSSLError(NULL, 0, __FILE__, __LINE__);
2984 return NULL;
2985 }
2986 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2987 EC_KEY_free(key);
2988 Py_RETURN_NONE;
2989}
2990#endif
2991
2992#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
2993static int
2994_servername_callback(SSL *s, int *al, void *args)
2995{
2996 int ret;
2997 PySSLContext *ssl_ctx = (PySSLContext *) args;
2998 PySSLSocket *ssl;
2999 PyObject *servername_o;
3000 PyObject *servername_idna;
3001 PyObject *result;
3002 /* The high-level ssl.SSLSocket object */
3003 PyObject *ssl_socket;
3004 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3005#ifdef WITH_THREAD
3006 PyGILState_STATE gstate = PyGILState_Ensure();
3007#endif
3008
3009 if (ssl_ctx->set_hostname == NULL) {
3010 /* remove race condition in this the call back while if removing the
3011 * callback is in progress */
3012#ifdef WITH_THREAD
3013 PyGILState_Release(gstate);
3014#endif
3015 return SSL_TLSEXT_ERR_OK;
3016 }
3017
3018 ssl = SSL_get_app_data(s);
3019 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003020 if (ssl->ssl_sock == NULL) {
3021 ssl_socket = Py_None;
3022 } else {
3023 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3024 Py_INCREF(ssl_socket);
3025 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003026 if (ssl_socket == Py_None) {
3027 goto error;
3028 }
3029
3030 if (servername == NULL) {
3031 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3032 Py_None, ssl_ctx, NULL);
3033 }
3034 else {
3035 servername_o = PyBytes_FromString(servername);
3036 if (servername_o == NULL) {
3037 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3038 goto error;
3039 }
3040 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3041 if (servername_idna == NULL) {
3042 PyErr_WriteUnraisable(servername_o);
3043 Py_DECREF(servername_o);
3044 goto error;
3045 }
3046 Py_DECREF(servername_o);
3047 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3048 servername_idna, ssl_ctx, NULL);
3049 Py_DECREF(servername_idna);
3050 }
3051 Py_DECREF(ssl_socket);
3052
3053 if (result == NULL) {
3054 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3055 *al = SSL_AD_HANDSHAKE_FAILURE;
3056 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3057 }
3058 else {
3059 if (result != Py_None) {
3060 *al = (int) PyLong_AsLong(result);
3061 if (PyErr_Occurred()) {
3062 PyErr_WriteUnraisable(result);
3063 *al = SSL_AD_INTERNAL_ERROR;
3064 }
3065 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3066 }
3067 else {
3068 ret = SSL_TLSEXT_ERR_OK;
3069 }
3070 Py_DECREF(result);
3071 }
3072
3073#ifdef WITH_THREAD
3074 PyGILState_Release(gstate);
3075#endif
3076 return ret;
3077
3078error:
3079 Py_DECREF(ssl_socket);
3080 *al = SSL_AD_INTERNAL_ERROR;
3081 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3082#ifdef WITH_THREAD
3083 PyGILState_Release(gstate);
3084#endif
3085 return ret;
3086}
3087#endif
3088
3089PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3090"set_servername_callback(method)\n\
3091\n\
3092This sets a callback that will be called when a server name is provided by\n\
3093the SSL/TLS client in the SNI extension.\n\
3094\n\
3095If the argument is None then the callback is disabled. The method is called\n\
3096with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3097See RFC 6066 for details of the SNI extension.");
3098
3099static PyObject *
3100set_servername_callback(PySSLContext *self, PyObject *args)
3101{
3102#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3103 PyObject *cb;
3104
3105 if (!PyArg_ParseTuple(args, "O", &cb))
3106 return NULL;
3107
3108 Py_CLEAR(self->set_hostname);
3109 if (cb == Py_None) {
3110 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3111 }
3112 else {
3113 if (!PyCallable_Check(cb)) {
3114 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3115 PyErr_SetString(PyExc_TypeError,
3116 "not a callable object");
3117 return NULL;
3118 }
3119 Py_INCREF(cb);
3120 self->set_hostname = cb;
3121 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3122 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3123 }
3124 Py_RETURN_NONE;
3125#else
3126 PyErr_SetString(PyExc_NotImplementedError,
3127 "The TLS extension servername callback, "
3128 "SSL_CTX_set_tlsext_servername_callback, "
3129 "is not in the current OpenSSL library.");
3130 return NULL;
3131#endif
3132}
3133
3134PyDoc_STRVAR(PySSL_get_stats_doc,
3135"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3136\n\
3137Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3138CA extension and certificate revocation lists inside the context's cert\n\
3139store.\n\
3140NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3141been used at least once.");
3142
3143static PyObject *
3144cert_store_stats(PySSLContext *self)
3145{
3146 X509_STORE *store;
3147 X509_OBJECT *obj;
3148 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3149
3150 store = SSL_CTX_get_cert_store(self->ctx);
3151 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3152 obj = sk_X509_OBJECT_value(store->objs, i);
3153 switch (obj->type) {
3154 case X509_LU_X509:
3155 x509++;
3156 if (X509_check_ca(obj->data.x509)) {
3157 ca++;
3158 }
3159 break;
3160 case X509_LU_CRL:
3161 crl++;
3162 break;
3163 case X509_LU_PKEY:
3164 pkey++;
3165 break;
3166 default:
3167 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3168 * As far as I can tell they are internal states and never
3169 * stored in a cert store */
3170 break;
3171 }
3172 }
3173 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3174 "x509_ca", ca);
3175}
3176
3177PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3178"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3179\n\
3180Returns a list of dicts with information of loaded CA certs. If the\n\
3181optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3182NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3183been used at least once.");
3184
3185static PyObject *
3186get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3187{
3188 char *kwlist[] = {"binary_form", NULL};
3189 X509_STORE *store;
3190 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3191 int i;
3192 int binary_mode = 0;
3193
3194 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3195 kwlist, &py_binary_mode)) {
3196 return NULL;
3197 }
3198 binary_mode = PyObject_IsTrue(py_binary_mode);
3199 if (binary_mode < 0) {
3200 return NULL;
3201 }
3202
3203 if ((rlist = PyList_New(0)) == NULL) {
3204 return NULL;
3205 }
3206
3207 store = SSL_CTX_get_cert_store(self->ctx);
3208 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3209 X509_OBJECT *obj;
3210 X509 *cert;
3211
3212 obj = sk_X509_OBJECT_value(store->objs, i);
3213 if (obj->type != X509_LU_X509) {
3214 /* not a x509 cert */
3215 continue;
3216 }
3217 /* CA for any purpose */
3218 cert = obj->data.x509;
3219 if (!X509_check_ca(cert)) {
3220 continue;
3221 }
3222 if (binary_mode) {
3223 ci = _certificate_to_der(cert);
3224 } else {
3225 ci = _decode_certificate(cert);
3226 }
3227 if (ci == NULL) {
3228 goto error;
3229 }
3230 if (PyList_Append(rlist, ci) == -1) {
3231 goto error;
3232 }
3233 Py_CLEAR(ci);
3234 }
3235 return rlist;
3236
3237 error:
3238 Py_XDECREF(ci);
3239 Py_XDECREF(rlist);
3240 return NULL;
3241}
3242
3243
3244static PyGetSetDef context_getsetlist[] = {
3245 {"check_hostname", (getter) get_check_hostname,
3246 (setter) set_check_hostname, NULL},
3247 {"options", (getter) get_options,
3248 (setter) set_options, NULL},
3249#ifdef HAVE_OPENSSL_VERIFY_PARAM
3250 {"verify_flags", (getter) get_verify_flags,
3251 (setter) set_verify_flags, NULL},
3252#endif
3253 {"verify_mode", (getter) get_verify_mode,
3254 (setter) set_verify_mode, NULL},
3255 {NULL}, /* sentinel */
3256};
3257
3258static struct PyMethodDef context_methods[] = {
3259 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3260 METH_VARARGS | METH_KEYWORDS, NULL},
3261 {"set_ciphers", (PyCFunction) set_ciphers,
3262 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003263 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3264 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003265 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3266 METH_VARARGS, NULL},
3267 {"load_cert_chain", (PyCFunction) load_cert_chain,
3268 METH_VARARGS | METH_KEYWORDS, NULL},
3269 {"load_dh_params", (PyCFunction) load_dh_params,
3270 METH_O, NULL},
3271 {"load_verify_locations", (PyCFunction) load_verify_locations,
3272 METH_VARARGS | METH_KEYWORDS, NULL},
3273 {"session_stats", (PyCFunction) session_stats,
3274 METH_NOARGS, NULL},
3275 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3276 METH_NOARGS, NULL},
3277#ifndef OPENSSL_NO_ECDH
3278 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3279 METH_O, NULL},
3280#endif
3281 {"set_servername_callback", (PyCFunction) set_servername_callback,
3282 METH_VARARGS, PySSL_set_servername_callback_doc},
3283 {"cert_store_stats", (PyCFunction) cert_store_stats,
3284 METH_NOARGS, PySSL_get_stats_doc},
3285 {"get_ca_certs", (PyCFunction) get_ca_certs,
3286 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3287 {NULL, NULL} /* sentinel */
3288};
3289
3290static PyTypeObject PySSLContext_Type = {
3291 PyVarObject_HEAD_INIT(NULL, 0)
3292 "_ssl._SSLContext", /*tp_name*/
3293 sizeof(PySSLContext), /*tp_basicsize*/
3294 0, /*tp_itemsize*/
3295 (destructor)context_dealloc, /*tp_dealloc*/
3296 0, /*tp_print*/
3297 0, /*tp_getattr*/
3298 0, /*tp_setattr*/
3299 0, /*tp_reserved*/
3300 0, /*tp_repr*/
3301 0, /*tp_as_number*/
3302 0, /*tp_as_sequence*/
3303 0, /*tp_as_mapping*/
3304 0, /*tp_hash*/
3305 0, /*tp_call*/
3306 0, /*tp_str*/
3307 0, /*tp_getattro*/
3308 0, /*tp_setattro*/
3309 0, /*tp_as_buffer*/
3310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3311 0, /*tp_doc*/
3312 (traverseproc) context_traverse, /*tp_traverse*/
3313 (inquiry) context_clear, /*tp_clear*/
3314 0, /*tp_richcompare*/
3315 0, /*tp_weaklistoffset*/
3316 0, /*tp_iter*/
3317 0, /*tp_iternext*/
3318 context_methods, /*tp_methods*/
3319 0, /*tp_members*/
3320 context_getsetlist, /*tp_getset*/
3321 0, /*tp_base*/
3322 0, /*tp_dict*/
3323 0, /*tp_descr_get*/
3324 0, /*tp_descr_set*/
3325 0, /*tp_dictoffset*/
3326 0, /*tp_init*/
3327 0, /*tp_alloc*/
3328 context_new, /*tp_new*/
3329};
3330
3331
3332
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003333#ifdef HAVE_OPENSSL_RAND
3334
3335/* helper routines for seeding the SSL PRNG */
3336static PyObject *
3337PySSL_RAND_add(PyObject *self, PyObject *args)
3338{
3339 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003340 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003341 double entropy;
3342
3343 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003344 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003345 do {
3346 if (len >= INT_MAX) {
3347 written = INT_MAX;
3348 } else {
3349 written = len;
3350 }
3351 RAND_add(buf, (int)written, entropy);
3352 buf += written;
3353 len -= written;
3354 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003355 Py_INCREF(Py_None);
3356 return Py_None;
3357}
3358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003359PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003360"RAND_add(string, entropy)\n\
3361\n\
3362Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003363bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003364
3365static PyObject *
3366PySSL_RAND_status(PyObject *self)
3367{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003368 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003369}
3370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003371PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003372"RAND_status() -> 0 or 1\n\
3373\n\
3374Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3375It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003376using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003377
Victor Stinner7c906672015-01-06 13:53:37 +01003378#endif /* HAVE_OPENSSL_RAND */
3379
3380
3381#ifdef HAVE_RAND_EGD
3382
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003383static PyObject *
3384PySSL_RAND_egd(PyObject *self, PyObject *arg)
3385{
3386 int bytes;
3387
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003388 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003389 return PyErr_Format(PyExc_TypeError,
3390 "RAND_egd() expected string, found %s",
3391 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003392 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003393 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003394 PyErr_SetString(PySSLErrorObject,
3395 "EGD connection failed or EGD did not return "
3396 "enough data to seed the PRNG");
3397 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003398 }
3399 return PyInt_FromLong(bytes);
3400}
3401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003402PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003403"RAND_egd(path) -> bytes\n\
3404\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003405Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3406Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003407fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003408
Victor Stinner7c906672015-01-06 13:53:37 +01003409#endif /* HAVE_RAND_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003410
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003411
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003412PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3413"get_default_verify_paths() -> tuple\n\
3414\n\
3415Return search paths and environment vars that are used by SSLContext's\n\
3416set_default_verify_paths() to load default CAs. The values are\n\
3417'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3418
3419static PyObject *
3420PySSL_get_default_verify_paths(PyObject *self)
3421{
3422 PyObject *ofile_env = NULL;
3423 PyObject *ofile = NULL;
3424 PyObject *odir_env = NULL;
3425 PyObject *odir = NULL;
3426
Benjamin Peterson65192c12015-07-18 10:59:13 -07003427#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003428 const char *tmp = (info); \
3429 target = NULL; \
3430 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3431 else { target = PyBytes_FromString(tmp); } \
3432 if (!target) goto error; \
Benjamin Peterson65192c12015-07-18 10:59:13 -07003433 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003434
Benjamin Peterson65192c12015-07-18 10:59:13 -07003435 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3436 CONVERT(X509_get_default_cert_file(), ofile);
3437 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3438 CONVERT(X509_get_default_cert_dir(), odir);
3439#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003440
3441 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3442
3443 error:
3444 Py_XDECREF(ofile_env);
3445 Py_XDECREF(ofile);
3446 Py_XDECREF(odir_env);
3447 Py_XDECREF(odir);
3448 return NULL;
3449}
3450
3451static PyObject*
3452asn1obj2py(ASN1_OBJECT *obj)
3453{
3454 int nid;
3455 const char *ln, *sn;
3456 char buf[100];
3457 Py_ssize_t buflen;
3458
3459 nid = OBJ_obj2nid(obj);
3460 if (nid == NID_undef) {
3461 PyErr_Format(PyExc_ValueError, "Unknown object");
3462 return NULL;
3463 }
3464 sn = OBJ_nid2sn(nid);
3465 ln = OBJ_nid2ln(nid);
3466 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3467 if (buflen < 0) {
3468 _setSSLError(NULL, 0, __FILE__, __LINE__);
3469 return NULL;
3470 }
3471 if (buflen) {
3472 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3473 } else {
3474 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3475 }
3476}
3477
3478PyDoc_STRVAR(PySSL_txt2obj_doc,
3479"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3480\n\
3481Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3482objects are looked up by OID. With name=True short and long name are also\n\
3483matched.");
3484
3485static PyObject*
3486PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3487{
3488 char *kwlist[] = {"txt", "name", NULL};
3489 PyObject *result = NULL;
3490 char *txt;
3491 PyObject *pyname = Py_None;
3492 int name = 0;
3493 ASN1_OBJECT *obj;
3494
3495 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3496 kwlist, &txt, &pyname)) {
3497 return NULL;
3498 }
3499 name = PyObject_IsTrue(pyname);
3500 if (name < 0)
3501 return NULL;
3502 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3503 if (obj == NULL) {
3504 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3505 return NULL;
3506 }
3507 result = asn1obj2py(obj);
3508 ASN1_OBJECT_free(obj);
3509 return result;
3510}
3511
3512PyDoc_STRVAR(PySSL_nid2obj_doc,
3513"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3514\n\
3515Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3516
3517static PyObject*
3518PySSL_nid2obj(PyObject *self, PyObject *args)
3519{
3520 PyObject *result = NULL;
3521 int nid;
3522 ASN1_OBJECT *obj;
3523
3524 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3525 return NULL;
3526 }
3527 if (nid < NID_undef) {
3528 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3529 return NULL;
3530 }
3531 obj = OBJ_nid2obj(nid);
3532 if (obj == NULL) {
3533 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3534 return NULL;
3535 }
3536 result = asn1obj2py(obj);
3537 ASN1_OBJECT_free(obj);
3538 return result;
3539}
3540
3541#ifdef _MSC_VER
3542
3543static PyObject*
3544certEncodingType(DWORD encodingType)
3545{
3546 static PyObject *x509_asn = NULL;
3547 static PyObject *pkcs_7_asn = NULL;
3548
3549 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003550 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003551 if (x509_asn == NULL)
3552 return NULL;
3553 }
3554 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003555 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003556 if (pkcs_7_asn == NULL)
3557 return NULL;
3558 }
3559 switch(encodingType) {
3560 case X509_ASN_ENCODING:
3561 Py_INCREF(x509_asn);
3562 return x509_asn;
3563 case PKCS_7_ASN_ENCODING:
3564 Py_INCREF(pkcs_7_asn);
3565 return pkcs_7_asn;
3566 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003567 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003568 }
3569}
3570
3571static PyObject*
3572parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3573{
3574 CERT_ENHKEY_USAGE *usage;
3575 DWORD size, error, i;
3576 PyObject *retval;
3577
3578 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3579 error = GetLastError();
3580 if (error == CRYPT_E_NOT_FOUND) {
3581 Py_RETURN_TRUE;
3582 }
3583 return PyErr_SetFromWindowsErr(error);
3584 }
3585
3586 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3587 if (usage == NULL) {
3588 return PyErr_NoMemory();
3589 }
3590
3591 /* Now get the actual enhanced usage property */
3592 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3593 PyMem_Free(usage);
3594 error = GetLastError();
3595 if (error == CRYPT_E_NOT_FOUND) {
3596 Py_RETURN_TRUE;
3597 }
3598 return PyErr_SetFromWindowsErr(error);
3599 }
3600 retval = PySet_New(NULL);
3601 if (retval == NULL) {
3602 goto error;
3603 }
3604 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3605 if (usage->rgpszUsageIdentifier[i]) {
3606 PyObject *oid;
3607 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003608 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003609 if (oid == NULL) {
3610 Py_CLEAR(retval);
3611 goto error;
3612 }
3613 err = PySet_Add(retval, oid);
3614 Py_DECREF(oid);
3615 if (err == -1) {
3616 Py_CLEAR(retval);
3617 goto error;
3618 }
3619 }
3620 }
3621 error:
3622 PyMem_Free(usage);
3623 return retval;
3624}
3625
3626PyDoc_STRVAR(PySSL_enum_certificates_doc,
3627"enum_certificates(store_name) -> []\n\
3628\n\
3629Retrieve certificates from Windows' cert store. store_name may be one of\n\
3630'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3631The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3632encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3633PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3634boolean True.");
3635
3636static PyObject *
3637PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3638{
3639 char *kwlist[] = {"store_name", NULL};
3640 char *store_name;
3641 HCERTSTORE hStore = NULL;
3642 PCCERT_CONTEXT pCertCtx = NULL;
3643 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3644 PyObject *result = NULL;
3645
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003646 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003647 kwlist, &store_name)) {
3648 return NULL;
3649 }
3650 result = PyList_New(0);
3651 if (result == NULL) {
3652 return NULL;
3653 }
3654 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3655 if (hStore == NULL) {
3656 Py_DECREF(result);
3657 return PyErr_SetFromWindowsErr(GetLastError());
3658 }
3659
3660 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3661 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3662 pCertCtx->cbCertEncoded);
3663 if (!cert) {
3664 Py_CLEAR(result);
3665 break;
3666 }
3667 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3668 Py_CLEAR(result);
3669 break;
3670 }
3671 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3672 if (keyusage == Py_True) {
3673 Py_DECREF(keyusage);
3674 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3675 }
3676 if (keyusage == NULL) {
3677 Py_CLEAR(result);
3678 break;
3679 }
3680 if ((tup = PyTuple_New(3)) == NULL) {
3681 Py_CLEAR(result);
3682 break;
3683 }
3684 PyTuple_SET_ITEM(tup, 0, cert);
3685 cert = NULL;
3686 PyTuple_SET_ITEM(tup, 1, enc);
3687 enc = NULL;
3688 PyTuple_SET_ITEM(tup, 2, keyusage);
3689 keyusage = NULL;
3690 if (PyList_Append(result, tup) < 0) {
3691 Py_CLEAR(result);
3692 break;
3693 }
3694 Py_CLEAR(tup);
3695 }
3696 if (pCertCtx) {
3697 /* loop ended with an error, need to clean up context manually */
3698 CertFreeCertificateContext(pCertCtx);
3699 }
3700
3701 /* In error cases cert, enc and tup may not be NULL */
3702 Py_XDECREF(cert);
3703 Py_XDECREF(enc);
3704 Py_XDECREF(keyusage);
3705 Py_XDECREF(tup);
3706
3707 if (!CertCloseStore(hStore, 0)) {
3708 /* This error case might shadow another exception.*/
3709 Py_XDECREF(result);
3710 return PyErr_SetFromWindowsErr(GetLastError());
3711 }
3712 return result;
3713}
3714
3715PyDoc_STRVAR(PySSL_enum_crls_doc,
3716"enum_crls(store_name) -> []\n\
3717\n\
3718Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3719'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3720The function returns a list of (bytes, encoding_type) tuples. The\n\
3721encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3722PKCS_7_ASN_ENCODING.");
3723
3724static PyObject *
3725PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3726{
3727 char *kwlist[] = {"store_name", NULL};
3728 char *store_name;
3729 HCERTSTORE hStore = NULL;
3730 PCCRL_CONTEXT pCrlCtx = NULL;
3731 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3732 PyObject *result = NULL;
3733
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003734 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003735 kwlist, &store_name)) {
3736 return NULL;
3737 }
3738 result = PyList_New(0);
3739 if (result == NULL) {
3740 return NULL;
3741 }
3742 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3743 if (hStore == NULL) {
3744 Py_DECREF(result);
3745 return PyErr_SetFromWindowsErr(GetLastError());
3746 }
3747
3748 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3749 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3750 pCrlCtx->cbCrlEncoded);
3751 if (!crl) {
3752 Py_CLEAR(result);
3753 break;
3754 }
3755 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3756 Py_CLEAR(result);
3757 break;
3758 }
3759 if ((tup = PyTuple_New(2)) == NULL) {
3760 Py_CLEAR(result);
3761 break;
3762 }
3763 PyTuple_SET_ITEM(tup, 0, crl);
3764 crl = NULL;
3765 PyTuple_SET_ITEM(tup, 1, enc);
3766 enc = NULL;
3767
3768 if (PyList_Append(result, tup) < 0) {
3769 Py_CLEAR(result);
3770 break;
3771 }
3772 Py_CLEAR(tup);
3773 }
3774 if (pCrlCtx) {
3775 /* loop ended with an error, need to clean up context manually */
3776 CertFreeCRLContext(pCrlCtx);
3777 }
3778
3779 /* In error cases cert, enc and tup may not be NULL */
3780 Py_XDECREF(crl);
3781 Py_XDECREF(enc);
3782 Py_XDECREF(tup);
3783
3784 if (!CertCloseStore(hStore, 0)) {
3785 /* This error case might shadow another exception.*/
3786 Py_XDECREF(result);
3787 return PyErr_SetFromWindowsErr(GetLastError());
3788 }
3789 return result;
3790}
3791
3792#endif /* _MSC_VER */
3793
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003794/* List of functions exported by this module. */
3795
3796static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003797 {"_test_decode_cert", PySSL_test_decode_certificate,
3798 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003799#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003800 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3801 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003802 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3803 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003804#endif
Victor Stinner7c906672015-01-06 13:53:37 +01003805#ifdef HAVE_RAND_EGD
3806 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3807 PySSL_RAND_egd_doc},
3808#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003809 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3810 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3811#ifdef _MSC_VER
3812 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3813 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3814 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3815 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3816#endif
3817 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3818 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3819 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3820 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003821 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003822};
3823
3824
Bill Janssen98d19da2007-09-10 21:51:02 +00003825#ifdef WITH_THREAD
3826
3827/* an implementation of OpenSSL threading operations in terms
3828 of the Python C thread library */
3829
3830static PyThread_type_lock *_ssl_locks = NULL;
3831
Christian Heimes10107812013-08-19 17:36:29 +02003832#if OPENSSL_VERSION_NUMBER >= 0x10000000
3833/* use new CRYPTO_THREADID API. */
3834static void
3835_ssl_threadid_callback(CRYPTO_THREADID *id)
3836{
3837 CRYPTO_THREADID_set_numeric(id,
3838 (unsigned long)PyThread_get_thread_ident());
3839}
3840#else
3841/* deprecated CRYPTO_set_id_callback() API. */
3842static unsigned long
3843_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003844 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003845}
Christian Heimes10107812013-08-19 17:36:29 +02003846#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003847
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003848static void _ssl_thread_locking_function
3849 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003850 /* this function is needed to perform locking on shared data
3851 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003852 structures that will be implicitly shared whenever multiple
3853 threads use OpenSSL.) Multi-threaded applications will
3854 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003855
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003856 locking_function() must be able to handle up to
3857 CRYPTO_num_locks() different mutex locks. It sets the n-th
3858 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003859
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003860 file and line are the file number of the function setting the
3861 lock. They can be useful for debugging.
3862 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003863
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003864 if ((_ssl_locks == NULL) ||
3865 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3866 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003867
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003868 if (mode & CRYPTO_LOCK) {
3869 PyThread_acquire_lock(_ssl_locks[n], 1);
3870 } else {
3871 PyThread_release_lock(_ssl_locks[n]);
3872 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003873}
3874
3875static int _setup_ssl_threads(void) {
3876
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003877 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003878
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003879 if (_ssl_locks == NULL) {
3880 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003881 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3882 if (_ssl_locks == NULL) {
3883 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003884 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003885 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003886 memset(_ssl_locks, 0,
3887 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003888 for (i = 0; i < _ssl_locks_count; i++) {
3889 _ssl_locks[i] = PyThread_allocate_lock();
3890 if (_ssl_locks[i] == NULL) {
3891 unsigned int j;
3892 for (j = 0; j < i; j++) {
3893 PyThread_free_lock(_ssl_locks[j]);
3894 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003895 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003896 return 0;
3897 }
3898 }
3899 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02003900#if OPENSSL_VERSION_NUMBER >= 0x10000000
3901 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3902#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003903 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02003904#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003905 }
3906 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00003907}
3908
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003909#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00003910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003911PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003912"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003913for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003914
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003915
3916
3917
3918static void
3919parse_openssl_version(unsigned long libver,
3920 unsigned int *major, unsigned int *minor,
3921 unsigned int *fix, unsigned int *patch,
3922 unsigned int *status)
3923{
3924 *status = libver & 0xF;
3925 libver >>= 4;
3926 *patch = libver & 0xFF;
3927 libver >>= 8;
3928 *fix = libver & 0xFF;
3929 libver >>= 8;
3930 *minor = libver & 0xFF;
3931 libver >>= 8;
3932 *major = libver & 0xFF;
3933}
3934
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003935PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003936init_ssl(void)
3937{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003938 PyObject *m, *d, *r;
3939 unsigned long libver;
3940 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003941 struct py_ssl_error_code *errcode;
3942 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003943
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003944 if (PyType_Ready(&PySSLContext_Type) < 0)
3945 return;
3946 if (PyType_Ready(&PySSLSocket_Type) < 0)
3947 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003948
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003949 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
3950 if (m == NULL)
3951 return;
3952 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003953
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003954 /* Load _socket module and its C API */
3955 if (PySocketModule_ImportModuleAndAPI())
3956 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003957
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003958 /* Init OpenSSL */
3959 SSL_load_error_strings();
3960 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00003961#ifdef WITH_THREAD
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003962 /* note that this will start threading if not already started */
3963 if (!_setup_ssl_threads()) {
3964 return;
3965 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003966#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003967 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003968
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003969 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003970 PySSLErrorObject = PyErr_NewExceptionWithDoc(
3971 "ssl.SSLError", SSLError_doc,
3972 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003973 if (PySSLErrorObject == NULL)
3974 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003975 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
3976
3977 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3978 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3979 PySSLErrorObject, NULL);
3980 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3981 "ssl.SSLWantReadError", SSLWantReadError_doc,
3982 PySSLErrorObject, NULL);
3983 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3984 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3985 PySSLErrorObject, NULL);
3986 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3987 "ssl.SSLSyscallError", SSLSyscallError_doc,
3988 PySSLErrorObject, NULL);
3989 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3990 "ssl.SSLEOFError", SSLEOFError_doc,
3991 PySSLErrorObject, NULL);
3992 if (PySSLZeroReturnErrorObject == NULL
3993 || PySSLWantReadErrorObject == NULL
3994 || PySSLWantWriteErrorObject == NULL
3995 || PySSLSyscallErrorObject == NULL
3996 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003997 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003998
3999 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4000 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4001 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4002 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4003 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4004
4005 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4006 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4007 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4008 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4009 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4010 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4011 return;
4012 if (PyDict_SetItemString(d, "_SSLContext",
4013 (PyObject *)&PySSLContext_Type) != 0)
4014 return;
4015 if (PyDict_SetItemString(d, "_SSLSocket",
4016 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004017 return;
4018 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4019 PY_SSL_ERROR_ZERO_RETURN);
4020 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4021 PY_SSL_ERROR_WANT_READ);
4022 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4023 PY_SSL_ERROR_WANT_WRITE);
4024 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4025 PY_SSL_ERROR_WANT_X509_LOOKUP);
4026 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4027 PY_SSL_ERROR_SYSCALL);
4028 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4029 PY_SSL_ERROR_SSL);
4030 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4031 PY_SSL_ERROR_WANT_CONNECT);
4032 /* non ssl.h errorcodes */
4033 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4034 PY_SSL_ERROR_EOF);
4035 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4036 PY_SSL_ERROR_INVALID_ERROR_CODE);
4037 /* cert requirements */
4038 PyModule_AddIntConstant(m, "CERT_NONE",
4039 PY_SSL_CERT_NONE);
4040 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4041 PY_SSL_CERT_OPTIONAL);
4042 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4043 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004044 /* CRL verification for verification_flags */
4045 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4046 0);
4047 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4048 X509_V_FLAG_CRL_CHECK);
4049 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4050 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4051 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4052 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004053#ifdef X509_V_FLAG_TRUSTED_FIRST
4054 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4055 X509_V_FLAG_TRUSTED_FIRST);
4056#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004057
4058 /* Alert Descriptions from ssl.h */
4059 /* note RESERVED constants no longer intended for use have been removed */
4060 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4061
4062#define ADD_AD_CONSTANT(s) \
4063 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4064 SSL_AD_##s)
4065
4066 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4067 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4068 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4069 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4070 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4071 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4072 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4073 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4074 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4075 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4076 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4077 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4078 ADD_AD_CONSTANT(UNKNOWN_CA);
4079 ADD_AD_CONSTANT(ACCESS_DENIED);
4080 ADD_AD_CONSTANT(DECODE_ERROR);
4081 ADD_AD_CONSTANT(DECRYPT_ERROR);
4082 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4083 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4084 ADD_AD_CONSTANT(INTERNAL_ERROR);
4085 ADD_AD_CONSTANT(USER_CANCELLED);
4086 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4087 /* Not all constants are in old OpenSSL versions */
4088#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4089 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4090#endif
4091#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4092 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4093#endif
4094#ifdef SSL_AD_UNRECOGNIZED_NAME
4095 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4096#endif
4097#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4098 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4099#endif
4100#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4101 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4102#endif
4103#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4104 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4105#endif
4106
4107#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004108
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004109 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004110#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004111 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4112 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004113#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004114#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004115 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4116 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004117#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004118 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4119 PY_SSL_VERSION_SSL23);
4120 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4121 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004122#if HAVE_TLSv1_2
4123 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4124 PY_SSL_VERSION_TLS1_1);
4125 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4126 PY_SSL_VERSION_TLS1_2);
4127#endif
4128
4129 /* protocol options */
4130 PyModule_AddIntConstant(m, "OP_ALL",
4131 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4132 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4133 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4134 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4135#if HAVE_TLSv1_2
4136 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4137 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4138#endif
4139 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4140 SSL_OP_CIPHER_SERVER_PREFERENCE);
4141 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4142#ifdef SSL_OP_SINGLE_ECDH_USE
4143 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4144#endif
4145#ifdef SSL_OP_NO_COMPRESSION
4146 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4147 SSL_OP_NO_COMPRESSION);
4148#endif
4149
4150#if HAVE_SNI
4151 r = Py_True;
4152#else
4153 r = Py_False;
4154#endif
4155 Py_INCREF(r);
4156 PyModule_AddObject(m, "HAS_SNI", r);
4157
4158#if HAVE_OPENSSL_FINISHED
4159 r = Py_True;
4160#else
4161 r = Py_False;
4162#endif
4163 Py_INCREF(r);
4164 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4165
4166#ifdef OPENSSL_NO_ECDH
4167 r = Py_False;
4168#else
4169 r = Py_True;
4170#endif
4171 Py_INCREF(r);
4172 PyModule_AddObject(m, "HAS_ECDH", r);
4173
4174#ifdef OPENSSL_NPN_NEGOTIATED
4175 r = Py_True;
4176#else
4177 r = Py_False;
4178#endif
4179 Py_INCREF(r);
4180 PyModule_AddObject(m, "HAS_NPN", r);
4181
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004182#ifdef HAVE_ALPN
4183 r = Py_True;
4184#else
4185 r = Py_False;
4186#endif
4187 Py_INCREF(r);
4188 PyModule_AddObject(m, "HAS_ALPN", r);
4189
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004190 /* Mappings for error codes */
4191 err_codes_to_names = PyDict_New();
4192 err_names_to_codes = PyDict_New();
4193 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4194 return;
4195 errcode = error_codes;
4196 while (errcode->mnemonic != NULL) {
4197 PyObject *mnemo, *key;
4198 mnemo = PyUnicode_FromString(errcode->mnemonic);
4199 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4200 if (mnemo == NULL || key == NULL)
4201 return;
4202 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4203 return;
4204 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4205 return;
4206 Py_DECREF(key);
4207 Py_DECREF(mnemo);
4208 errcode++;
4209 }
4210 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4211 return;
4212 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4213 return;
4214
4215 lib_codes_to_names = PyDict_New();
4216 if (lib_codes_to_names == NULL)
4217 return;
4218 libcode = library_codes;
4219 while (libcode->library != NULL) {
4220 PyObject *mnemo, *key;
4221 key = PyLong_FromLong(libcode->code);
4222 mnemo = PyUnicode_FromString(libcode->library);
4223 if (key == NULL || mnemo == NULL)
4224 return;
4225 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4226 return;
4227 Py_DECREF(key);
4228 Py_DECREF(mnemo);
4229 libcode++;
4230 }
4231 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4232 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004233
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004234 /* OpenSSL version */
4235 /* SSLeay() gives us the version of the library linked against,
4236 which could be different from the headers version.
4237 */
4238 libver = SSLeay();
4239 r = PyLong_FromUnsignedLong(libver);
4240 if (r == NULL)
4241 return;
4242 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4243 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004244 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004245 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4246 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4247 return;
4248 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4249 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4250 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004251
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004252 libver = OPENSSL_VERSION_NUMBER;
4253 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4254 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4255 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4256 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004257}