blob: 4572751a851e8c7820bb5a528bb0bff9df7b2d96 [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);
Benjamin Petersonc5919362015-11-14 15:12:18 -0800968 if (info == NULL)
969 return Py_None;
970 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
971 AUTHORITY_INFO_ACCESS_free(info);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500972 return Py_None;
973 }
974
975 if ((lst = PyList_New(0)) == NULL) {
976 goto fail;
977 }
978
979 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
980 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
981 ASN1_IA5STRING *uri;
982
983 if ((OBJ_obj2nid(ad->method) != nid) ||
984 (ad->location->type != GEN_URI)) {
985 continue;
986 }
987 uri = ad->location->d.uniformResourceIdentifier;
988 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
989 uri->length);
990 if (ostr == NULL) {
991 goto fail;
992 }
993 result = PyList_Append(lst, ostr);
994 Py_DECREF(ostr);
995 if (result < 0) {
996 goto fail;
997 }
998 }
999 AUTHORITY_INFO_ACCESS_free(info);
1000
1001 /* convert to tuple or None */
1002 if (PyList_Size(lst) == 0) {
1003 Py_DECREF(lst);
1004 return Py_None;
1005 } else {
1006 PyObject *tup;
1007 tup = PyList_AsTuple(lst);
1008 Py_DECREF(lst);
1009 return tup;
1010 }
1011
1012 fail:
1013 AUTHORITY_INFO_ACCESS_free(info);
1014 Py_XDECREF(lst);
1015 return NULL;
1016}
1017
1018static PyObject *
1019_get_crl_dp(X509 *certificate) {
1020 STACK_OF(DIST_POINT) *dps;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001021 int i, j;
1022 PyObject *lst, *res = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001023
1024#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001025 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001026#else
1027 /* Calls x509v3_cache_extensions and sets up crldp */
1028 X509_check_ca(certificate);
1029 dps = certificate->crldp;
1030#endif
1031
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001032 if (dps == NULL)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001033 return Py_None;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001034
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001035 lst = PyList_New(0);
1036 if (lst == NULL)
1037 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001038
1039 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1040 DIST_POINT *dp;
1041 STACK_OF(GENERAL_NAME) *gns;
1042
1043 dp = sk_DIST_POINT_value(dps, i);
1044 gns = dp->distpoint->name.fullname;
1045
1046 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1047 GENERAL_NAME *gn;
1048 ASN1_IA5STRING *uri;
1049 PyObject *ouri;
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001050 int err;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001051
1052 gn = sk_GENERAL_NAME_value(gns, j);
1053 if (gn->type != GEN_URI) {
1054 continue;
1055 }
1056 uri = gn->d.uniformResourceIdentifier;
1057 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1058 uri->length);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001059 if (ouri == NULL)
1060 goto done;
1061
1062 err = PyList_Append(lst, ouri);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001063 Py_DECREF(ouri);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001064 if (err < 0)
1065 goto done;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001066 }
1067 }
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001068
1069 /* Convert to tuple. */
1070 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1071
1072 done:
1073 Py_XDECREF(lst);
1074#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersonb1c1e672015-11-14 00:09:22 -08001075 sk_DIST_POINT_free(dps);
Benjamin Peterson59d451d2015-11-11 22:07:38 -08001076#endif
1077 return res;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001078}
1079
1080static PyObject *
1081_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001082
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001083 PyObject *retval = NULL;
1084 BIO *biobuf = NULL;
1085 PyObject *peer;
1086 PyObject *peer_alt_names = NULL;
1087 PyObject *issuer;
1088 PyObject *version;
1089 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001090 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001091 ASN1_INTEGER *serialNumber;
1092 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001093 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001094 ASN1_TIME *notBefore, *notAfter;
1095 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001096
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001097 retval = PyDict_New();
1098 if (retval == NULL)
1099 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001100
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001101 peer = _create_tuple_for_X509_NAME(
1102 X509_get_subject_name(certificate));
1103 if (peer == NULL)
1104 goto fail0;
1105 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1106 Py_DECREF(peer);
1107 goto fail0;
1108 }
1109 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001110
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001111 issuer = _create_tuple_for_X509_NAME(
1112 X509_get_issuer_name(certificate));
1113 if (issuer == NULL)
1114 goto fail0;
1115 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001116 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001117 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001118 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001119 Py_DECREF(issuer);
1120
1121 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1122 if (version == NULL)
1123 goto fail0;
1124 if (PyDict_SetItemString(retval, "version", version) < 0) {
1125 Py_DECREF(version);
1126 goto fail0;
1127 }
1128 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001129
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001130 /* get a memory buffer */
1131 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001132
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001133 (void) BIO_reset(biobuf);
1134 serialNumber = X509_get_serialNumber(certificate);
1135 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1136 i2a_ASN1_INTEGER(biobuf, serialNumber);
1137 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1138 if (len < 0) {
1139 _setSSLError(NULL, 0, __FILE__, __LINE__);
1140 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001141 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001142 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1143 if (sn_obj == NULL)
1144 goto fail1;
1145 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1146 Py_DECREF(sn_obj);
1147 goto fail1;
1148 }
1149 Py_DECREF(sn_obj);
1150
1151 (void) BIO_reset(biobuf);
1152 notBefore = X509_get_notBefore(certificate);
1153 ASN1_TIME_print(biobuf, notBefore);
1154 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1155 if (len < 0) {
1156 _setSSLError(NULL, 0, __FILE__, __LINE__);
1157 goto fail1;
1158 }
1159 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1160 if (pnotBefore == NULL)
1161 goto fail1;
1162 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1163 Py_DECREF(pnotBefore);
1164 goto fail1;
1165 }
1166 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001167
1168 (void) BIO_reset(biobuf);
1169 notAfter = X509_get_notAfter(certificate);
1170 ASN1_TIME_print(biobuf, notAfter);
1171 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1172 if (len < 0) {
1173 _setSSLError(NULL, 0, __FILE__, __LINE__);
1174 goto fail1;
1175 }
1176 pnotAfter = PyString_FromStringAndSize(buf, len);
1177 if (pnotAfter == NULL)
1178 goto fail1;
1179 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1180 Py_DECREF(pnotAfter);
1181 goto fail1;
1182 }
1183 Py_DECREF(pnotAfter);
1184
1185 /* Now look for subjectAltName */
1186
1187 peer_alt_names = _get_peer_alt_names(certificate);
1188 if (peer_alt_names == NULL)
1189 goto fail1;
1190 else if (peer_alt_names != Py_None) {
1191 if (PyDict_SetItemString(retval, "subjectAltName",
1192 peer_alt_names) < 0) {
1193 Py_DECREF(peer_alt_names);
1194 goto fail1;
1195 }
1196 Py_DECREF(peer_alt_names);
1197 }
1198
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001199 /* Authority Information Access: OCSP URIs */
1200 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1201 if (obj == NULL) {
1202 goto fail1;
1203 } else if (obj != Py_None) {
1204 result = PyDict_SetItemString(retval, "OCSP", obj);
1205 Py_DECREF(obj);
1206 if (result < 0) {
1207 goto fail1;
1208 }
1209 }
1210
1211 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1212 if (obj == NULL) {
1213 goto fail1;
1214 } else if (obj != Py_None) {
1215 result = PyDict_SetItemString(retval, "caIssuers", obj);
1216 Py_DECREF(obj);
1217 if (result < 0) {
1218 goto fail1;
1219 }
1220 }
1221
1222 /* CDP (CRL distribution points) */
1223 obj = _get_crl_dp(certificate);
1224 if (obj == NULL) {
1225 goto fail1;
1226 } else if (obj != Py_None) {
1227 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1228 Py_DECREF(obj);
1229 if (result < 0) {
1230 goto fail1;
1231 }
1232 }
1233
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001234 BIO_free(biobuf);
1235 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001236
1237 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001238 if (biobuf != NULL)
1239 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001240 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001241 Py_XDECREF(retval);
1242 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001243}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001244
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001245static PyObject *
1246_certificate_to_der(X509 *certificate)
1247{
1248 unsigned char *bytes_buf = NULL;
1249 int len;
1250 PyObject *retval;
1251
1252 bytes_buf = NULL;
1253 len = i2d_X509(certificate, &bytes_buf);
1254 if (len < 0) {
1255 _setSSLError(NULL, 0, __FILE__, __LINE__);
1256 return NULL;
1257 }
1258 /* this is actually an immutable bytes sequence */
1259 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1260 OPENSSL_free(bytes_buf);
1261 return retval;
1262}
Bill Janssen98d19da2007-09-10 21:51:02 +00001263
1264static PyObject *
1265PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1266
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001267 PyObject *retval = NULL;
1268 char *filename = NULL;
1269 X509 *x=NULL;
1270 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001271
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001272 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001273 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001274
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001275 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001276 PyErr_SetString(PySSLErrorObject,
1277 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001278 goto fail0;
1279 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001280
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001281 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001282 PyErr_SetString(PySSLErrorObject,
1283 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001284 goto fail0;
1285 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001286
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001287 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1288 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001289 PyErr_SetString(PySSLErrorObject,
1290 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001291 goto fail0;
1292 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001293
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001294 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001295 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001296
1297 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001298
1299 if (cert != NULL) BIO_free(cert);
1300 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001301}
1302
1303
1304static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001305PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001306{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001307 int verification;
1308 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001309 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001310
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001311 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1312 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001313
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001314 if (!self->handshake_done) {
1315 PyErr_SetString(PyExc_ValueError,
1316 "handshake not done yet");
1317 return NULL;
1318 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001319 if (!self->peer_cert)
1320 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001321
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001322 b = PyObject_IsTrue(binary_mode);
1323 if (b < 0)
1324 return NULL;
1325 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001326 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001327 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001328 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001329 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001330 if ((verification & SSL_VERIFY_PEER) == 0)
1331 return PyDict_New();
1332 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001333 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001334 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001335}
1336
1337PyDoc_STRVAR(PySSL_peercert_doc,
1338"peer_certificate([der=False]) -> certificate\n\
1339\n\
1340Returns the certificate for the peer. If no certificate was provided,\n\
1341returns None. If a certificate was provided, but not validated, returns\n\
1342an empty dictionary. Otherwise returns a dict containing information\n\
1343about the peer certificate.\n\
1344\n\
1345If the optional argument is True, returns a DER-encoded copy of the\n\
1346peer certificate, or None if no certificate was provided. This will\n\
1347return the certificate even if it wasn't validated.");
1348
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001349static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001350
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001351 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001352 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001353 char *cipher_name;
1354 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001355
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001356 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001357 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001358 current = SSL_get_current_cipher(self->ssl);
1359 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001360 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001361
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001362 retval = PyTuple_New(3);
1363 if (retval == NULL)
1364 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001365
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001366 cipher_name = (char *) SSL_CIPHER_get_name(current);
1367 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001368 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001369 PyTuple_SET_ITEM(retval, 0, Py_None);
1370 } else {
1371 v = PyString_FromString(cipher_name);
1372 if (v == NULL)
1373 goto fail0;
1374 PyTuple_SET_ITEM(retval, 0, v);
1375 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001376 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001377 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001378 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001379 PyTuple_SET_ITEM(retval, 1, Py_None);
1380 } else {
1381 v = PyString_FromString(cipher_protocol);
1382 if (v == NULL)
1383 goto fail0;
1384 PyTuple_SET_ITEM(retval, 1, v);
1385 }
1386 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1387 if (v == NULL)
1388 goto fail0;
1389 PyTuple_SET_ITEM(retval, 2, v);
1390 return retval;
1391
Bill Janssen98d19da2007-09-10 21:51:02 +00001392 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001393 Py_DECREF(retval);
1394 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001395}
1396
Alex Gaynore98205d2014-09-04 13:33:22 -07001397static PyObject *PySSL_version(PySSLSocket *self)
1398{
1399 const char *version;
1400
1401 if (self->ssl == NULL)
1402 Py_RETURN_NONE;
1403 version = SSL_get_version(self->ssl);
1404 if (!strcmp(version, "unknown"))
1405 Py_RETURN_NONE;
1406 return PyUnicode_FromString(version);
1407}
1408
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001409#ifdef OPENSSL_NPN_NEGOTIATED
1410static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1411 const unsigned char *out;
1412 unsigned int outlen;
1413
1414 SSL_get0_next_proto_negotiated(self->ssl,
1415 &out, &outlen);
1416
1417 if (out == NULL)
1418 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001419 return PyString_FromStringAndSize((char *)out, outlen);
1420}
1421#endif
1422
1423#ifdef HAVE_ALPN
1424static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1425 const unsigned char *out;
1426 unsigned int outlen;
1427
1428 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1429
1430 if (out == NULL)
1431 Py_RETURN_NONE;
1432 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001433}
1434#endif
1435
1436static PyObject *PySSL_compression(PySSLSocket *self) {
1437#ifdef OPENSSL_NO_COMP
1438 Py_RETURN_NONE;
1439#else
1440 const COMP_METHOD *comp_method;
1441 const char *short_name;
1442
1443 if (self->ssl == NULL)
1444 Py_RETURN_NONE;
1445 comp_method = SSL_get_current_compression(self->ssl);
1446 if (comp_method == NULL || comp_method->type == NID_undef)
1447 Py_RETURN_NONE;
1448 short_name = OBJ_nid2sn(comp_method->type);
1449 if (short_name == NULL)
1450 Py_RETURN_NONE;
1451 return PyBytes_FromString(short_name);
1452#endif
1453}
1454
1455static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1456 Py_INCREF(self->ctx);
1457 return self->ctx;
1458}
1459
1460static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1461 void *closure) {
1462
1463 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1464#if !HAVE_SNI
1465 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1466 "context is not supported by your OpenSSL library");
1467 return -1;
1468#else
1469 Py_INCREF(value);
Serhiy Storchaka763a61c2016-04-10 18:05:12 +03001470 Py_SETREF(self->ctx, (PySSLContext *)value);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001471 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1472#endif
1473 } else {
1474 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1475 return -1;
1476 }
1477
1478 return 0;
1479}
1480
1481PyDoc_STRVAR(PySSL_set_context_doc,
1482"_setter_context(ctx)\n\
1483\
1484This changes the context associated with the SSLSocket. This is typically\n\
1485used from within a callback function set by the set_servername_callback\n\
1486on the SSLContext to change the certificate information associated with the\n\
1487SSLSocket before the cryptographic exchange handshake messages\n");
1488
1489
1490
1491static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001492{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001493 if (self->peer_cert) /* Possible not to have one? */
1494 X509_free (self->peer_cert);
1495 if (self->ssl)
1496 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001497 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001498 Py_XDECREF(self->ssl_sock);
1499 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001500 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001501}
1502
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001503/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001504 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001505 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001506 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001507
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001508static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001509check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001510{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001511 fd_set fds;
1512 struct timeval tv;
1513 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001514
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001515 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1516 if (s->sock_timeout < 0.0)
1517 return SOCKET_IS_BLOCKING;
1518 else if (s->sock_timeout == 0.0)
1519 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001520
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001521 /* Guard against closed socket */
1522 if (s->sock_fd < 0)
1523 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001524
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001525 /* Prefer poll, if available, since you can poll() any fd
1526 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001527#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001528 {
1529 struct pollfd pollfd;
1530 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001531
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001532 pollfd.fd = s->sock_fd;
1533 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001534
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001535 /* s->sock_timeout is in seconds, timeout in ms */
1536 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1537 PySSL_BEGIN_ALLOW_THREADS
1538 rc = poll(&pollfd, 1, timeout);
1539 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001540
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001541 goto normal_return;
1542 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001543#endif
1544
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001545 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001546 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001547 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001548
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001549 /* Construct the arguments to select */
1550 tv.tv_sec = (int)s->sock_timeout;
1551 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1552 FD_ZERO(&fds);
1553 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001554
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001555 /* See if the socket is ready */
1556 PySSL_BEGIN_ALLOW_THREADS
1557 if (writing)
1558 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1559 else
1560 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1561 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001562
Bill Janssen934b16d2008-06-28 22:19:33 +00001563#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001564normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001565#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001566 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1567 (when we are able to write or when there's something to read) */
1568 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001569}
1570
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001571static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001572{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001573 Py_buffer buf;
1574 int len;
1575 int sockstate;
1576 int err;
1577 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001578 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001579
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001580 Py_INCREF(sock);
1581
1582 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1583 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001584 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001585 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001586
Victor Stinnerc1a44262013-06-25 00:48:02 +02001587 if (buf.len > INT_MAX) {
1588 PyErr_Format(PyExc_OverflowError,
1589 "string longer than %d bytes", INT_MAX);
1590 goto error;
1591 }
1592
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001593 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001594 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001595 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1596 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001597
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001598 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001599 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1600 PyErr_SetString(PySSLErrorObject,
1601 "The write operation timed out");
1602 goto error;
1603 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1604 PyErr_SetString(PySSLErrorObject,
1605 "Underlying socket has been closed.");
1606 goto error;
1607 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1608 PyErr_SetString(PySSLErrorObject,
1609 "Underlying socket too large for select().");
1610 goto error;
1611 }
1612 do {
1613 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001614 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001615 err = SSL_get_error(self->ssl, len);
1616 PySSL_END_ALLOW_THREADS
1617 if (PyErr_CheckSignals()) {
1618 goto error;
1619 }
1620 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001621 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001622 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001623 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001624 } else {
1625 sockstate = SOCKET_OPERATION_OK;
1626 }
1627 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1628 PyErr_SetString(PySSLErrorObject,
1629 "The write operation timed out");
1630 goto error;
1631 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1632 PyErr_SetString(PySSLErrorObject,
1633 "Underlying socket has been closed.");
1634 goto error;
1635 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1636 break;
1637 }
1638 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001639
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001640 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001641 PyBuffer_Release(&buf);
1642 if (len > 0)
1643 return PyInt_FromLong(len);
1644 else
1645 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001646
1647error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001648 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001649 PyBuffer_Release(&buf);
1650 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001651}
1652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001653PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001654"write(s) -> len\n\
1655\n\
1656Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001657of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001658
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001659static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001660{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001661 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001662
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001663 PySSL_BEGIN_ALLOW_THREADS
1664 count = SSL_pending(self->ssl);
1665 PySSL_END_ALLOW_THREADS
1666 if (count < 0)
1667 return PySSL_SetError(self, count, __FILE__, __LINE__);
1668 else
1669 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001670}
1671
1672PyDoc_STRVAR(PySSL_SSLpending_doc,
1673"pending() -> count\n\
1674\n\
1675Returns the number of already decrypted bytes available for read,\n\
1676pending on the connection.\n");
1677
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001678static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001679{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001680 PyObject *dest = NULL;
1681 Py_buffer buf;
1682 char *mem;
1683 int len, count;
1684 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001685 int sockstate;
1686 int err;
1687 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001688 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001691
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001692 buf.obj = NULL;
1693 buf.buf = NULL;
1694 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1695 goto error;
1696
1697 if ((buf.buf == NULL) && (buf.obj == NULL)) {
Martin Panterb8089b42016-03-27 05:35:19 +00001698 if (len < 0) {
1699 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1700 goto error;
1701 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001702 dest = PyBytes_FromStringAndSize(NULL, len);
1703 if (dest == NULL)
1704 goto error;
Martin Panter8c6849b2016-07-11 00:17:13 +00001705 if (len == 0) {
1706 Py_XDECREF(sock);
1707 return dest;
1708 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001709 mem = PyBytes_AS_STRING(dest);
1710 }
1711 else {
1712 buf_passed = 1;
1713 mem = buf.buf;
1714 if (len <= 0 || len > buf.len) {
1715 len = (int) buf.len;
1716 if (buf.len != len) {
1717 PyErr_SetString(PyExc_OverflowError,
1718 "maximum length can't fit in a C 'int'");
1719 goto error;
1720 }
Martin Panter8c6849b2016-07-11 00:17:13 +00001721 if (len == 0) {
1722 count = 0;
1723 goto done;
1724 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001725 }
1726 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001727
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001729 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001730 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1731 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001732
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001733 do {
1734 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001735 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001736 err = SSL_get_error(self->ssl, count);
1737 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001738 if (PyErr_CheckSignals())
1739 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001740 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001741 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001742 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001743 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001744 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1745 (SSL_get_shutdown(self->ssl) ==
1746 SSL_RECEIVED_SHUTDOWN))
1747 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001748 count = 0;
1749 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001750 } else {
1751 sockstate = SOCKET_OPERATION_OK;
1752 }
1753 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1754 PyErr_SetString(PySSLErrorObject,
1755 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001756 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001757 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1758 break;
1759 }
1760 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1761 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001762 PySSL_SetError(self, count, __FILE__, __LINE__);
1763 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001764 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001765
1766done:
1767 Py_DECREF(sock);
1768 if (!buf_passed) {
1769 _PyBytes_Resize(&dest, count);
1770 return dest;
1771 }
1772 else {
1773 PyBuffer_Release(&buf);
1774 return PyLong_FromLong(count);
1775 }
1776
1777error:
1778 Py_DECREF(sock);
1779 if (!buf_passed)
1780 Py_XDECREF(dest);
1781 else
1782 PyBuffer_Release(&buf);
1783 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001784}
1785
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001786PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001787"read([len]) -> string\n\
1788\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001789Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001790
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001791static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001792{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001793 int err, ssl_err, sockstate, nonblocking;
1794 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001795 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001796
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001797 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001798 if (sock->sock_fd < 0) {
1799 _setSSLError("Underlying socket connection gone",
1800 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001801 return NULL;
1802 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001803 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001804
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001805 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001806 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001807 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1808 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001809
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001810 while (1) {
1811 PySSL_BEGIN_ALLOW_THREADS
1812 /* Disable read-ahead so that unwrap can work correctly.
1813 * Otherwise OpenSSL might read in too much data,
1814 * eating clear text data that happens to be
1815 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001816 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001817 * function is used and the shutdown_seen_zero != 0
1818 * condition is met.
1819 */
1820 if (self->shutdown_seen_zero)
1821 SSL_set_read_ahead(self->ssl, 0);
1822 err = SSL_shutdown(self->ssl);
1823 PySSL_END_ALLOW_THREADS
1824 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1825 if (err > 0)
1826 break;
1827 if (err == 0) {
1828 /* Don't loop endlessly; instead preserve legacy
1829 behaviour of trying SSL_shutdown() only twice.
1830 This looks necessary for OpenSSL < 0.9.8m */
1831 if (++zeros > 1)
1832 break;
1833 /* Shutdown was sent, now try receiving */
1834 self->shutdown_seen_zero = 1;
1835 continue;
1836 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001837
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001838 /* Possibly retry shutdown until timeout or failure */
1839 ssl_err = SSL_get_error(self->ssl, err);
1840 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001841 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001843 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001844 else
1845 break;
1846 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1847 if (ssl_err == SSL_ERROR_WANT_READ)
1848 PyErr_SetString(PySSLErrorObject,
1849 "The read operation timed out");
1850 else
1851 PyErr_SetString(PySSLErrorObject,
1852 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001853 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001854 }
1855 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1856 PyErr_SetString(PySSLErrorObject,
1857 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001859 }
1860 else if (sockstate != SOCKET_OPERATION_OK)
1861 /* Retain the SSL error code */
1862 break;
1863 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001864
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001865 if (err < 0) {
1866 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001867 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001868 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001869 else
1870 /* It's already INCREF'ed */
1871 return (PyObject *) sock;
1872
1873error:
1874 Py_DECREF(sock);
1875 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001876}
1877
1878PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1879"shutdown(s) -> socket\n\
1880\n\
1881Does the SSL shutdown handshake with the remote end, and returns\n\
1882the underlying socket object.");
1883
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001884#if HAVE_OPENSSL_FINISHED
1885static PyObject *
1886PySSL_tls_unique_cb(PySSLSocket *self)
1887{
1888 PyObject *retval = NULL;
1889 char buf[PySSL_CB_MAXLEN];
1890 size_t len;
1891
1892 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1893 /* if session is resumed XOR we are the client */
1894 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1895 }
1896 else {
1897 /* if a new session XOR we are the server */
1898 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1899 }
1900
1901 /* It cannot be negative in current OpenSSL version as of July 2011 */
1902 if (len == 0)
1903 Py_RETURN_NONE;
1904
1905 retval = PyBytes_FromStringAndSize(buf, len);
1906
1907 return retval;
1908}
1909
1910PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1911"tls_unique_cb() -> bytes\n\
1912\n\
1913Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1914\n\
1915If the TLS handshake is not yet complete, None is returned");
1916
1917#endif /* HAVE_OPENSSL_FINISHED */
1918
1919static PyGetSetDef ssl_getsetlist[] = {
1920 {"context", (getter) PySSL_get_context,
1921 (setter) PySSL_set_context, PySSL_set_context_doc},
1922 {NULL}, /* sentinel */
1923};
1924
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001925static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001926 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1927 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1928 PySSL_SSLwrite_doc},
1929 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1930 PySSL_SSLread_doc},
1931 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1932 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001933 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1934 PySSL_peercert_doc},
1935 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07001936 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001937#ifdef OPENSSL_NPN_NEGOTIATED
1938 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1939#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001940#ifdef HAVE_ALPN
1941 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
1942#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001943 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001944 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1945 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001946#if HAVE_OPENSSL_FINISHED
1947 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1948 PySSL_tls_unique_cb_doc},
1949#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001950 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001951};
1952
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001953static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001954 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001955 "_ssl._SSLSocket", /*tp_name*/
1956 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001957 0, /*tp_itemsize*/
1958 /* methods */
1959 (destructor)PySSL_dealloc, /*tp_dealloc*/
1960 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001961 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001962 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001963 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001964 0, /*tp_repr*/
1965 0, /*tp_as_number*/
1966 0, /*tp_as_sequence*/
1967 0, /*tp_as_mapping*/
1968 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001969 0, /*tp_call*/
1970 0, /*tp_str*/
1971 0, /*tp_getattro*/
1972 0, /*tp_setattro*/
1973 0, /*tp_as_buffer*/
1974 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1975 0, /*tp_doc*/
1976 0, /*tp_traverse*/
1977 0, /*tp_clear*/
1978 0, /*tp_richcompare*/
1979 0, /*tp_weaklistoffset*/
1980 0, /*tp_iter*/
1981 0, /*tp_iternext*/
1982 PySSLMethods, /*tp_methods*/
1983 0, /*tp_members*/
1984 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001985};
1986
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001987
1988/*
1989 * _SSLContext objects
1990 */
1991
1992static PyObject *
1993context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1994{
1995 char *kwlist[] = {"protocol", NULL};
1996 PySSLContext *self;
1997 int proto_version = PY_SSL_VERSION_SSL23;
1998 long options;
1999 SSL_CTX *ctx = NULL;
2000
2001 if (!PyArg_ParseTupleAndKeywords(
2002 args, kwds, "i:_SSLContext", kwlist,
2003 &proto_version))
2004 return NULL;
2005
2006 PySSL_BEGIN_ALLOW_THREADS
2007 if (proto_version == PY_SSL_VERSION_TLS1)
2008 ctx = SSL_CTX_new(TLSv1_method());
2009#if HAVE_TLSv1_2
2010 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2011 ctx = SSL_CTX_new(TLSv1_1_method());
2012 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2013 ctx = SSL_CTX_new(TLSv1_2_method());
2014#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002015#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002016 else if (proto_version == PY_SSL_VERSION_SSL3)
2017 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002018#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002019#ifndef OPENSSL_NO_SSL2
2020 else if (proto_version == PY_SSL_VERSION_SSL2)
2021 ctx = SSL_CTX_new(SSLv2_method());
2022#endif
2023 else if (proto_version == PY_SSL_VERSION_SSL23)
2024 ctx = SSL_CTX_new(SSLv23_method());
2025 else
2026 proto_version = -1;
2027 PySSL_END_ALLOW_THREADS
2028
2029 if (proto_version == -1) {
2030 PyErr_SetString(PyExc_ValueError,
2031 "invalid protocol version");
2032 return NULL;
2033 }
2034 if (ctx == NULL) {
2035 PyErr_SetString(PySSLErrorObject,
2036 "failed to allocate SSL context");
2037 return NULL;
2038 }
2039
2040 assert(type != NULL && type->tp_alloc != NULL);
2041 self = (PySSLContext *) type->tp_alloc(type, 0);
2042 if (self == NULL) {
2043 SSL_CTX_free(ctx);
2044 return NULL;
2045 }
2046 self->ctx = ctx;
2047#ifdef OPENSSL_NPN_NEGOTIATED
2048 self->npn_protocols = NULL;
2049#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002050#ifdef HAVE_ALPN
2051 self->alpn_protocols = NULL;
2052#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002053#ifndef OPENSSL_NO_TLSEXT
2054 self->set_hostname = NULL;
2055#endif
2056 /* Don't check host name by default */
2057 self->check_hostname = 0;
2058 /* Defaults */
2059 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2060 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2061 if (proto_version != PY_SSL_VERSION_SSL2)
2062 options |= SSL_OP_NO_SSLv2;
Benjamin Peterson10aaca92015-11-11 22:38:41 -08002063 if (proto_version != PY_SSL_VERSION_SSL3)
2064 options |= SSL_OP_NO_SSLv3;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002065 SSL_CTX_set_options(self->ctx, options);
2066
2067#ifndef OPENSSL_NO_ECDH
2068 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2069 prime256v1 by default. This is Apache mod_ssl's initialization
2070 policy, so we should be safe. */
2071#if defined(SSL_CTX_set_ecdh_auto)
2072 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2073#else
2074 {
2075 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2076 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2077 EC_KEY_free(key);
2078 }
2079#endif
2080#endif
2081
2082#define SID_CTX "Python"
2083 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2084 sizeof(SID_CTX));
2085#undef SID_CTX
2086
Benjamin Petersonb1ebba52015-03-04 22:11:12 -05002087#ifdef X509_V_FLAG_TRUSTED_FIRST
2088 {
2089 /* Improve trust chain building when cross-signed intermediate
2090 certificates are present. See https://bugs.python.org/issue23476. */
2091 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2092 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2093 }
2094#endif
2095
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002096 return (PyObject *)self;
2097}
2098
2099static int
2100context_traverse(PySSLContext *self, visitproc visit, void *arg)
2101{
2102#ifndef OPENSSL_NO_TLSEXT
2103 Py_VISIT(self->set_hostname);
2104#endif
2105 return 0;
2106}
2107
2108static int
2109context_clear(PySSLContext *self)
2110{
2111#ifndef OPENSSL_NO_TLSEXT
2112 Py_CLEAR(self->set_hostname);
2113#endif
2114 return 0;
2115}
2116
2117static void
2118context_dealloc(PySSLContext *self)
2119{
2120 context_clear(self);
2121 SSL_CTX_free(self->ctx);
2122#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002123 PyMem_FREE(self->npn_protocols);
2124#endif
2125#ifdef HAVE_ALPN
2126 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002127#endif
2128 Py_TYPE(self)->tp_free(self);
2129}
2130
2131static PyObject *
2132set_ciphers(PySSLContext *self, PyObject *args)
2133{
2134 int ret;
2135 const char *cipherlist;
2136
2137 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2138 return NULL;
2139 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2140 if (ret == 0) {
2141 /* Clearing the error queue is necessary on some OpenSSL versions,
2142 otherwise the error will be reported again when another SSL call
2143 is done. */
2144 ERR_clear_error();
2145 PyErr_SetString(PySSLErrorObject,
2146 "No cipher can be selected.");
2147 return NULL;
2148 }
2149 Py_RETURN_NONE;
2150}
2151
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002152#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002153static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002154do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2155 const unsigned char *server_protocols, unsigned int server_protocols_len,
2156 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002157{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002158 int ret;
2159 if (client_protocols == NULL) {
2160 client_protocols = (unsigned char *)"";
2161 client_protocols_len = 0;
2162 }
2163 if (server_protocols == NULL) {
2164 server_protocols = (unsigned char *)"";
2165 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002166 }
2167
Benjamin Petersonaa707582015-01-23 17:30:26 -05002168 ret = SSL_select_next_proto(out, outlen,
2169 server_protocols, server_protocols_len,
2170 client_protocols, client_protocols_len);
2171 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2172 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002173
2174 return SSL_TLSEXT_ERR_OK;
2175}
2176
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002177/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2178static int
2179_advertiseNPN_cb(SSL *s,
2180 const unsigned char **data, unsigned int *len,
2181 void *args)
2182{
2183 PySSLContext *ssl_ctx = (PySSLContext *) args;
2184
2185 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002186 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002187 *len = 0;
2188 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002189 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002190 *len = ssl_ctx->npn_protocols_len;
2191 }
2192
2193 return SSL_TLSEXT_ERR_OK;
2194}
2195/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2196static int
2197_selectNPN_cb(SSL *s,
2198 unsigned char **out, unsigned char *outlen,
2199 const unsigned char *server, unsigned int server_len,
2200 void *args)
2201{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002202 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002203 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002204 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002205}
2206#endif
2207
2208static PyObject *
2209_set_npn_protocols(PySSLContext *self, PyObject *args)
2210{
2211#ifdef OPENSSL_NPN_NEGOTIATED
2212 Py_buffer protos;
2213
2214 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2215 return NULL;
2216
2217 if (self->npn_protocols != NULL) {
2218 PyMem_Free(self->npn_protocols);
2219 }
2220
2221 self->npn_protocols = PyMem_Malloc(protos.len);
2222 if (self->npn_protocols == NULL) {
2223 PyBuffer_Release(&protos);
2224 return PyErr_NoMemory();
2225 }
2226 memcpy(self->npn_protocols, protos.buf, protos.len);
2227 self->npn_protocols_len = (int) protos.len;
2228
2229 /* set both server and client callbacks, because the context can
2230 * be used to create both types of sockets */
2231 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2232 _advertiseNPN_cb,
2233 self);
2234 SSL_CTX_set_next_proto_select_cb(self->ctx,
2235 _selectNPN_cb,
2236 self);
2237
2238 PyBuffer_Release(&protos);
2239 Py_RETURN_NONE;
2240#else
2241 PyErr_SetString(PyExc_NotImplementedError,
2242 "The NPN extension requires OpenSSL 1.0.1 or later.");
2243 return NULL;
2244#endif
2245}
2246
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002247#ifdef HAVE_ALPN
2248static int
2249_selectALPN_cb(SSL *s,
2250 const unsigned char **out, unsigned char *outlen,
2251 const unsigned char *client_protocols, unsigned int client_protocols_len,
2252 void *args)
2253{
2254 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002255 return do_protocol_selection(1, (unsigned char **)out, outlen,
2256 ctx->alpn_protocols, ctx->alpn_protocols_len,
2257 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002258}
2259#endif
2260
2261static PyObject *
2262_set_alpn_protocols(PySSLContext *self, PyObject *args)
2263{
2264#ifdef HAVE_ALPN
2265 Py_buffer protos;
2266
2267 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2268 return NULL;
2269
2270 PyMem_FREE(self->alpn_protocols);
2271 self->alpn_protocols = PyMem_Malloc(protos.len);
2272 if (!self->alpn_protocols)
2273 return PyErr_NoMemory();
2274 memcpy(self->alpn_protocols, protos.buf, protos.len);
2275 self->alpn_protocols_len = protos.len;
2276 PyBuffer_Release(&protos);
2277
2278 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2279 return PyErr_NoMemory();
2280 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2281
2282 PyBuffer_Release(&protos);
2283 Py_RETURN_NONE;
2284#else
2285 PyErr_SetString(PyExc_NotImplementedError,
2286 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2287 return NULL;
2288#endif
2289}
2290
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002291static PyObject *
2292get_verify_mode(PySSLContext *self, void *c)
2293{
2294 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2295 case SSL_VERIFY_NONE:
2296 return PyLong_FromLong(PY_SSL_CERT_NONE);
2297 case SSL_VERIFY_PEER:
2298 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2299 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2300 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2301 }
2302 PyErr_SetString(PySSLErrorObject,
2303 "invalid return value from SSL_CTX_get_verify_mode");
2304 return NULL;
2305}
2306
2307static int
2308set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2309{
2310 int n, mode;
2311 if (!PyArg_Parse(arg, "i", &n))
2312 return -1;
2313 if (n == PY_SSL_CERT_NONE)
2314 mode = SSL_VERIFY_NONE;
2315 else if (n == PY_SSL_CERT_OPTIONAL)
2316 mode = SSL_VERIFY_PEER;
2317 else if (n == PY_SSL_CERT_REQUIRED)
2318 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2319 else {
2320 PyErr_SetString(PyExc_ValueError,
2321 "invalid value for verify_mode");
2322 return -1;
2323 }
2324 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2325 PyErr_SetString(PyExc_ValueError,
2326 "Cannot set verify_mode to CERT_NONE when "
2327 "check_hostname is enabled.");
2328 return -1;
2329 }
2330 SSL_CTX_set_verify(self->ctx, mode, NULL);
2331 return 0;
2332}
2333
2334#ifdef HAVE_OPENSSL_VERIFY_PARAM
2335static PyObject *
2336get_verify_flags(PySSLContext *self, void *c)
2337{
2338 X509_STORE *store;
2339 unsigned long flags;
2340
2341 store = SSL_CTX_get_cert_store(self->ctx);
2342 flags = X509_VERIFY_PARAM_get_flags(store->param);
2343 return PyLong_FromUnsignedLong(flags);
2344}
2345
2346static int
2347set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2348{
2349 X509_STORE *store;
2350 unsigned long new_flags, flags, set, clear;
2351
2352 if (!PyArg_Parse(arg, "k", &new_flags))
2353 return -1;
2354 store = SSL_CTX_get_cert_store(self->ctx);
2355 flags = X509_VERIFY_PARAM_get_flags(store->param);
2356 clear = flags & ~new_flags;
2357 set = ~flags & new_flags;
2358 if (clear) {
2359 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2360 _setSSLError(NULL, 0, __FILE__, __LINE__);
2361 return -1;
2362 }
2363 }
2364 if (set) {
2365 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2366 _setSSLError(NULL, 0, __FILE__, __LINE__);
2367 return -1;
2368 }
2369 }
2370 return 0;
2371}
2372#endif
2373
2374static PyObject *
2375get_options(PySSLContext *self, void *c)
2376{
2377 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2378}
2379
2380static int
2381set_options(PySSLContext *self, PyObject *arg, void *c)
2382{
2383 long new_opts, opts, set, clear;
2384 if (!PyArg_Parse(arg, "l", &new_opts))
2385 return -1;
2386 opts = SSL_CTX_get_options(self->ctx);
2387 clear = opts & ~new_opts;
2388 set = ~opts & new_opts;
2389 if (clear) {
2390#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2391 SSL_CTX_clear_options(self->ctx, clear);
2392#else
2393 PyErr_SetString(PyExc_ValueError,
2394 "can't clear options before OpenSSL 0.9.8m");
2395 return -1;
2396#endif
2397 }
2398 if (set)
2399 SSL_CTX_set_options(self->ctx, set);
2400 return 0;
2401}
2402
2403static PyObject *
2404get_check_hostname(PySSLContext *self, void *c)
2405{
2406 return PyBool_FromLong(self->check_hostname);
2407}
2408
2409static int
2410set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2411{
2412 PyObject *py_check_hostname;
2413 int check_hostname;
2414 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2415 return -1;
2416
2417 check_hostname = PyObject_IsTrue(py_check_hostname);
2418 if (check_hostname < 0)
2419 return -1;
2420 if (check_hostname &&
2421 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2422 PyErr_SetString(PyExc_ValueError,
2423 "check_hostname needs a SSL context with either "
2424 "CERT_OPTIONAL or CERT_REQUIRED");
2425 return -1;
2426 }
2427 self->check_hostname = check_hostname;
2428 return 0;
2429}
2430
2431
2432typedef struct {
2433 PyThreadState *thread_state;
2434 PyObject *callable;
2435 char *password;
2436 int size;
2437 int error;
2438} _PySSLPasswordInfo;
2439
2440static int
2441_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2442 const char *bad_type_error)
2443{
2444 /* Set the password and size fields of a _PySSLPasswordInfo struct
2445 from a unicode, bytes, or byte array object.
2446 The password field will be dynamically allocated and must be freed
2447 by the caller */
2448 PyObject *password_bytes = NULL;
2449 const char *data = NULL;
2450 Py_ssize_t size;
2451
2452 if (PyUnicode_Check(password)) {
2453 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2454 if (!password_bytes) {
2455 goto error;
2456 }
2457 data = PyBytes_AS_STRING(password_bytes);
2458 size = PyBytes_GET_SIZE(password_bytes);
2459 } else if (PyBytes_Check(password)) {
2460 data = PyBytes_AS_STRING(password);
2461 size = PyBytes_GET_SIZE(password);
2462 } else if (PyByteArray_Check(password)) {
2463 data = PyByteArray_AS_STRING(password);
2464 size = PyByteArray_GET_SIZE(password);
2465 } else {
2466 PyErr_SetString(PyExc_TypeError, bad_type_error);
2467 goto error;
2468 }
2469
2470 if (size > (Py_ssize_t)INT_MAX) {
2471 PyErr_Format(PyExc_ValueError,
2472 "password cannot be longer than %d bytes", INT_MAX);
2473 goto error;
2474 }
2475
2476 PyMem_Free(pw_info->password);
2477 pw_info->password = PyMem_Malloc(size);
2478 if (!pw_info->password) {
2479 PyErr_SetString(PyExc_MemoryError,
2480 "unable to allocate password buffer");
2481 goto error;
2482 }
2483 memcpy(pw_info->password, data, size);
2484 pw_info->size = (int)size;
2485
2486 Py_XDECREF(password_bytes);
2487 return 1;
2488
2489error:
2490 Py_XDECREF(password_bytes);
2491 return 0;
2492}
2493
2494static int
2495_password_callback(char *buf, int size, int rwflag, void *userdata)
2496{
2497 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2498 PyObject *fn_ret = NULL;
2499
2500 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2501
2502 if (pw_info->callable) {
2503 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2504 if (!fn_ret) {
2505 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2506 core python API, so we could use it to add a frame here */
2507 goto error;
2508 }
2509
2510 if (!_pwinfo_set(pw_info, fn_ret,
2511 "password callback must return a string")) {
2512 goto error;
2513 }
2514 Py_CLEAR(fn_ret);
2515 }
2516
2517 if (pw_info->size > size) {
2518 PyErr_Format(PyExc_ValueError,
2519 "password cannot be longer than %d bytes", size);
2520 goto error;
2521 }
2522
2523 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2524 memcpy(buf, pw_info->password, pw_info->size);
2525 return pw_info->size;
2526
2527error:
2528 Py_XDECREF(fn_ret);
2529 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2530 pw_info->error = 1;
2531 return -1;
2532}
2533
2534static PyObject *
2535load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2536{
2537 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002538 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2539 char *certfile_bytes = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002540 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2541 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2542 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2543 int r;
2544
2545 errno = 0;
2546 ERR_clear_error();
2547 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002548 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002549 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002550 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002551 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002552
2553 if (keyfile && keyfile != Py_None) {
2554 if (PyString_Check(keyfile)) {
2555 Py_INCREF(keyfile);
2556 keyfile_bytes = keyfile;
2557 } else {
2558 PyObject *u = PyUnicode_FromObject(keyfile);
2559 if (!u)
2560 goto error;
2561 keyfile_bytes = PyUnicode_AsEncodedString(
2562 u, Py_FileSystemDefaultEncoding, NULL);
2563 Py_DECREF(u);
2564 if (!keyfile_bytes)
2565 goto error;
2566 }
2567 }
2568
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002569 if (password && password != Py_None) {
2570 if (PyCallable_Check(password)) {
2571 pw_info.callable = password;
2572 } else if (!_pwinfo_set(&pw_info, password,
2573 "password should be a string or callable")) {
2574 goto error;
2575 }
2576 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2577 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2578 }
2579 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2580 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2581 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2582 if (r != 1) {
2583 if (pw_info.error) {
2584 ERR_clear_error();
2585 /* the password callback has already set the error information */
2586 }
2587 else if (errno != 0) {
2588 ERR_clear_error();
2589 PyErr_SetFromErrno(PyExc_IOError);
2590 }
2591 else {
2592 _setSSLError(NULL, 0, __FILE__, __LINE__);
2593 }
2594 goto error;
2595 }
2596 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2597 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002598 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002599 SSL_FILETYPE_PEM);
2600 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2601 if (r != 1) {
2602 if (pw_info.error) {
2603 ERR_clear_error();
2604 /* the password callback has already set the error information */
2605 }
2606 else if (errno != 0) {
2607 ERR_clear_error();
2608 PyErr_SetFromErrno(PyExc_IOError);
2609 }
2610 else {
2611 _setSSLError(NULL, 0, __FILE__, __LINE__);
2612 }
2613 goto error;
2614 }
2615 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2616 r = SSL_CTX_check_private_key(self->ctx);
2617 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2618 if (r != 1) {
2619 _setSSLError(NULL, 0, __FILE__, __LINE__);
2620 goto error;
2621 }
2622 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2623 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Petersonb3e073c2016-06-08 23:18:51 -07002624 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002625 PyMem_Free(pw_info.password);
Benjamin Peterson3b91de52016-06-08 23:16:36 -07002626 PyMem_Free(certfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002627 Py_RETURN_NONE;
2628
2629error:
2630 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2631 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002632 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002633 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002634 PyMem_Free(certfile_bytes);
2635 return NULL;
2636}
2637
2638/* internal helper function, returns -1 on error
2639 */
2640static int
2641_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2642 int filetype)
2643{
2644 BIO *biobuf = NULL;
2645 X509_STORE *store;
2646 int retval = 0, err, loaded = 0;
2647
2648 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2649
2650 if (len <= 0) {
2651 PyErr_SetString(PyExc_ValueError,
2652 "Empty certificate data");
2653 return -1;
2654 } else if (len > INT_MAX) {
2655 PyErr_SetString(PyExc_OverflowError,
2656 "Certificate data is too long.");
2657 return -1;
2658 }
2659
2660 biobuf = BIO_new_mem_buf(data, (int)len);
2661 if (biobuf == NULL) {
2662 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2663 return -1;
2664 }
2665
2666 store = SSL_CTX_get_cert_store(self->ctx);
2667 assert(store != NULL);
2668
2669 while (1) {
2670 X509 *cert = NULL;
2671 int r;
2672
2673 if (filetype == SSL_FILETYPE_ASN1) {
2674 cert = d2i_X509_bio(biobuf, NULL);
2675 } else {
2676 cert = PEM_read_bio_X509(biobuf, NULL,
2677 self->ctx->default_passwd_callback,
2678 self->ctx->default_passwd_callback_userdata);
2679 }
2680 if (cert == NULL) {
2681 break;
2682 }
2683 r = X509_STORE_add_cert(store, cert);
2684 X509_free(cert);
2685 if (!r) {
2686 err = ERR_peek_last_error();
2687 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2688 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2689 /* cert already in hash table, not an error */
2690 ERR_clear_error();
2691 } else {
2692 break;
2693 }
2694 }
2695 loaded++;
2696 }
2697
2698 err = ERR_peek_last_error();
2699 if ((filetype == SSL_FILETYPE_ASN1) &&
2700 (loaded > 0) &&
2701 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2702 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2703 /* EOF ASN1 file, not an error */
2704 ERR_clear_error();
2705 retval = 0;
2706 } else if ((filetype == SSL_FILETYPE_PEM) &&
2707 (loaded > 0) &&
2708 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2709 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2710 /* EOF PEM file, not an error */
2711 ERR_clear_error();
2712 retval = 0;
2713 } else {
2714 _setSSLError(NULL, 0, __FILE__, __LINE__);
2715 retval = -1;
2716 }
2717
2718 BIO_free(biobuf);
2719 return retval;
2720}
2721
2722
2723static PyObject *
2724load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2725{
2726 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2727 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2728 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2729 const char *cafile_buf = NULL, *capath_buf = NULL;
2730 int r = 0, ok = 1;
2731
2732 errno = 0;
2733 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2734 "|OOO:load_verify_locations", kwlist,
2735 &cafile, &capath, &cadata))
2736 return NULL;
2737
2738 if (cafile == Py_None)
2739 cafile = NULL;
2740 if (capath == Py_None)
2741 capath = NULL;
2742 if (cadata == Py_None)
2743 cadata = NULL;
2744
2745 if (cafile == NULL && capath == NULL && cadata == NULL) {
2746 PyErr_SetString(PyExc_TypeError,
2747 "cafile, capath and cadata cannot be all omitted");
2748 goto error;
2749 }
2750
2751 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002752 if (PyString_Check(cafile)) {
2753 Py_INCREF(cafile);
2754 cafile_bytes = cafile;
2755 } else {
2756 PyObject *u = PyUnicode_FromObject(cafile);
2757 if (!u)
2758 goto error;
2759 cafile_bytes = PyUnicode_AsEncodedString(
2760 u, Py_FileSystemDefaultEncoding, NULL);
2761 Py_DECREF(u);
2762 if (!cafile_bytes)
2763 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002764 }
2765 }
2766 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002767 if (PyString_Check(capath)) {
2768 Py_INCREF(capath);
2769 capath_bytes = capath;
2770 } else {
2771 PyObject *u = PyUnicode_FromObject(capath);
2772 if (!u)
2773 goto error;
2774 capath_bytes = PyUnicode_AsEncodedString(
2775 u, Py_FileSystemDefaultEncoding, NULL);
2776 Py_DECREF(u);
2777 if (!capath_bytes)
2778 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002779 }
2780 }
2781
2782 /* validata cadata type and load cadata */
2783 if (cadata) {
2784 Py_buffer buf;
2785 PyObject *cadata_ascii = NULL;
2786
2787 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2788 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2789 PyBuffer_Release(&buf);
2790 PyErr_SetString(PyExc_TypeError,
2791 "cadata should be a contiguous buffer with "
2792 "a single dimension");
2793 goto error;
2794 }
2795 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2796 PyBuffer_Release(&buf);
2797 if (r == -1) {
2798 goto error;
2799 }
2800 } else {
2801 PyErr_Clear();
2802 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2803 if (cadata_ascii == NULL) {
2804 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakac72e66a2015-11-02 15:06:09 +02002805 "cadata should be an ASCII string or a "
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002806 "bytes-like object");
2807 goto error;
2808 }
2809 r = _add_ca_certs(self,
2810 PyBytes_AS_STRING(cadata_ascii),
2811 PyBytes_GET_SIZE(cadata_ascii),
2812 SSL_FILETYPE_PEM);
2813 Py_DECREF(cadata_ascii);
2814 if (r == -1) {
2815 goto error;
2816 }
2817 }
2818 }
2819
2820 /* load cafile or capath */
2821 if (cafile_bytes || capath_bytes) {
2822 if (cafile)
2823 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2824 if (capath)
2825 capath_buf = PyBytes_AS_STRING(capath_bytes);
2826 PySSL_BEGIN_ALLOW_THREADS
2827 r = SSL_CTX_load_verify_locations(
2828 self->ctx,
2829 cafile_buf,
2830 capath_buf);
2831 PySSL_END_ALLOW_THREADS
2832 if (r != 1) {
2833 ok = 0;
2834 if (errno != 0) {
2835 ERR_clear_error();
2836 PyErr_SetFromErrno(PyExc_IOError);
2837 }
2838 else {
2839 _setSSLError(NULL, 0, __FILE__, __LINE__);
2840 }
2841 goto error;
2842 }
2843 }
2844 goto end;
2845
2846 error:
2847 ok = 0;
2848 end:
2849 Py_XDECREF(cafile_bytes);
2850 Py_XDECREF(capath_bytes);
2851 if (ok) {
2852 Py_RETURN_NONE;
2853 } else {
2854 return NULL;
2855 }
2856}
2857
2858static PyObject *
2859load_dh_params(PySSLContext *self, PyObject *filepath)
2860{
2861 BIO *bio;
2862 DH *dh;
2863 char *path = PyBytes_AsString(filepath);
2864 if (!path) {
2865 return NULL;
2866 }
2867
2868 bio = BIO_new_file(path, "r");
2869 if (bio == NULL) {
2870 ERR_clear_error();
2871 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2872 return NULL;
2873 }
2874 errno = 0;
2875 PySSL_BEGIN_ALLOW_THREADS
2876 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2877 BIO_free(bio);
2878 PySSL_END_ALLOW_THREADS
2879 if (dh == NULL) {
2880 if (errno != 0) {
2881 ERR_clear_error();
2882 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2883 }
2884 else {
2885 _setSSLError(NULL, 0, __FILE__, __LINE__);
2886 }
2887 return NULL;
2888 }
2889 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2890 _setSSLError(NULL, 0, __FILE__, __LINE__);
2891 DH_free(dh);
2892 Py_RETURN_NONE;
2893}
2894
2895static PyObject *
2896context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2897{
2898 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2899 PySocketSockObject *sock;
2900 int server_side = 0;
2901 char *hostname = NULL;
2902 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2903
2904 /* server_hostname is either None (or absent), or to be encoded
2905 using the idna encoding. */
2906 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2907 PySocketModule.Sock_Type,
2908 &sock, &server_side,
2909 Py_TYPE(Py_None), &hostname_obj,
2910 &ssl_sock)) {
2911 PyErr_Clear();
2912 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2913 PySocketModule.Sock_Type,
2914 &sock, &server_side,
2915 "idna", &hostname, &ssl_sock))
2916 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002917 }
2918
2919 res = (PyObject *) newPySSLSocket(self, sock, server_side,
2920 hostname, ssl_sock);
2921 if (hostname != NULL)
2922 PyMem_Free(hostname);
2923 return res;
2924}
2925
2926static PyObject *
2927session_stats(PySSLContext *self, PyObject *unused)
2928{
2929 int r;
2930 PyObject *value, *stats = PyDict_New();
2931 if (!stats)
2932 return NULL;
2933
2934#define ADD_STATS(SSL_NAME, KEY_NAME) \
2935 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2936 if (value == NULL) \
2937 goto error; \
2938 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2939 Py_DECREF(value); \
2940 if (r < 0) \
2941 goto error;
2942
2943 ADD_STATS(number, "number");
2944 ADD_STATS(connect, "connect");
2945 ADD_STATS(connect_good, "connect_good");
2946 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2947 ADD_STATS(accept, "accept");
2948 ADD_STATS(accept_good, "accept_good");
2949 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2950 ADD_STATS(accept, "accept");
2951 ADD_STATS(hits, "hits");
2952 ADD_STATS(misses, "misses");
2953 ADD_STATS(timeouts, "timeouts");
2954 ADD_STATS(cache_full, "cache_full");
2955
2956#undef ADD_STATS
2957
2958 return stats;
2959
2960error:
2961 Py_DECREF(stats);
2962 return NULL;
2963}
2964
2965static PyObject *
2966set_default_verify_paths(PySSLContext *self, PyObject *unused)
2967{
2968 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2969 _setSSLError(NULL, 0, __FILE__, __LINE__);
2970 return NULL;
2971 }
2972 Py_RETURN_NONE;
2973}
2974
2975#ifndef OPENSSL_NO_ECDH
2976static PyObject *
2977set_ecdh_curve(PySSLContext *self, PyObject *name)
2978{
2979 char *name_bytes;
2980 int nid;
2981 EC_KEY *key;
2982
2983 name_bytes = PyBytes_AsString(name);
2984 if (!name_bytes) {
2985 return NULL;
2986 }
2987 nid = OBJ_sn2nid(name_bytes);
2988 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002989 PyObject *r = PyObject_Repr(name);
2990 if (!r)
2991 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002992 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002993 "unknown elliptic curve name %s", PyString_AS_STRING(r));
2994 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002995 return NULL;
2996 }
2997 key = EC_KEY_new_by_curve_name(nid);
2998 if (key == NULL) {
2999 _setSSLError(NULL, 0, __FILE__, __LINE__);
3000 return NULL;
3001 }
3002 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3003 EC_KEY_free(key);
3004 Py_RETURN_NONE;
3005}
3006#endif
3007
3008#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3009static int
3010_servername_callback(SSL *s, int *al, void *args)
3011{
3012 int ret;
3013 PySSLContext *ssl_ctx = (PySSLContext *) args;
3014 PySSLSocket *ssl;
3015 PyObject *servername_o;
3016 PyObject *servername_idna;
3017 PyObject *result;
3018 /* The high-level ssl.SSLSocket object */
3019 PyObject *ssl_socket;
3020 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3021#ifdef WITH_THREAD
3022 PyGILState_STATE gstate = PyGILState_Ensure();
3023#endif
3024
3025 if (ssl_ctx->set_hostname == NULL) {
3026 /* remove race condition in this the call back while if removing the
3027 * callback is in progress */
3028#ifdef WITH_THREAD
3029 PyGILState_Release(gstate);
3030#endif
3031 return SSL_TLSEXT_ERR_OK;
3032 }
3033
3034 ssl = SSL_get_app_data(s);
3035 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003036 if (ssl->ssl_sock == NULL) {
3037 ssl_socket = Py_None;
3038 } else {
3039 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3040 Py_INCREF(ssl_socket);
3041 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003042 if (ssl_socket == Py_None) {
3043 goto error;
3044 }
3045
3046 if (servername == NULL) {
3047 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3048 Py_None, ssl_ctx, NULL);
3049 }
3050 else {
3051 servername_o = PyBytes_FromString(servername);
3052 if (servername_o == NULL) {
3053 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3054 goto error;
3055 }
3056 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3057 if (servername_idna == NULL) {
3058 PyErr_WriteUnraisable(servername_o);
3059 Py_DECREF(servername_o);
3060 goto error;
3061 }
3062 Py_DECREF(servername_o);
3063 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3064 servername_idna, ssl_ctx, NULL);
3065 Py_DECREF(servername_idna);
3066 }
3067 Py_DECREF(ssl_socket);
3068
3069 if (result == NULL) {
3070 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3071 *al = SSL_AD_HANDSHAKE_FAILURE;
3072 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3073 }
3074 else {
3075 if (result != Py_None) {
3076 *al = (int) PyLong_AsLong(result);
3077 if (PyErr_Occurred()) {
3078 PyErr_WriteUnraisable(result);
3079 *al = SSL_AD_INTERNAL_ERROR;
3080 }
3081 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3082 }
3083 else {
3084 ret = SSL_TLSEXT_ERR_OK;
3085 }
3086 Py_DECREF(result);
3087 }
3088
3089#ifdef WITH_THREAD
3090 PyGILState_Release(gstate);
3091#endif
3092 return ret;
3093
3094error:
3095 Py_DECREF(ssl_socket);
3096 *al = SSL_AD_INTERNAL_ERROR;
3097 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3098#ifdef WITH_THREAD
3099 PyGILState_Release(gstate);
3100#endif
3101 return ret;
3102}
3103#endif
3104
3105PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3106"set_servername_callback(method)\n\
3107\n\
3108This sets a callback that will be called when a server name is provided by\n\
3109the SSL/TLS client in the SNI extension.\n\
3110\n\
3111If the argument is None then the callback is disabled. The method is called\n\
3112with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3113See RFC 6066 for details of the SNI extension.");
3114
3115static PyObject *
3116set_servername_callback(PySSLContext *self, PyObject *args)
3117{
3118#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3119 PyObject *cb;
3120
3121 if (!PyArg_ParseTuple(args, "O", &cb))
3122 return NULL;
3123
3124 Py_CLEAR(self->set_hostname);
3125 if (cb == Py_None) {
3126 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3127 }
3128 else {
3129 if (!PyCallable_Check(cb)) {
3130 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3131 PyErr_SetString(PyExc_TypeError,
3132 "not a callable object");
3133 return NULL;
3134 }
3135 Py_INCREF(cb);
3136 self->set_hostname = cb;
3137 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3138 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3139 }
3140 Py_RETURN_NONE;
3141#else
3142 PyErr_SetString(PyExc_NotImplementedError,
3143 "The TLS extension servername callback, "
3144 "SSL_CTX_set_tlsext_servername_callback, "
3145 "is not in the current OpenSSL library.");
3146 return NULL;
3147#endif
3148}
3149
3150PyDoc_STRVAR(PySSL_get_stats_doc,
3151"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3152\n\
3153Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3154CA extension and certificate revocation lists inside the context's cert\n\
3155store.\n\
3156NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3157been used at least once.");
3158
3159static PyObject *
3160cert_store_stats(PySSLContext *self)
3161{
3162 X509_STORE *store;
3163 X509_OBJECT *obj;
3164 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3165
3166 store = SSL_CTX_get_cert_store(self->ctx);
3167 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3168 obj = sk_X509_OBJECT_value(store->objs, i);
3169 switch (obj->type) {
3170 case X509_LU_X509:
3171 x509++;
3172 if (X509_check_ca(obj->data.x509)) {
3173 ca++;
3174 }
3175 break;
3176 case X509_LU_CRL:
3177 crl++;
3178 break;
3179 case X509_LU_PKEY:
3180 pkey++;
3181 break;
3182 default:
3183 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3184 * As far as I can tell they are internal states and never
3185 * stored in a cert store */
3186 break;
3187 }
3188 }
3189 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3190 "x509_ca", ca);
3191}
3192
3193PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3194"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3195\n\
3196Returns a list of dicts with information of loaded CA certs. If the\n\
3197optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3198NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3199been used at least once.");
3200
3201static PyObject *
3202get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3203{
3204 char *kwlist[] = {"binary_form", NULL};
3205 X509_STORE *store;
3206 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3207 int i;
3208 int binary_mode = 0;
3209
3210 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3211 kwlist, &py_binary_mode)) {
3212 return NULL;
3213 }
3214 binary_mode = PyObject_IsTrue(py_binary_mode);
3215 if (binary_mode < 0) {
3216 return NULL;
3217 }
3218
3219 if ((rlist = PyList_New(0)) == NULL) {
3220 return NULL;
3221 }
3222
3223 store = SSL_CTX_get_cert_store(self->ctx);
3224 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3225 X509_OBJECT *obj;
3226 X509 *cert;
3227
3228 obj = sk_X509_OBJECT_value(store->objs, i);
3229 if (obj->type != X509_LU_X509) {
3230 /* not a x509 cert */
3231 continue;
3232 }
3233 /* CA for any purpose */
3234 cert = obj->data.x509;
3235 if (!X509_check_ca(cert)) {
3236 continue;
3237 }
3238 if (binary_mode) {
3239 ci = _certificate_to_der(cert);
3240 } else {
3241 ci = _decode_certificate(cert);
3242 }
3243 if (ci == NULL) {
3244 goto error;
3245 }
3246 if (PyList_Append(rlist, ci) == -1) {
3247 goto error;
3248 }
3249 Py_CLEAR(ci);
3250 }
3251 return rlist;
3252
3253 error:
3254 Py_XDECREF(ci);
3255 Py_XDECREF(rlist);
3256 return NULL;
3257}
3258
3259
3260static PyGetSetDef context_getsetlist[] = {
3261 {"check_hostname", (getter) get_check_hostname,
3262 (setter) set_check_hostname, NULL},
3263 {"options", (getter) get_options,
3264 (setter) set_options, NULL},
3265#ifdef HAVE_OPENSSL_VERIFY_PARAM
3266 {"verify_flags", (getter) get_verify_flags,
3267 (setter) set_verify_flags, NULL},
3268#endif
3269 {"verify_mode", (getter) get_verify_mode,
3270 (setter) set_verify_mode, NULL},
3271 {NULL}, /* sentinel */
3272};
3273
3274static struct PyMethodDef context_methods[] = {
3275 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3276 METH_VARARGS | METH_KEYWORDS, NULL},
3277 {"set_ciphers", (PyCFunction) set_ciphers,
3278 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003279 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3280 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003281 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3282 METH_VARARGS, NULL},
3283 {"load_cert_chain", (PyCFunction) load_cert_chain,
3284 METH_VARARGS | METH_KEYWORDS, NULL},
3285 {"load_dh_params", (PyCFunction) load_dh_params,
3286 METH_O, NULL},
3287 {"load_verify_locations", (PyCFunction) load_verify_locations,
3288 METH_VARARGS | METH_KEYWORDS, NULL},
3289 {"session_stats", (PyCFunction) session_stats,
3290 METH_NOARGS, NULL},
3291 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3292 METH_NOARGS, NULL},
3293#ifndef OPENSSL_NO_ECDH
3294 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3295 METH_O, NULL},
3296#endif
3297 {"set_servername_callback", (PyCFunction) set_servername_callback,
3298 METH_VARARGS, PySSL_set_servername_callback_doc},
3299 {"cert_store_stats", (PyCFunction) cert_store_stats,
3300 METH_NOARGS, PySSL_get_stats_doc},
3301 {"get_ca_certs", (PyCFunction) get_ca_certs,
3302 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3303 {NULL, NULL} /* sentinel */
3304};
3305
3306static PyTypeObject PySSLContext_Type = {
3307 PyVarObject_HEAD_INIT(NULL, 0)
3308 "_ssl._SSLContext", /*tp_name*/
3309 sizeof(PySSLContext), /*tp_basicsize*/
3310 0, /*tp_itemsize*/
3311 (destructor)context_dealloc, /*tp_dealloc*/
3312 0, /*tp_print*/
3313 0, /*tp_getattr*/
3314 0, /*tp_setattr*/
3315 0, /*tp_reserved*/
3316 0, /*tp_repr*/
3317 0, /*tp_as_number*/
3318 0, /*tp_as_sequence*/
3319 0, /*tp_as_mapping*/
3320 0, /*tp_hash*/
3321 0, /*tp_call*/
3322 0, /*tp_str*/
3323 0, /*tp_getattro*/
3324 0, /*tp_setattro*/
3325 0, /*tp_as_buffer*/
3326 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3327 0, /*tp_doc*/
3328 (traverseproc) context_traverse, /*tp_traverse*/
3329 (inquiry) context_clear, /*tp_clear*/
3330 0, /*tp_richcompare*/
3331 0, /*tp_weaklistoffset*/
3332 0, /*tp_iter*/
3333 0, /*tp_iternext*/
3334 context_methods, /*tp_methods*/
3335 0, /*tp_members*/
3336 context_getsetlist, /*tp_getset*/
3337 0, /*tp_base*/
3338 0, /*tp_dict*/
3339 0, /*tp_descr_get*/
3340 0, /*tp_descr_set*/
3341 0, /*tp_dictoffset*/
3342 0, /*tp_init*/
3343 0, /*tp_alloc*/
3344 context_new, /*tp_new*/
3345};
3346
3347
3348
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003349#ifdef HAVE_OPENSSL_RAND
3350
3351/* helper routines for seeding the SSL PRNG */
3352static PyObject *
3353PySSL_RAND_add(PyObject *self, PyObject *args)
3354{
3355 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003356 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003357 double entropy;
3358
3359 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003360 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003361 do {
3362 if (len >= INT_MAX) {
3363 written = INT_MAX;
3364 } else {
3365 written = len;
3366 }
3367 RAND_add(buf, (int)written, entropy);
3368 buf += written;
3369 len -= written;
3370 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003371 Py_INCREF(Py_None);
3372 return Py_None;
3373}
3374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003375PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003376"RAND_add(string, entropy)\n\
3377\n\
3378Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003379bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003380
3381static PyObject *
3382PySSL_RAND_status(PyObject *self)
3383{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003384 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003385}
3386
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003387PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003388"RAND_status() -> 0 or 1\n\
3389\n\
3390Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3391It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003392using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003393
Victor Stinner7c906672015-01-06 13:53:37 +01003394#endif /* HAVE_OPENSSL_RAND */
3395
3396
Benjamin Peterson42e10292016-07-07 00:02:31 -07003397#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003398
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003399static PyObject *
3400PySSL_RAND_egd(PyObject *self, PyObject *arg)
3401{
3402 int bytes;
3403
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003404 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003405 return PyErr_Format(PyExc_TypeError,
3406 "RAND_egd() expected string, found %s",
3407 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003408 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003409 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003410 PyErr_SetString(PySSLErrorObject,
3411 "EGD connection failed or EGD did not return "
3412 "enough data to seed the PRNG");
3413 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003414 }
3415 return PyInt_FromLong(bytes);
3416}
3417
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003418PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003419"RAND_egd(path) -> bytes\n\
3420\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003421Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3422Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003423fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003424
Benjamin Peterson42e10292016-07-07 00:02:31 -07003425#endif /* !OPENSSL_NO_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003426
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003427
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003428PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3429"get_default_verify_paths() -> tuple\n\
3430\n\
3431Return search paths and environment vars that are used by SSLContext's\n\
3432set_default_verify_paths() to load default CAs. The values are\n\
3433'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3434
3435static PyObject *
3436PySSL_get_default_verify_paths(PyObject *self)
3437{
3438 PyObject *ofile_env = NULL;
3439 PyObject *ofile = NULL;
3440 PyObject *odir_env = NULL;
3441 PyObject *odir = NULL;
3442
Benjamin Peterson65192c12015-07-18 10:59:13 -07003443#define CONVERT(info, target) { \
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003444 const char *tmp = (info); \
3445 target = NULL; \
3446 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3447 else { target = PyBytes_FromString(tmp); } \
3448 if (!target) goto error; \
Benjamin Peterson93ed9462015-11-14 15:12:38 -08003449 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003450
Benjamin Peterson65192c12015-07-18 10:59:13 -07003451 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3452 CONVERT(X509_get_default_cert_file(), ofile);
3453 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3454 CONVERT(X509_get_default_cert_dir(), odir);
3455#undef CONVERT
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003456
3457 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3458
3459 error:
3460 Py_XDECREF(ofile_env);
3461 Py_XDECREF(ofile);
3462 Py_XDECREF(odir_env);
3463 Py_XDECREF(odir);
3464 return NULL;
3465}
3466
3467static PyObject*
3468asn1obj2py(ASN1_OBJECT *obj)
3469{
3470 int nid;
3471 const char *ln, *sn;
3472 char buf[100];
3473 Py_ssize_t buflen;
3474
3475 nid = OBJ_obj2nid(obj);
3476 if (nid == NID_undef) {
3477 PyErr_Format(PyExc_ValueError, "Unknown object");
3478 return NULL;
3479 }
3480 sn = OBJ_nid2sn(nid);
3481 ln = OBJ_nid2ln(nid);
3482 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3483 if (buflen < 0) {
3484 _setSSLError(NULL, 0, __FILE__, __LINE__);
3485 return NULL;
3486 }
3487 if (buflen) {
3488 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3489 } else {
3490 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3491 }
3492}
3493
3494PyDoc_STRVAR(PySSL_txt2obj_doc,
3495"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3496\n\
3497Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3498objects are looked up by OID. With name=True short and long name are also\n\
3499matched.");
3500
3501static PyObject*
3502PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3503{
3504 char *kwlist[] = {"txt", "name", NULL};
3505 PyObject *result = NULL;
3506 char *txt;
3507 PyObject *pyname = Py_None;
3508 int name = 0;
3509 ASN1_OBJECT *obj;
3510
3511 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3512 kwlist, &txt, &pyname)) {
3513 return NULL;
3514 }
3515 name = PyObject_IsTrue(pyname);
3516 if (name < 0)
3517 return NULL;
3518 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3519 if (obj == NULL) {
3520 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3521 return NULL;
3522 }
3523 result = asn1obj2py(obj);
3524 ASN1_OBJECT_free(obj);
3525 return result;
3526}
3527
3528PyDoc_STRVAR(PySSL_nid2obj_doc,
3529"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3530\n\
3531Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3532
3533static PyObject*
3534PySSL_nid2obj(PyObject *self, PyObject *args)
3535{
3536 PyObject *result = NULL;
3537 int nid;
3538 ASN1_OBJECT *obj;
3539
3540 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3541 return NULL;
3542 }
3543 if (nid < NID_undef) {
3544 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3545 return NULL;
3546 }
3547 obj = OBJ_nid2obj(nid);
3548 if (obj == NULL) {
3549 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3550 return NULL;
3551 }
3552 result = asn1obj2py(obj);
3553 ASN1_OBJECT_free(obj);
3554 return result;
3555}
3556
3557#ifdef _MSC_VER
3558
3559static PyObject*
3560certEncodingType(DWORD encodingType)
3561{
3562 static PyObject *x509_asn = NULL;
3563 static PyObject *pkcs_7_asn = NULL;
3564
3565 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003566 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003567 if (x509_asn == NULL)
3568 return NULL;
3569 }
3570 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003571 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003572 if (pkcs_7_asn == NULL)
3573 return NULL;
3574 }
3575 switch(encodingType) {
3576 case X509_ASN_ENCODING:
3577 Py_INCREF(x509_asn);
3578 return x509_asn;
3579 case PKCS_7_ASN_ENCODING:
3580 Py_INCREF(pkcs_7_asn);
3581 return pkcs_7_asn;
3582 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003583 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003584 }
3585}
3586
3587static PyObject*
3588parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3589{
3590 CERT_ENHKEY_USAGE *usage;
3591 DWORD size, error, i;
3592 PyObject *retval;
3593
3594 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3595 error = GetLastError();
3596 if (error == CRYPT_E_NOT_FOUND) {
3597 Py_RETURN_TRUE;
3598 }
3599 return PyErr_SetFromWindowsErr(error);
3600 }
3601
3602 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3603 if (usage == NULL) {
3604 return PyErr_NoMemory();
3605 }
3606
3607 /* Now get the actual enhanced usage property */
3608 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3609 PyMem_Free(usage);
3610 error = GetLastError();
3611 if (error == CRYPT_E_NOT_FOUND) {
3612 Py_RETURN_TRUE;
3613 }
3614 return PyErr_SetFromWindowsErr(error);
3615 }
3616 retval = PySet_New(NULL);
3617 if (retval == NULL) {
3618 goto error;
3619 }
3620 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3621 if (usage->rgpszUsageIdentifier[i]) {
3622 PyObject *oid;
3623 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003624 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003625 if (oid == NULL) {
3626 Py_CLEAR(retval);
3627 goto error;
3628 }
3629 err = PySet_Add(retval, oid);
3630 Py_DECREF(oid);
3631 if (err == -1) {
3632 Py_CLEAR(retval);
3633 goto error;
3634 }
3635 }
3636 }
3637 error:
3638 PyMem_Free(usage);
3639 return retval;
3640}
3641
3642PyDoc_STRVAR(PySSL_enum_certificates_doc,
3643"enum_certificates(store_name) -> []\n\
3644\n\
3645Retrieve certificates from Windows' cert store. store_name may be one of\n\
3646'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3647The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3648encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3649PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3650boolean True.");
3651
3652static PyObject *
3653PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3654{
3655 char *kwlist[] = {"store_name", NULL};
3656 char *store_name;
3657 HCERTSTORE hStore = NULL;
3658 PCCERT_CONTEXT pCertCtx = NULL;
3659 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3660 PyObject *result = NULL;
3661
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003662 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003663 kwlist, &store_name)) {
3664 return NULL;
3665 }
3666 result = PyList_New(0);
3667 if (result == NULL) {
3668 return NULL;
3669 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003670 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3671 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3672 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003673 if (hStore == NULL) {
3674 Py_DECREF(result);
3675 return PyErr_SetFromWindowsErr(GetLastError());
3676 }
3677
3678 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3679 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3680 pCertCtx->cbCertEncoded);
3681 if (!cert) {
3682 Py_CLEAR(result);
3683 break;
3684 }
3685 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3686 Py_CLEAR(result);
3687 break;
3688 }
3689 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3690 if (keyusage == Py_True) {
3691 Py_DECREF(keyusage);
3692 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3693 }
3694 if (keyusage == NULL) {
3695 Py_CLEAR(result);
3696 break;
3697 }
3698 if ((tup = PyTuple_New(3)) == NULL) {
3699 Py_CLEAR(result);
3700 break;
3701 }
3702 PyTuple_SET_ITEM(tup, 0, cert);
3703 cert = NULL;
3704 PyTuple_SET_ITEM(tup, 1, enc);
3705 enc = NULL;
3706 PyTuple_SET_ITEM(tup, 2, keyusage);
3707 keyusage = NULL;
3708 if (PyList_Append(result, tup) < 0) {
3709 Py_CLEAR(result);
3710 break;
3711 }
3712 Py_CLEAR(tup);
3713 }
3714 if (pCertCtx) {
3715 /* loop ended with an error, need to clean up context manually */
3716 CertFreeCertificateContext(pCertCtx);
3717 }
3718
3719 /* In error cases cert, enc and tup may not be NULL */
3720 Py_XDECREF(cert);
3721 Py_XDECREF(enc);
3722 Py_XDECREF(keyusage);
3723 Py_XDECREF(tup);
3724
3725 if (!CertCloseStore(hStore, 0)) {
3726 /* This error case might shadow another exception.*/
3727 Py_XDECREF(result);
3728 return PyErr_SetFromWindowsErr(GetLastError());
3729 }
3730 return result;
3731}
3732
3733PyDoc_STRVAR(PySSL_enum_crls_doc,
3734"enum_crls(store_name) -> []\n\
3735\n\
3736Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3737'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3738The function returns a list of (bytes, encoding_type) tuples. The\n\
3739encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3740PKCS_7_ASN_ENCODING.");
3741
3742static PyObject *
3743PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3744{
3745 char *kwlist[] = {"store_name", NULL};
3746 char *store_name;
3747 HCERTSTORE hStore = NULL;
3748 PCCRL_CONTEXT pCrlCtx = NULL;
3749 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3750 PyObject *result = NULL;
3751
Benjamin Peterson9c5a8d42015-04-06 13:05:22 -04003752 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003753 kwlist, &store_name)) {
3754 return NULL;
3755 }
3756 result = PyList_New(0);
3757 if (result == NULL) {
3758 return NULL;
3759 }
Benjamin Petersonb2e39462016-02-17 22:13:19 -08003760 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
3761 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
3762 store_name);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003763 if (hStore == NULL) {
3764 Py_DECREF(result);
3765 return PyErr_SetFromWindowsErr(GetLastError());
3766 }
3767
3768 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3769 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3770 pCrlCtx->cbCrlEncoded);
3771 if (!crl) {
3772 Py_CLEAR(result);
3773 break;
3774 }
3775 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3776 Py_CLEAR(result);
3777 break;
3778 }
3779 if ((tup = PyTuple_New(2)) == NULL) {
3780 Py_CLEAR(result);
3781 break;
3782 }
3783 PyTuple_SET_ITEM(tup, 0, crl);
3784 crl = NULL;
3785 PyTuple_SET_ITEM(tup, 1, enc);
3786 enc = NULL;
3787
3788 if (PyList_Append(result, tup) < 0) {
3789 Py_CLEAR(result);
3790 break;
3791 }
3792 Py_CLEAR(tup);
3793 }
3794 if (pCrlCtx) {
3795 /* loop ended with an error, need to clean up context manually */
3796 CertFreeCRLContext(pCrlCtx);
3797 }
3798
3799 /* In error cases cert, enc and tup may not be NULL */
3800 Py_XDECREF(crl);
3801 Py_XDECREF(enc);
3802 Py_XDECREF(tup);
3803
3804 if (!CertCloseStore(hStore, 0)) {
3805 /* This error case might shadow another exception.*/
3806 Py_XDECREF(result);
3807 return PyErr_SetFromWindowsErr(GetLastError());
3808 }
3809 return result;
3810}
3811
3812#endif /* _MSC_VER */
3813
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003814/* List of functions exported by this module. */
3815
3816static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003817 {"_test_decode_cert", PySSL_test_decode_certificate,
3818 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003819#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003820 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3821 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003822 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3823 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003824#endif
Benjamin Peterson42e10292016-07-07 00:02:31 -07003825#ifndef OPENSSL_NO_EGD
Victor Stinner7c906672015-01-06 13:53:37 +01003826 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3827 PySSL_RAND_egd_doc},
3828#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003829 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3830 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3831#ifdef _MSC_VER
3832 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3833 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3834 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3835 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3836#endif
3837 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3838 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3839 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3840 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003841 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003842};
3843
3844
Bill Janssen98d19da2007-09-10 21:51:02 +00003845#ifdef WITH_THREAD
3846
3847/* an implementation of OpenSSL threading operations in terms
3848 of the Python C thread library */
3849
3850static PyThread_type_lock *_ssl_locks = NULL;
3851
Christian Heimes10107812013-08-19 17:36:29 +02003852#if OPENSSL_VERSION_NUMBER >= 0x10000000
3853/* use new CRYPTO_THREADID API. */
3854static void
3855_ssl_threadid_callback(CRYPTO_THREADID *id)
3856{
3857 CRYPTO_THREADID_set_numeric(id,
3858 (unsigned long)PyThread_get_thread_ident());
3859}
3860#else
3861/* deprecated CRYPTO_set_id_callback() API. */
3862static unsigned long
3863_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003864 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003865}
Christian Heimes10107812013-08-19 17:36:29 +02003866#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003867
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003868static void _ssl_thread_locking_function
3869 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003870 /* this function is needed to perform locking on shared data
3871 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003872 structures that will be implicitly shared whenever multiple
3873 threads use OpenSSL.) Multi-threaded applications will
3874 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003875
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003876 locking_function() must be able to handle up to
3877 CRYPTO_num_locks() different mutex locks. It sets the n-th
3878 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003879
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003880 file and line are the file number of the function setting the
3881 lock. They can be useful for debugging.
3882 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003883
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003884 if ((_ssl_locks == NULL) ||
3885 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3886 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003887
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003888 if (mode & CRYPTO_LOCK) {
3889 PyThread_acquire_lock(_ssl_locks[n], 1);
3890 } else {
3891 PyThread_release_lock(_ssl_locks[n]);
3892 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003893}
3894
3895static int _setup_ssl_threads(void) {
3896
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003897 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003898
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003899 if (_ssl_locks == NULL) {
3900 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003901 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
3902 if (_ssl_locks == NULL) {
3903 PyErr_NoMemory();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003904 return 0;
Serhiy Storchakaa2269d02015-02-16 13:16:07 +02003905 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003906 memset(_ssl_locks, 0,
3907 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003908 for (i = 0; i < _ssl_locks_count; i++) {
3909 _ssl_locks[i] = PyThread_allocate_lock();
3910 if (_ssl_locks[i] == NULL) {
3911 unsigned int j;
3912 for (j = 0; j < i; j++) {
3913 PyThread_free_lock(_ssl_locks[j]);
3914 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003915 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003916 return 0;
3917 }
3918 }
3919 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02003920#if OPENSSL_VERSION_NUMBER >= 0x10000000
3921 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3922#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003923 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02003924#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003925 }
3926 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00003927}
3928
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003929#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00003930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003931PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003932"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003933for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003934
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003935
3936
3937
3938static void
3939parse_openssl_version(unsigned long libver,
3940 unsigned int *major, unsigned int *minor,
3941 unsigned int *fix, unsigned int *patch,
3942 unsigned int *status)
3943{
3944 *status = libver & 0xF;
3945 libver >>= 4;
3946 *patch = libver & 0xFF;
3947 libver >>= 8;
3948 *fix = libver & 0xFF;
3949 libver >>= 8;
3950 *minor = libver & 0xFF;
3951 libver >>= 8;
3952 *major = libver & 0xFF;
3953}
3954
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003955PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003956init_ssl(void)
3957{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003958 PyObject *m, *d, *r;
3959 unsigned long libver;
3960 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003961 struct py_ssl_error_code *errcode;
3962 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003963
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003964 if (PyType_Ready(&PySSLContext_Type) < 0)
3965 return;
3966 if (PyType_Ready(&PySSLSocket_Type) < 0)
3967 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003968
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003969 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
3970 if (m == NULL)
3971 return;
3972 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003973
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003974 /* Load _socket module and its C API */
3975 if (PySocketModule_ImportModuleAndAPI())
3976 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003977
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003978 /* Init OpenSSL */
3979 SSL_load_error_strings();
3980 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00003981#ifdef WITH_THREAD
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003982 /* note that this will start threading if not already started */
3983 if (!_setup_ssl_threads()) {
3984 return;
3985 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003986#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003987 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003988
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003989 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003990 PySSLErrorObject = PyErr_NewExceptionWithDoc(
3991 "ssl.SSLError", SSLError_doc,
3992 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003993 if (PySSLErrorObject == NULL)
3994 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003995 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
3996
3997 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3998 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3999 PySSLErrorObject, NULL);
4000 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4001 "ssl.SSLWantReadError", SSLWantReadError_doc,
4002 PySSLErrorObject, NULL);
4003 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4004 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4005 PySSLErrorObject, NULL);
4006 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4007 "ssl.SSLSyscallError", SSLSyscallError_doc,
4008 PySSLErrorObject, NULL);
4009 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4010 "ssl.SSLEOFError", SSLEOFError_doc,
4011 PySSLErrorObject, NULL);
4012 if (PySSLZeroReturnErrorObject == NULL
4013 || PySSLWantReadErrorObject == NULL
4014 || PySSLWantWriteErrorObject == NULL
4015 || PySSLSyscallErrorObject == NULL
4016 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004017 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004018
4019 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4020 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4021 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4022 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4023 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4024
4025 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4026 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4027 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4028 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4029 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4030 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4031 return;
4032 if (PyDict_SetItemString(d, "_SSLContext",
4033 (PyObject *)&PySSLContext_Type) != 0)
4034 return;
4035 if (PyDict_SetItemString(d, "_SSLSocket",
4036 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004037 return;
4038 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4039 PY_SSL_ERROR_ZERO_RETURN);
4040 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4041 PY_SSL_ERROR_WANT_READ);
4042 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4043 PY_SSL_ERROR_WANT_WRITE);
4044 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4045 PY_SSL_ERROR_WANT_X509_LOOKUP);
4046 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4047 PY_SSL_ERROR_SYSCALL);
4048 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4049 PY_SSL_ERROR_SSL);
4050 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4051 PY_SSL_ERROR_WANT_CONNECT);
4052 /* non ssl.h errorcodes */
4053 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4054 PY_SSL_ERROR_EOF);
4055 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4056 PY_SSL_ERROR_INVALID_ERROR_CODE);
4057 /* cert requirements */
4058 PyModule_AddIntConstant(m, "CERT_NONE",
4059 PY_SSL_CERT_NONE);
4060 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4061 PY_SSL_CERT_OPTIONAL);
4062 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4063 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004064 /* CRL verification for verification_flags */
4065 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4066 0);
4067 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4068 X509_V_FLAG_CRL_CHECK);
4069 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4070 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4071 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4072 X509_V_FLAG_X509_STRICT);
Benjamin Peterson72ef9612015-03-04 22:49:41 -05004073#ifdef X509_V_FLAG_TRUSTED_FIRST
4074 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4075 X509_V_FLAG_TRUSTED_FIRST);
4076#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004077
4078 /* Alert Descriptions from ssl.h */
4079 /* note RESERVED constants no longer intended for use have been removed */
4080 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4081
4082#define ADD_AD_CONSTANT(s) \
4083 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4084 SSL_AD_##s)
4085
4086 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4087 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4088 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4089 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4090 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4091 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4092 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4093 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4094 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4095 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4096 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4097 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4098 ADD_AD_CONSTANT(UNKNOWN_CA);
4099 ADD_AD_CONSTANT(ACCESS_DENIED);
4100 ADD_AD_CONSTANT(DECODE_ERROR);
4101 ADD_AD_CONSTANT(DECRYPT_ERROR);
4102 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4103 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4104 ADD_AD_CONSTANT(INTERNAL_ERROR);
4105 ADD_AD_CONSTANT(USER_CANCELLED);
4106 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4107 /* Not all constants are in old OpenSSL versions */
4108#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4109 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4110#endif
4111#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4112 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4113#endif
4114#ifdef SSL_AD_UNRECOGNIZED_NAME
4115 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4116#endif
4117#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4118 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4119#endif
4120#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4121 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4122#endif
4123#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4124 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4125#endif
4126
4127#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004128
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004129 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004130#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004131 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4132 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004133#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004134#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004135 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4136 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004137#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004138 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4139 PY_SSL_VERSION_SSL23);
4140 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4141 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004142#if HAVE_TLSv1_2
4143 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4144 PY_SSL_VERSION_TLS1_1);
4145 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4146 PY_SSL_VERSION_TLS1_2);
4147#endif
4148
4149 /* protocol options */
4150 PyModule_AddIntConstant(m, "OP_ALL",
4151 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4152 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4153 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4154 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4155#if HAVE_TLSv1_2
4156 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4157 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4158#endif
4159 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4160 SSL_OP_CIPHER_SERVER_PREFERENCE);
4161 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4162#ifdef SSL_OP_SINGLE_ECDH_USE
4163 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4164#endif
4165#ifdef SSL_OP_NO_COMPRESSION
4166 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4167 SSL_OP_NO_COMPRESSION);
4168#endif
4169
4170#if HAVE_SNI
4171 r = Py_True;
4172#else
4173 r = Py_False;
4174#endif
4175 Py_INCREF(r);
4176 PyModule_AddObject(m, "HAS_SNI", r);
4177
4178#if HAVE_OPENSSL_FINISHED
4179 r = Py_True;
4180#else
4181 r = Py_False;
4182#endif
4183 Py_INCREF(r);
4184 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4185
4186#ifdef OPENSSL_NO_ECDH
4187 r = Py_False;
4188#else
4189 r = Py_True;
4190#endif
4191 Py_INCREF(r);
4192 PyModule_AddObject(m, "HAS_ECDH", r);
4193
4194#ifdef OPENSSL_NPN_NEGOTIATED
4195 r = Py_True;
4196#else
4197 r = Py_False;
4198#endif
4199 Py_INCREF(r);
4200 PyModule_AddObject(m, "HAS_NPN", r);
4201
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004202#ifdef HAVE_ALPN
4203 r = Py_True;
4204#else
4205 r = Py_False;
4206#endif
4207 Py_INCREF(r);
4208 PyModule_AddObject(m, "HAS_ALPN", r);
4209
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004210 /* Mappings for error codes */
4211 err_codes_to_names = PyDict_New();
4212 err_names_to_codes = PyDict_New();
4213 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4214 return;
4215 errcode = error_codes;
4216 while (errcode->mnemonic != NULL) {
4217 PyObject *mnemo, *key;
4218 mnemo = PyUnicode_FromString(errcode->mnemonic);
4219 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4220 if (mnemo == NULL || key == NULL)
4221 return;
4222 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4223 return;
4224 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4225 return;
4226 Py_DECREF(key);
4227 Py_DECREF(mnemo);
4228 errcode++;
4229 }
4230 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4231 return;
4232 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4233 return;
4234
4235 lib_codes_to_names = PyDict_New();
4236 if (lib_codes_to_names == NULL)
4237 return;
4238 libcode = library_codes;
4239 while (libcode->library != NULL) {
4240 PyObject *mnemo, *key;
4241 key = PyLong_FromLong(libcode->code);
4242 mnemo = PyUnicode_FromString(libcode->library);
4243 if (key == NULL || mnemo == NULL)
4244 return;
4245 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4246 return;
4247 Py_DECREF(key);
4248 Py_DECREF(mnemo);
4249 libcode++;
4250 }
4251 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4252 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004253
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004254 /* OpenSSL version */
4255 /* SSLeay() gives us the version of the library linked against,
4256 which could be different from the headers version.
4257 */
4258 libver = SSLeay();
4259 r = PyLong_FromUnsignedLong(libver);
4260 if (r == NULL)
4261 return;
4262 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4263 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004264 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004265 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4266 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4267 return;
4268 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4269 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4270 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004271
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004272 libver = OPENSSL_VERSION_NUMBER;
4273 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4274 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4275 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4276 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004277}