blob: 9dc085922a78d3b87dc6f70939d2102bb58205d0 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Benjamin Petersondaeb9252014-08-20 14:14:50 -050017#define PY_SSIZE_T_CLEAN
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000018#include "Python.h"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000019
Bill Janssen98d19da2007-09-10 21:51:02 +000020#ifdef WITH_THREAD
21#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020022
Christian Heimes0d604cf2013-08-21 13:26:05 +020023
Benjamin Petersondaeb9252014-08-20 14:14:50 -050024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Bill Janssen98d19da2007-09-10 21:51:02 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000029 PyThreadState *_save = NULL; \
Benjamin Petersondaeb9252014-08-20 14:14:50 -050030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Bill Janssen98d19da2007-09-10 21:51:02 +000034
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000035#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000036
Benjamin Petersondaeb9252014-08-20 14:14:50 -050037#define PySSL_BEGIN_ALLOW_THREADS_S(save)
38#define PySSL_END_ALLOW_THREADS_S(save)
Bill Janssen98d19da2007-09-10 21:51:02 +000039#define PySSL_BEGIN_ALLOW_THREADS
40#define PySSL_BLOCK_THREADS
41#define PySSL_UNBLOCK_THREADS
42#define PySSL_END_ALLOW_THREADS
43
44#endif
45
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000046/* Include symbols from _socket module */
47#include "socketmodule.h"
48
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000049#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000050#include <poll.h>
51#elif defined(HAVE_SYS_POLL_H)
52#include <sys/poll.h>
53#endif
54
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000055/* Include OpenSSL header files */
56#include "openssl/rsa.h"
57#include "openssl/crypto.h"
58#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000059#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000060#include "openssl/pem.h"
61#include "openssl/ssl.h"
62#include "openssl/err.h"
63#include "openssl/rand.h"
64
65/* SSL error object */
66static PyObject *PySSLErrorObject;
Benjamin Petersondaeb9252014-08-20 14:14:50 -050067static PyObject *PySSLZeroReturnErrorObject;
68static PyObject *PySSLWantReadErrorObject;
69static PyObject *PySSLWantWriteErrorObject;
70static PyObject *PySSLSyscallErrorObject;
71static PyObject *PySSLEOFErrorObject;
72
73/* Error mappings */
74static PyObject *err_codes_to_names;
75static PyObject *err_names_to_codes;
76static PyObject *lib_codes_to_names;
77
78struct py_ssl_error_code {
79 const char *mnemonic;
80 int library, reason;
81};
82struct py_ssl_library_code {
83 const char *library;
84 int code;
85};
86
87/* Include generated data (error codes) */
88#include "_ssl_data.h"
89
90/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
91 http://www.openssl.org/news/changelog.html
92 */
93#if OPENSSL_VERSION_NUMBER >= 0x10001000L
94# define HAVE_TLSv1_2 1
95#else
96# define HAVE_TLSv1_2 0
97#endif
98
99/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
100 * This includes the SSL_set_SSL_CTX() function.
101 */
102#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
103# define HAVE_SNI 1
104#else
105# define HAVE_SNI 0
106#endif
107
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500108/* ALPN added in OpenSSL 1.0.2 */
Benjamin Petersonf4bb2312015-01-27 11:10:18 -0500109#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500110# define HAVE_ALPN
111#endif
112
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500113enum py_ssl_error {
114 /* these mirror ssl.h */
115 PY_SSL_ERROR_NONE,
116 PY_SSL_ERROR_SSL,
117 PY_SSL_ERROR_WANT_READ,
118 PY_SSL_ERROR_WANT_WRITE,
119 PY_SSL_ERROR_WANT_X509_LOOKUP,
120 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
121 PY_SSL_ERROR_ZERO_RETURN,
122 PY_SSL_ERROR_WANT_CONNECT,
123 /* start of non ssl.h errorcodes */
124 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
125 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
126 PY_SSL_ERROR_INVALID_ERROR_CODE
127};
128
129enum py_ssl_server_or_client {
130 PY_SSL_CLIENT,
131 PY_SSL_SERVER
132};
133
134enum py_ssl_cert_requirements {
135 PY_SSL_CERT_NONE,
136 PY_SSL_CERT_OPTIONAL,
137 PY_SSL_CERT_REQUIRED
138};
139
140enum py_ssl_version {
141 PY_SSL_VERSION_SSL2,
142 PY_SSL_VERSION_SSL3=1,
143 PY_SSL_VERSION_SSL23,
144#if HAVE_TLSv1_2
145 PY_SSL_VERSION_TLS1,
146 PY_SSL_VERSION_TLS1_1,
147 PY_SSL_VERSION_TLS1_2
148#else
149 PY_SSL_VERSION_TLS1
150#endif
151};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000152
Bill Janssen98d19da2007-09-10 21:51:02 +0000153#ifdef WITH_THREAD
154
155/* serves as a flag to see whether we've initialized the SSL thread support. */
156/* 0 means no, greater than 0 means yes */
157
158static unsigned int _ssl_locks_count = 0;
159
160#endif /* def WITH_THREAD */
161
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000162/* SSL socket object */
163
164#define X509_NAME_MAXLEN 256
165
166/* RAND_* APIs got added to OpenSSL in 0.9.5 */
167#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
168# define HAVE_OPENSSL_RAND 1
169#else
170# undef HAVE_OPENSSL_RAND
171#endif
172
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500173/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
174 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
175 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
176#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
177# define HAVE_SSL_CTX_CLEAR_OPTIONS
178#else
179# undef HAVE_SSL_CTX_CLEAR_OPTIONS
180#endif
181
182/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
183 * older SSL, but let's be safe */
184#define PySSL_CB_MAXLEN 128
185
186/* SSL_get_finished got added to OpenSSL in 0.9.5 */
187#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
188# define HAVE_OPENSSL_FINISHED 1
189#else
190# define HAVE_OPENSSL_FINISHED 0
191#endif
192
193/* ECDH support got added to OpenSSL in 0.9.8 */
194#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
195# define OPENSSL_NO_ECDH
196#endif
197
198/* compression support got added to OpenSSL in 0.9.8 */
199#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
200# define OPENSSL_NO_COMP
201#endif
202
203/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
204#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
205# define HAVE_OPENSSL_VERIFY_PARAM
206#endif
207
208
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000209typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000210 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500211 SSL_CTX *ctx;
212#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500213 unsigned char *npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500214 int npn_protocols_len;
215#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500216#ifdef HAVE_ALPN
217 unsigned char *alpn_protocols;
218 int alpn_protocols_len;
219#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500220#ifndef OPENSSL_NO_TLSEXT
221 PyObject *set_hostname;
222#endif
223 int check_hostname;
224} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500226typedef struct {
227 PyObject_HEAD
228 PySocketSockObject *Socket;
229 PyObject *ssl_sock;
230 SSL *ssl;
231 PySSLContext *ctx; /* weakref to SSL context */
232 X509 *peer_cert;
233 char shutdown_seen_zero;
234 char handshake_done;
235 enum py_ssl_server_or_client socket_type;
236} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500238static PyTypeObject PySSLContext_Type;
239static PyTypeObject PySSLSocket_Type;
240
241static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
242static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000243static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000244 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500245static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
246static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000247
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500248#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
249#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000250
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000251typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000252 SOCKET_IS_NONBLOCKING,
253 SOCKET_IS_BLOCKING,
254 SOCKET_HAS_TIMED_OUT,
255 SOCKET_HAS_BEEN_CLOSED,
256 SOCKET_TOO_LARGE_FOR_SELECT,
257 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000258} timeout_state;
259
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000260/* Wrap error strings with filename and line # */
261#define STRINGIFY1(x) #x
262#define STRINGIFY2(x) STRINGIFY1(x)
263#define ERRSTR1(x,y,z) (x ":" y ": " z)
264#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
265
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500266
267/*
268 * SSL errors.
269 */
270
271PyDoc_STRVAR(SSLError_doc,
272"An error occurred in the SSL implementation.");
273
274PyDoc_STRVAR(SSLZeroReturnError_doc,
275"SSL/TLS session closed cleanly.");
276
277PyDoc_STRVAR(SSLWantReadError_doc,
278"Non-blocking SSL socket needs to read more data\n"
279"before the requested operation can be completed.");
280
281PyDoc_STRVAR(SSLWantWriteError_doc,
282"Non-blocking SSL socket needs to write more data\n"
283"before the requested operation can be completed.");
284
285PyDoc_STRVAR(SSLSyscallError_doc,
286"System error when attempting SSL operation.");
287
288PyDoc_STRVAR(SSLEOFError_doc,
289"SSL/TLS connection terminated abruptly.");
290
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000291
292static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500293SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000294{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500295 if (self->strerror != NULL) {
296 Py_INCREF(self->strerror);
297 return self->strerror;
298 }
299 else
300 return PyObject_Str(self->args);
301}
302
303static void
304fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
305 int lineno, unsigned long errcode)
306{
307 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
308 PyObject *init_value, *msg, *key;
309
310 if (errcode != 0) {
311 int lib, reason;
312
313 lib = ERR_GET_LIB(errcode);
314 reason = ERR_GET_REASON(errcode);
315 key = Py_BuildValue("ii", lib, reason);
316 if (key == NULL)
317 goto fail;
318 reason_obj = PyDict_GetItem(err_codes_to_names, key);
319 Py_DECREF(key);
320 if (reason_obj == NULL) {
321 /* XXX if reason < 100, it might reflect a library number (!!) */
322 PyErr_Clear();
323 }
324 key = PyLong_FromLong(lib);
325 if (key == NULL)
326 goto fail;
327 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
328 Py_DECREF(key);
329 if (lib_obj == NULL) {
330 PyErr_Clear();
331 }
332 if (errstr == NULL)
333 errstr = ERR_reason_error_string(errcode);
334 }
335 if (errstr == NULL)
336 errstr = "unknown error";
337
338 if (reason_obj && lib_obj)
339 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
340 lib_obj, reason_obj, errstr, lineno);
341 else if (lib_obj)
342 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
343 lib_obj, errstr, lineno);
344 else
345 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
346 if (msg == NULL)
347 goto fail;
348
349 init_value = Py_BuildValue("iN", ssl_errno, msg);
350 if (init_value == NULL)
351 goto fail;
352
353 err_value = PyObject_CallObject(type, init_value);
354 Py_DECREF(init_value);
355 if (err_value == NULL)
356 goto fail;
357
358 if (reason_obj == NULL)
359 reason_obj = Py_None;
360 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
361 goto fail;
362 if (lib_obj == NULL)
363 lib_obj = Py_None;
364 if (PyObject_SetAttrString(err_value, "library", lib_obj))
365 goto fail;
366 PyErr_SetObject(type, err_value);
367fail:
368 Py_XDECREF(err_value);
369}
370
371static PyObject *
372PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
373{
374 PyObject *type = PySSLErrorObject;
375 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000376 int err;
377 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500378 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000380 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500381 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000382
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000383 if (obj->ssl != NULL) {
384 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000385
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000386 switch (err) {
387 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500388 errstr = "TLS/SSL connection has been closed (EOF)";
389 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000390 p = PY_SSL_ERROR_ZERO_RETURN;
391 break;
392 case SSL_ERROR_WANT_READ:
393 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500394 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000395 p = PY_SSL_ERROR_WANT_READ;
396 break;
397 case SSL_ERROR_WANT_WRITE:
398 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500399 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000400 errstr = "The operation did not complete (write)";
401 break;
402 case SSL_ERROR_WANT_X509_LOOKUP:
403 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000404 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000405 break;
406 case SSL_ERROR_WANT_CONNECT:
407 p = PY_SSL_ERROR_WANT_CONNECT;
408 errstr = "The operation did not complete (connect)";
409 break;
410 case SSL_ERROR_SYSCALL:
411 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000412 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500413 PySocketSockObject *s = obj->Socket;
414 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000415 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500416 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000417 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000418 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000419 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500420 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000421 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500422 s->errorhandler();
423 Py_DECREF(s);
424 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000425 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000426 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500427 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000428 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000429 }
430 } else {
431 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000432 }
433 break;
434 }
435 case SSL_ERROR_SSL:
436 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000437 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500438 if (e == 0)
439 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000440 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000441 break;
442 }
443 default:
444 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
445 errstr = "Invalid error code";
446 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000447 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500448 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000449 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000450 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451}
452
Bill Janssen98d19da2007-09-10 21:51:02 +0000453static PyObject *
454_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
455
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500456 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000457 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500458 else
459 errcode = 0;
460 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000461 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000462 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000463}
464
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500465/*
466 * SSL objects
467 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000468
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500469static PySSLSocket *
470newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
471 enum py_ssl_server_or_client socket_type,
472 char *server_hostname, PyObject *ssl_sock)
473{
474 PySSLSocket *self;
475 SSL_CTX *ctx = sslctx->ctx;
476 long mode;
477
478 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000479 if (self == NULL)
480 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500481
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000482 self->peer_cert = NULL;
483 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000484 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500485 self->ssl_sock = NULL;
486 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200487 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500488 self->handshake_done = 0;
489 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000490
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000491 /* Make sure the SSL error state is initialized */
492 (void) ERR_get_state();
493 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000494
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000495 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500496 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000497 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500498 SSL_set_app_data(self->ssl,self);
499 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
500 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000501#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500502 mode |= SSL_MODE_AUTO_RETRY;
503#endif
504 SSL_set_mode(self->ssl, mode);
505
506#if HAVE_SNI
507 if (server_hostname != NULL)
508 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000509#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000510
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000511 /* If the socket is in non-blocking mode or timeout mode, set the BIO
512 * to non-blocking mode (blocking is the default)
513 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500514 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000515 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
516 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
517 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000518
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000519 PySSL_BEGIN_ALLOW_THREADS
520 if (socket_type == PY_SSL_CLIENT)
521 SSL_set_connect_state(self->ssl);
522 else
523 SSL_set_accept_state(self->ssl);
524 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000525
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500526 self->socket_type = socket_type;
527 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000528 Py_INCREF(self->Socket);
Benjamin Peterson2f334562014-10-01 23:53:01 -0400529 if (ssl_sock != Py_None) {
530 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
531 if (self->ssl_sock == NULL) {
532 Py_DECREF(self);
533 return NULL;
534 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500535 }
536 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000537}
538
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000539
540/* SSL object methods */
541
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500542static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000543{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000544 int ret;
545 int err;
546 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500547 PySocketSockObject *sock = self->Socket;
548
549 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000550
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000551 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000553 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
554 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000555
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000556 /* Actually negotiate SSL connection */
557 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
558 do {
559 PySSL_BEGIN_ALLOW_THREADS
560 ret = SSL_do_handshake(self->ssl);
561 err = SSL_get_error(self->ssl, ret);
562 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500563 if (PyErr_CheckSignals())
564 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000565 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500566 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000567 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500568 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000569 } else {
570 sockstate = SOCKET_OPERATION_OK;
571 }
572 if (sockstate == SOCKET_HAS_TIMED_OUT) {
573 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000574 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500575 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000576 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
577 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000578 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500579 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000580 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
581 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000582 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500583 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000584 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
585 break;
586 }
587 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500588 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000589 if (ret < 1)
590 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000591
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000592 if (self->peer_cert)
593 X509_free (self->peer_cert);
594 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500595 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000596 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500597 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 Py_INCREF(Py_None);
600 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000601
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500602error:
603 Py_DECREF(sock);
604 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000605}
606
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000607static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000608_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000609
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000610 char namebuf[X509_NAME_MAXLEN];
611 int buflen;
612 PyObject *name_obj;
613 PyObject *value_obj;
614 PyObject *attr;
615 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000616
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000617 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
618 if (buflen < 0) {
619 _setSSLError(NULL, 0, __FILE__, __LINE__);
620 goto fail;
621 }
622 name_obj = PyString_FromStringAndSize(namebuf, buflen);
623 if (name_obj == NULL)
624 goto fail;
625
626 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
627 if (buflen < 0) {
628 _setSSLError(NULL, 0, __FILE__, __LINE__);
629 Py_DECREF(name_obj);
630 goto fail;
631 }
632 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000633 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000634 OPENSSL_free(valuebuf);
635 if (value_obj == NULL) {
636 Py_DECREF(name_obj);
637 goto fail;
638 }
639 attr = PyTuple_New(2);
640 if (attr == NULL) {
641 Py_DECREF(name_obj);
642 Py_DECREF(value_obj);
643 goto fail;
644 }
645 PyTuple_SET_ITEM(attr, 0, name_obj);
646 PyTuple_SET_ITEM(attr, 1, value_obj);
647 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000648
Bill Janssen98d19da2007-09-10 21:51:02 +0000649 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000650 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000651}
652
653static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000654_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000655{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000656 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
657 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
658 PyObject *rdnt;
659 PyObject *attr = NULL; /* tuple to hold an attribute */
660 int entry_count = X509_NAME_entry_count(xname);
661 X509_NAME_ENTRY *entry;
662 ASN1_OBJECT *name;
663 ASN1_STRING *value;
664 int index_counter;
665 int rdn_level = -1;
666 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000667
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000668 dn = PyList_New(0);
669 if (dn == NULL)
670 return NULL;
671 /* now create another tuple to hold the top-level RDN */
672 rdn = PyList_New(0);
673 if (rdn == NULL)
674 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000675
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000676 for (index_counter = 0;
677 index_counter < entry_count;
678 index_counter++)
679 {
680 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000681
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000682 /* check to see if we've gotten to a new RDN */
683 if (rdn_level >= 0) {
684 if (rdn_level != entry->set) {
685 /* yes, new RDN */
686 /* add old RDN to DN */
687 rdnt = PyList_AsTuple(rdn);
688 Py_DECREF(rdn);
689 if (rdnt == NULL)
690 goto fail0;
691 retcode = PyList_Append(dn, rdnt);
692 Py_DECREF(rdnt);
693 if (retcode < 0)
694 goto fail0;
695 /* create new RDN */
696 rdn = PyList_New(0);
697 if (rdn == NULL)
698 goto fail0;
699 }
700 }
701 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000702
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000703 /* now add this attribute to the current RDN */
704 name = X509_NAME_ENTRY_get_object(entry);
705 value = X509_NAME_ENTRY_get_data(entry);
706 attr = _create_tuple_for_attribute(name, value);
707 /*
708 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
709 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500710 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
711 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000712 */
713 if (attr == NULL)
714 goto fail1;
715 retcode = PyList_Append(rdn, attr);
716 Py_DECREF(attr);
717 if (retcode < 0)
718 goto fail1;
719 }
720 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100721 if (rdn != NULL) {
722 if (PyList_GET_SIZE(rdn) > 0) {
723 rdnt = PyList_AsTuple(rdn);
724 Py_DECREF(rdn);
725 if (rdnt == NULL)
726 goto fail0;
727 retcode = PyList_Append(dn, rdnt);
728 Py_DECREF(rdnt);
729 if (retcode < 0)
730 goto fail0;
731 }
732 else {
733 Py_DECREF(rdn);
734 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000735 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000736
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000737 /* convert list to tuple */
738 rdnt = PyList_AsTuple(dn);
739 Py_DECREF(dn);
740 if (rdnt == NULL)
741 return NULL;
742 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
744 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000745 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000746
747 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000748 Py_XDECREF(dn);
749 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000750}
751
752static PyObject *
753_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000754
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000755 /* this code follows the procedure outlined in
756 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
757 function to extract the STACK_OF(GENERAL_NAME),
758 then iterates through the stack to add the
759 names. */
760
761 int i, j;
762 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200763 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000764 X509_EXTENSION *ext = NULL;
765 GENERAL_NAMES *names = NULL;
766 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000767 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000768 BIO *biobuf = NULL;
769 char buf[2048];
770 char *vptr;
771 int len;
772 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000773#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000774 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000775#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000776 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000777#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000778
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000779 if (certificate == NULL)
780 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000781
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000782 /* get a memory buffer */
783 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000784
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200785 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000786 while ((i = X509_get_ext_by_NID(
787 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000788
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000789 if (peer_alt_names == Py_None) {
790 peer_alt_names = PyList_New(0);
791 if (peer_alt_names == NULL)
792 goto fail;
793 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000794
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000795 /* now decode the altName */
796 ext = X509_get_ext(certificate, i);
797 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500798 PyErr_SetString
799 (PySSLErrorObject,
800 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000801 goto fail;
802 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000803
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000804 p = ext->value->data;
805 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500806 names = (GENERAL_NAMES*)
807 (ASN1_item_d2i(NULL,
808 &p,
809 ext->value->length,
810 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000811 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500812 names = (GENERAL_NAMES*)
813 (method->d2i(NULL,
814 &p,
815 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000816
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000817 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000818 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200819 int gntype;
820 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000821
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000822 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200823 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200824 switch (gntype) {
825 case GEN_DIRNAME:
826 /* we special-case DirName as a tuple of
827 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000828
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000829 t = PyTuple_New(2);
830 if (t == NULL) {
831 goto fail;
832 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000833
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000834 v = PyString_FromString("DirName");
835 if (v == NULL) {
836 Py_DECREF(t);
837 goto fail;
838 }
839 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000840
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000841 v = _create_tuple_for_X509_NAME (name->d.dirn);
842 if (v == NULL) {
843 Py_DECREF(t);
844 goto fail;
845 }
846 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200847 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000848
Christian Heimes88b174c2013-08-17 00:54:47 +0200849 case GEN_EMAIL:
850 case GEN_DNS:
851 case GEN_URI:
852 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
853 correctly, CVE-2013-4238 */
854 t = PyTuple_New(2);
855 if (t == NULL)
856 goto fail;
857 switch (gntype) {
858 case GEN_EMAIL:
859 v = PyString_FromString("email");
860 as = name->d.rfc822Name;
861 break;
862 case GEN_DNS:
863 v = PyString_FromString("DNS");
864 as = name->d.dNSName;
865 break;
866 case GEN_URI:
867 v = PyString_FromString("URI");
868 as = name->d.uniformResourceIdentifier;
869 break;
870 }
871 if (v == NULL) {
872 Py_DECREF(t);
873 goto fail;
874 }
875 PyTuple_SET_ITEM(t, 0, v);
876 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
877 ASN1_STRING_length(as));
878 if (v == NULL) {
879 Py_DECREF(t);
880 goto fail;
881 }
882 PyTuple_SET_ITEM(t, 1, v);
883 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000884
Christian Heimes88b174c2013-08-17 00:54:47 +0200885 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000886 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200887 switch (gntype) {
888 /* check for new general name type */
889 case GEN_OTHERNAME:
890 case GEN_X400:
891 case GEN_EDIPARTY:
892 case GEN_IPADD:
893 case GEN_RID:
894 break;
895 default:
896 if (PyErr_Warn(PyExc_RuntimeWarning,
897 "Unknown general name type") == -1) {
898 goto fail;
899 }
900 break;
901 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000902 (void) BIO_reset(biobuf);
903 GENERAL_NAME_print(biobuf, name);
904 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
905 if (len < 0) {
906 _setSSLError(NULL, 0, __FILE__, __LINE__);
907 goto fail;
908 }
909 vptr = strchr(buf, ':');
910 if (vptr == NULL)
911 goto fail;
912 t = PyTuple_New(2);
913 if (t == NULL)
914 goto fail;
915 v = PyString_FromStringAndSize(buf, (vptr - buf));
916 if (v == NULL) {
917 Py_DECREF(t);
918 goto fail;
919 }
920 PyTuple_SET_ITEM(t, 0, v);
921 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
922 if (v == NULL) {
923 Py_DECREF(t);
924 goto fail;
925 }
926 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200927 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 }
929
930 /* and add that rendering to the list */
931
932 if (PyList_Append(peer_alt_names, t) < 0) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 Py_DECREF(t);
937 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +0100938 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000939 }
940 BIO_free(biobuf);
941 if (peer_alt_names != Py_None) {
942 v = PyList_AsTuple(peer_alt_names);
943 Py_DECREF(peer_alt_names);
944 return v;
945 } else {
946 return peer_alt_names;
947 }
948
Bill Janssen98d19da2007-09-10 21:51:02 +0000949
950 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000951 if (biobuf != NULL)
952 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000953
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000954 if (peer_alt_names != Py_None) {
955 Py_XDECREF(peer_alt_names);
956 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000957
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000958 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000959}
960
961static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500962_get_aia_uri(X509 *certificate, int nid) {
963 PyObject *lst = NULL, *ostr = NULL;
964 int i, result;
965 AUTHORITY_INFO_ACCESS *info;
966
967 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
968 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
969 return Py_None;
970 }
971
972 if ((lst = PyList_New(0)) == NULL) {
973 goto fail;
974 }
975
976 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
977 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
978 ASN1_IA5STRING *uri;
979
980 if ((OBJ_obj2nid(ad->method) != nid) ||
981 (ad->location->type != GEN_URI)) {
982 continue;
983 }
984 uri = ad->location->d.uniformResourceIdentifier;
985 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
986 uri->length);
987 if (ostr == NULL) {
988 goto fail;
989 }
990 result = PyList_Append(lst, ostr);
991 Py_DECREF(ostr);
992 if (result < 0) {
993 goto fail;
994 }
995 }
996 AUTHORITY_INFO_ACCESS_free(info);
997
998 /* convert to tuple or None */
999 if (PyList_Size(lst) == 0) {
1000 Py_DECREF(lst);
1001 return Py_None;
1002 } else {
1003 PyObject *tup;
1004 tup = PyList_AsTuple(lst);
1005 Py_DECREF(lst);
1006 return tup;
1007 }
1008
1009 fail:
1010 AUTHORITY_INFO_ACCESS_free(info);
1011 Py_XDECREF(lst);
1012 return NULL;
1013}
1014
1015static PyObject *
1016_get_crl_dp(X509 *certificate) {
1017 STACK_OF(DIST_POINT) *dps;
1018 int i, j, result;
1019 PyObject *lst;
1020
1021#if OPENSSL_VERSION_NUMBER < 0x10001000L
1022 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1023 NULL, NULL);
1024#else
1025 /* Calls x509v3_cache_extensions and sets up crldp */
1026 X509_check_ca(certificate);
1027 dps = certificate->crldp;
1028#endif
1029
1030 if (dps == NULL) {
1031 return Py_None;
1032 }
1033
1034 if ((lst = PyList_New(0)) == NULL) {
1035 return NULL;
1036 }
1037
1038 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1039 DIST_POINT *dp;
1040 STACK_OF(GENERAL_NAME) *gns;
1041
1042 dp = sk_DIST_POINT_value(dps, i);
1043 gns = dp->distpoint->name.fullname;
1044
1045 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1046 GENERAL_NAME *gn;
1047 ASN1_IA5STRING *uri;
1048 PyObject *ouri;
1049
1050 gn = sk_GENERAL_NAME_value(gns, j);
1051 if (gn->type != GEN_URI) {
1052 continue;
1053 }
1054 uri = gn->d.uniformResourceIdentifier;
1055 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1056 uri->length);
1057 if (ouri == NULL) {
1058 Py_DECREF(lst);
1059 return NULL;
1060 }
1061 result = PyList_Append(lst, ouri);
1062 Py_DECREF(ouri);
1063 if (result < 0) {
1064 Py_DECREF(lst);
1065 return NULL;
1066 }
1067 }
1068 }
1069 /* convert to tuple or None */
1070 if (PyList_Size(lst) == 0) {
1071 Py_DECREF(lst);
1072 return Py_None;
1073 } else {
1074 PyObject *tup;
1075 tup = PyList_AsTuple(lst);
1076 Py_DECREF(lst);
1077 return tup;
1078 }
1079}
1080
1081static PyObject *
1082_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001083
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001084 PyObject *retval = NULL;
1085 BIO *biobuf = NULL;
1086 PyObject *peer;
1087 PyObject *peer_alt_names = NULL;
1088 PyObject *issuer;
1089 PyObject *version;
1090 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001091 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001092 ASN1_INTEGER *serialNumber;
1093 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001094 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001095 ASN1_TIME *notBefore, *notAfter;
1096 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001097
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001098 retval = PyDict_New();
1099 if (retval == NULL)
1100 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001101
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001102 peer = _create_tuple_for_X509_NAME(
1103 X509_get_subject_name(certificate));
1104 if (peer == NULL)
1105 goto fail0;
1106 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1107 Py_DECREF(peer);
1108 goto fail0;
1109 }
1110 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001111
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001112 issuer = _create_tuple_for_X509_NAME(
1113 X509_get_issuer_name(certificate));
1114 if (issuer == NULL)
1115 goto fail0;
1116 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001117 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001118 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001119 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001120 Py_DECREF(issuer);
1121
1122 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1123 if (version == NULL)
1124 goto fail0;
1125 if (PyDict_SetItemString(retval, "version", version) < 0) {
1126 Py_DECREF(version);
1127 goto fail0;
1128 }
1129 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001130
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001131 /* get a memory buffer */
1132 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001133
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001134 (void) BIO_reset(biobuf);
1135 serialNumber = X509_get_serialNumber(certificate);
1136 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1137 i2a_ASN1_INTEGER(biobuf, serialNumber);
1138 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1139 if (len < 0) {
1140 _setSSLError(NULL, 0, __FILE__, __LINE__);
1141 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001142 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001143 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1144 if (sn_obj == NULL)
1145 goto fail1;
1146 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1147 Py_DECREF(sn_obj);
1148 goto fail1;
1149 }
1150 Py_DECREF(sn_obj);
1151
1152 (void) BIO_reset(biobuf);
1153 notBefore = X509_get_notBefore(certificate);
1154 ASN1_TIME_print(biobuf, notBefore);
1155 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1156 if (len < 0) {
1157 _setSSLError(NULL, 0, __FILE__, __LINE__);
1158 goto fail1;
1159 }
1160 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1161 if (pnotBefore == NULL)
1162 goto fail1;
1163 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1164 Py_DECREF(pnotBefore);
1165 goto fail1;
1166 }
1167 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001168
1169 (void) BIO_reset(biobuf);
1170 notAfter = X509_get_notAfter(certificate);
1171 ASN1_TIME_print(biobuf, notAfter);
1172 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1173 if (len < 0) {
1174 _setSSLError(NULL, 0, __FILE__, __LINE__);
1175 goto fail1;
1176 }
1177 pnotAfter = PyString_FromStringAndSize(buf, len);
1178 if (pnotAfter == NULL)
1179 goto fail1;
1180 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1181 Py_DECREF(pnotAfter);
1182 goto fail1;
1183 }
1184 Py_DECREF(pnotAfter);
1185
1186 /* Now look for subjectAltName */
1187
1188 peer_alt_names = _get_peer_alt_names(certificate);
1189 if (peer_alt_names == NULL)
1190 goto fail1;
1191 else if (peer_alt_names != Py_None) {
1192 if (PyDict_SetItemString(retval, "subjectAltName",
1193 peer_alt_names) < 0) {
1194 Py_DECREF(peer_alt_names);
1195 goto fail1;
1196 }
1197 Py_DECREF(peer_alt_names);
1198 }
1199
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001200 /* Authority Information Access: OCSP URIs */
1201 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1202 if (obj == NULL) {
1203 goto fail1;
1204 } else if (obj != Py_None) {
1205 result = PyDict_SetItemString(retval, "OCSP", obj);
1206 Py_DECREF(obj);
1207 if (result < 0) {
1208 goto fail1;
1209 }
1210 }
1211
1212 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1213 if (obj == NULL) {
1214 goto fail1;
1215 } else if (obj != Py_None) {
1216 result = PyDict_SetItemString(retval, "caIssuers", obj);
1217 Py_DECREF(obj);
1218 if (result < 0) {
1219 goto fail1;
1220 }
1221 }
1222
1223 /* CDP (CRL distribution points) */
1224 obj = _get_crl_dp(certificate);
1225 if (obj == NULL) {
1226 goto fail1;
1227 } else if (obj != Py_None) {
1228 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1229 Py_DECREF(obj);
1230 if (result < 0) {
1231 goto fail1;
1232 }
1233 }
1234
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001235 BIO_free(biobuf);
1236 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001237
1238 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001239 if (biobuf != NULL)
1240 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001241 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001242 Py_XDECREF(retval);
1243 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001244}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001245
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001246static PyObject *
1247_certificate_to_der(X509 *certificate)
1248{
1249 unsigned char *bytes_buf = NULL;
1250 int len;
1251 PyObject *retval;
1252
1253 bytes_buf = NULL;
1254 len = i2d_X509(certificate, &bytes_buf);
1255 if (len < 0) {
1256 _setSSLError(NULL, 0, __FILE__, __LINE__);
1257 return NULL;
1258 }
1259 /* this is actually an immutable bytes sequence */
1260 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1261 OPENSSL_free(bytes_buf);
1262 return retval;
1263}
Bill Janssen98d19da2007-09-10 21:51:02 +00001264
1265static PyObject *
1266PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1267
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001268 PyObject *retval = NULL;
1269 char *filename = NULL;
1270 X509 *x=NULL;
1271 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001272
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001273 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001274 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001275
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001276 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001277 PyErr_SetString(PySSLErrorObject,
1278 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001279 goto fail0;
1280 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001281
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001282 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001283 PyErr_SetString(PySSLErrorObject,
1284 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001285 goto fail0;
1286 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001287
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001288 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1289 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001290 PyErr_SetString(PySSLErrorObject,
1291 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001292 goto fail0;
1293 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001294
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001295 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001296 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001297
1298 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001299
1300 if (cert != NULL) BIO_free(cert);
1301 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001302}
1303
1304
1305static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001306PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001307{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001308 int verification;
1309 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001310 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001311
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001312 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1313 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001314
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001315 if (!self->handshake_done) {
1316 PyErr_SetString(PyExc_ValueError,
1317 "handshake not done yet");
1318 return NULL;
1319 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001320 if (!self->peer_cert)
1321 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001322
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001323 b = PyObject_IsTrue(binary_mode);
1324 if (b < 0)
1325 return NULL;
1326 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001327 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001328 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001329 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001330 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001331 if ((verification & SSL_VERIFY_PEER) == 0)
1332 return PyDict_New();
1333 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001334 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001335 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001336}
1337
1338PyDoc_STRVAR(PySSL_peercert_doc,
1339"peer_certificate([der=False]) -> certificate\n\
1340\n\
1341Returns the certificate for the peer. If no certificate was provided,\n\
1342returns None. If a certificate was provided, but not validated, returns\n\
1343an empty dictionary. Otherwise returns a dict containing information\n\
1344about the peer certificate.\n\
1345\n\
1346If the optional argument is True, returns a DER-encoded copy of the\n\
1347peer certificate, or None if no certificate was provided. This will\n\
1348return the certificate even if it wasn't validated.");
1349
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001350static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001351
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001352 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001353 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001354 char *cipher_name;
1355 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001356
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001357 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001358 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001359 current = SSL_get_current_cipher(self->ssl);
1360 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001361 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001362
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001363 retval = PyTuple_New(3);
1364 if (retval == NULL)
1365 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001366
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001367 cipher_name = (char *) SSL_CIPHER_get_name(current);
1368 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001369 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001370 PyTuple_SET_ITEM(retval, 0, Py_None);
1371 } else {
1372 v = PyString_FromString(cipher_name);
1373 if (v == NULL)
1374 goto fail0;
1375 PyTuple_SET_ITEM(retval, 0, v);
1376 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001377 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001378 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001379 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001380 PyTuple_SET_ITEM(retval, 1, Py_None);
1381 } else {
1382 v = PyString_FromString(cipher_protocol);
1383 if (v == NULL)
1384 goto fail0;
1385 PyTuple_SET_ITEM(retval, 1, v);
1386 }
1387 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1388 if (v == NULL)
1389 goto fail0;
1390 PyTuple_SET_ITEM(retval, 2, v);
1391 return retval;
1392
Bill Janssen98d19da2007-09-10 21:51:02 +00001393 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001394 Py_DECREF(retval);
1395 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001396}
1397
Alex Gaynore98205d2014-09-04 13:33:22 -07001398static PyObject *PySSL_version(PySSLSocket *self)
1399{
1400 const char *version;
1401
1402 if (self->ssl == NULL)
1403 Py_RETURN_NONE;
1404 version = SSL_get_version(self->ssl);
1405 if (!strcmp(version, "unknown"))
1406 Py_RETURN_NONE;
1407 return PyUnicode_FromString(version);
1408}
1409
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001410#ifdef OPENSSL_NPN_NEGOTIATED
1411static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1412 const unsigned char *out;
1413 unsigned int outlen;
1414
1415 SSL_get0_next_proto_negotiated(self->ssl,
1416 &out, &outlen);
1417
1418 if (out == NULL)
1419 Py_RETURN_NONE;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001420 return PyString_FromStringAndSize((char *)out, outlen);
1421}
1422#endif
1423
1424#ifdef HAVE_ALPN
1425static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1426 const unsigned char *out;
1427 unsigned int outlen;
1428
1429 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1430
1431 if (out == NULL)
1432 Py_RETURN_NONE;
1433 return PyString_FromStringAndSize((char *)out, outlen);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001434}
1435#endif
1436
1437static PyObject *PySSL_compression(PySSLSocket *self) {
1438#ifdef OPENSSL_NO_COMP
1439 Py_RETURN_NONE;
1440#else
1441 const COMP_METHOD *comp_method;
1442 const char *short_name;
1443
1444 if (self->ssl == NULL)
1445 Py_RETURN_NONE;
1446 comp_method = SSL_get_current_compression(self->ssl);
1447 if (comp_method == NULL || comp_method->type == NID_undef)
1448 Py_RETURN_NONE;
1449 short_name = OBJ_nid2sn(comp_method->type);
1450 if (short_name == NULL)
1451 Py_RETURN_NONE;
1452 return PyBytes_FromString(short_name);
1453#endif
1454}
1455
1456static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1457 Py_INCREF(self->ctx);
1458 return self->ctx;
1459}
1460
1461static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1462 void *closure) {
1463
1464 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1465#if !HAVE_SNI
1466 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1467 "context is not supported by your OpenSSL library");
1468 return -1;
1469#else
1470 Py_INCREF(value);
1471 Py_DECREF(self->ctx);
1472 self->ctx = (PySSLContext *) value;
1473 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1474#endif
1475 } else {
1476 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1477 return -1;
1478 }
1479
1480 return 0;
1481}
1482
1483PyDoc_STRVAR(PySSL_set_context_doc,
1484"_setter_context(ctx)\n\
1485\
1486This changes the context associated with the SSLSocket. This is typically\n\
1487used from within a callback function set by the set_servername_callback\n\
1488on the SSLContext to change the certificate information associated with the\n\
1489SSLSocket before the cryptographic exchange handshake messages\n");
1490
1491
1492
1493static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001494{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001495 if (self->peer_cert) /* Possible not to have one? */
1496 X509_free (self->peer_cert);
1497 if (self->ssl)
1498 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001499 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001500 Py_XDECREF(self->ssl_sock);
1501 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001502 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001503}
1504
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001505/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001506 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001507 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001508 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001509
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001510static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001511check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001512{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001513 fd_set fds;
1514 struct timeval tv;
1515 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001516
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001517 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1518 if (s->sock_timeout < 0.0)
1519 return SOCKET_IS_BLOCKING;
1520 else if (s->sock_timeout == 0.0)
1521 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001522
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001523 /* Guard against closed socket */
1524 if (s->sock_fd < 0)
1525 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001526
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001527 /* Prefer poll, if available, since you can poll() any fd
1528 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001529#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001530 {
1531 struct pollfd pollfd;
1532 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001533
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001534 pollfd.fd = s->sock_fd;
1535 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001536
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001537 /* s->sock_timeout is in seconds, timeout in ms */
1538 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1539 PySSL_BEGIN_ALLOW_THREADS
1540 rc = poll(&pollfd, 1, timeout);
1541 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001542
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001543 goto normal_return;
1544 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001545#endif
1546
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001547 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001548 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001549 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001550
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001551 /* Construct the arguments to select */
1552 tv.tv_sec = (int)s->sock_timeout;
1553 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1554 FD_ZERO(&fds);
1555 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001556
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001557 /* See if the socket is ready */
1558 PySSL_BEGIN_ALLOW_THREADS
1559 if (writing)
1560 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1561 else
1562 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1563 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001564
Bill Janssen934b16d2008-06-28 22:19:33 +00001565#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001566normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001567#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001568 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1569 (when we are able to write or when there's something to read) */
1570 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001571}
1572
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001573static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001574{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001575 Py_buffer buf;
1576 int len;
1577 int sockstate;
1578 int err;
1579 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001580 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001581
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001582 Py_INCREF(sock);
1583
1584 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1585 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001586 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001587 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588
Victor Stinnerc1a44262013-06-25 00:48:02 +02001589 if (buf.len > INT_MAX) {
1590 PyErr_Format(PyExc_OverflowError,
1591 "string longer than %d bytes", INT_MAX);
1592 goto error;
1593 }
1594
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001595 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001596 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001597 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1598 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001599
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001600 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001601 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1602 PyErr_SetString(PySSLErrorObject,
1603 "The write operation timed out");
1604 goto error;
1605 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1606 PyErr_SetString(PySSLErrorObject,
1607 "Underlying socket has been closed.");
1608 goto error;
1609 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1610 PyErr_SetString(PySSLErrorObject,
1611 "Underlying socket too large for select().");
1612 goto error;
1613 }
1614 do {
1615 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001616 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001617 err = SSL_get_error(self->ssl, len);
1618 PySSL_END_ALLOW_THREADS
1619 if (PyErr_CheckSignals()) {
1620 goto error;
1621 }
1622 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001623 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001624 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001625 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001626 } else {
1627 sockstate = SOCKET_OPERATION_OK;
1628 }
1629 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1630 PyErr_SetString(PySSLErrorObject,
1631 "The write operation timed out");
1632 goto error;
1633 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1634 PyErr_SetString(PySSLErrorObject,
1635 "Underlying socket has been closed.");
1636 goto error;
1637 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1638 break;
1639 }
1640 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001641
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001642 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001643 PyBuffer_Release(&buf);
1644 if (len > 0)
1645 return PyInt_FromLong(len);
1646 else
1647 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001648
1649error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001650 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001651 PyBuffer_Release(&buf);
1652 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001653}
1654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001655PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001656"write(s) -> len\n\
1657\n\
1658Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001659of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001660
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001661static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001662{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001663 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001664
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001665 PySSL_BEGIN_ALLOW_THREADS
1666 count = SSL_pending(self->ssl);
1667 PySSL_END_ALLOW_THREADS
1668 if (count < 0)
1669 return PySSL_SetError(self, count, __FILE__, __LINE__);
1670 else
1671 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001672}
1673
1674PyDoc_STRVAR(PySSL_SSLpending_doc,
1675"pending() -> count\n\
1676\n\
1677Returns the number of already decrypted bytes available for read,\n\
1678pending on the connection.\n");
1679
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001680static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001681{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001682 PyObject *dest = NULL;
1683 Py_buffer buf;
1684 char *mem;
1685 int len, count;
1686 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001687 int sockstate;
1688 int err;
1689 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001690 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001691
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001692 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001693
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001694 buf.obj = NULL;
1695 buf.buf = NULL;
1696 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1697 goto error;
1698
1699 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1700 dest = PyBytes_FromStringAndSize(NULL, len);
1701 if (dest == NULL)
1702 goto error;
1703 mem = PyBytes_AS_STRING(dest);
1704 }
1705 else {
1706 buf_passed = 1;
1707 mem = buf.buf;
1708 if (len <= 0 || len > buf.len) {
1709 len = (int) buf.len;
1710 if (buf.len != len) {
1711 PyErr_SetString(PyExc_OverflowError,
1712 "maximum length can't fit in a C 'int'");
1713 goto error;
1714 }
1715 }
1716 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001717
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001719 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001720 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1721 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001722
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001723 /* first check if there are bytes ready to be read */
1724 PySSL_BEGIN_ALLOW_THREADS
1725 count = SSL_pending(self->ssl);
1726 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001727
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 if (!count) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001729 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001730 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1731 PyErr_SetString(PySSLErrorObject,
1732 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001733 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001734 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1735 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001736 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001737 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001738 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001739 count = 0;
1740 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001741 }
1742 }
1743 do {
1744 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001745 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001746 err = SSL_get_error(self->ssl, count);
1747 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001748 if (PyErr_CheckSignals())
1749 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001750 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001751 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001752 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001753 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001754 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1755 (SSL_get_shutdown(self->ssl) ==
1756 SSL_RECEIVED_SHUTDOWN))
1757 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001758 count = 0;
1759 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001760 } else {
1761 sockstate = SOCKET_OPERATION_OK;
1762 }
1763 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1764 PyErr_SetString(PySSLErrorObject,
1765 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001766 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001767 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1768 break;
1769 }
1770 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1771 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001772 PySSL_SetError(self, count, __FILE__, __LINE__);
1773 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001774 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001775
1776done:
1777 Py_DECREF(sock);
1778 if (!buf_passed) {
1779 _PyBytes_Resize(&dest, count);
1780 return dest;
1781 }
1782 else {
1783 PyBuffer_Release(&buf);
1784 return PyLong_FromLong(count);
1785 }
1786
1787error:
1788 Py_DECREF(sock);
1789 if (!buf_passed)
1790 Py_XDECREF(dest);
1791 else
1792 PyBuffer_Release(&buf);
1793 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794}
1795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001797"read([len]) -> string\n\
1798\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001799Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001800
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001801static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001802{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001803 int err, ssl_err, sockstate, nonblocking;
1804 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001805 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001806
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001807 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001808 if (sock->sock_fd < 0) {
1809 _setSSLError("Underlying socket connection gone",
1810 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001811 return NULL;
1812 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001813 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001814
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001815 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001816 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001817 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1818 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001819
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001820 while (1) {
1821 PySSL_BEGIN_ALLOW_THREADS
1822 /* Disable read-ahead so that unwrap can work correctly.
1823 * Otherwise OpenSSL might read in too much data,
1824 * eating clear text data that happens to be
1825 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001826 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001827 * function is used and the shutdown_seen_zero != 0
1828 * condition is met.
1829 */
1830 if (self->shutdown_seen_zero)
1831 SSL_set_read_ahead(self->ssl, 0);
1832 err = SSL_shutdown(self->ssl);
1833 PySSL_END_ALLOW_THREADS
1834 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1835 if (err > 0)
1836 break;
1837 if (err == 0) {
1838 /* Don't loop endlessly; instead preserve legacy
1839 behaviour of trying SSL_shutdown() only twice.
1840 This looks necessary for OpenSSL < 0.9.8m */
1841 if (++zeros > 1)
1842 break;
1843 /* Shutdown was sent, now try receiving */
1844 self->shutdown_seen_zero = 1;
1845 continue;
1846 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001847
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001848 /* Possibly retry shutdown until timeout or failure */
1849 ssl_err = SSL_get_error(self->ssl, err);
1850 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001851 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001852 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001853 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001854 else
1855 break;
1856 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1857 if (ssl_err == SSL_ERROR_WANT_READ)
1858 PyErr_SetString(PySSLErrorObject,
1859 "The read operation timed out");
1860 else
1861 PyErr_SetString(PySSLErrorObject,
1862 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001863 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001864 }
1865 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1866 PyErr_SetString(PySSLErrorObject,
1867 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001868 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001869 }
1870 else if (sockstate != SOCKET_OPERATION_OK)
1871 /* Retain the SSL error code */
1872 break;
1873 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001874
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001875 if (err < 0) {
1876 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001877 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001878 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001879 else
1880 /* It's already INCREF'ed */
1881 return (PyObject *) sock;
1882
1883error:
1884 Py_DECREF(sock);
1885 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001886}
1887
1888PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1889"shutdown(s) -> socket\n\
1890\n\
1891Does the SSL shutdown handshake with the remote end, and returns\n\
1892the underlying socket object.");
1893
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001894#if HAVE_OPENSSL_FINISHED
1895static PyObject *
1896PySSL_tls_unique_cb(PySSLSocket *self)
1897{
1898 PyObject *retval = NULL;
1899 char buf[PySSL_CB_MAXLEN];
1900 size_t len;
1901
1902 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1903 /* if session is resumed XOR we are the client */
1904 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1905 }
1906 else {
1907 /* if a new session XOR we are the server */
1908 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1909 }
1910
1911 /* It cannot be negative in current OpenSSL version as of July 2011 */
1912 if (len == 0)
1913 Py_RETURN_NONE;
1914
1915 retval = PyBytes_FromStringAndSize(buf, len);
1916
1917 return retval;
1918}
1919
1920PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1921"tls_unique_cb() -> bytes\n\
1922\n\
1923Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1924\n\
1925If the TLS handshake is not yet complete, None is returned");
1926
1927#endif /* HAVE_OPENSSL_FINISHED */
1928
1929static PyGetSetDef ssl_getsetlist[] = {
1930 {"context", (getter) PySSL_get_context,
1931 (setter) PySSL_set_context, PySSL_set_context_doc},
1932 {NULL}, /* sentinel */
1933};
1934
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001935static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001936 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1937 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1938 PySSL_SSLwrite_doc},
1939 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1940 PySSL_SSLread_doc},
1941 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1942 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001943 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1944 PySSL_peercert_doc},
1945 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Alex Gaynore98205d2014-09-04 13:33:22 -07001946 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001947#ifdef OPENSSL_NPN_NEGOTIATED
1948 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1949#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001950#ifdef HAVE_ALPN
1951 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
1952#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001953 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001954 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1955 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001956#if HAVE_OPENSSL_FINISHED
1957 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1958 PySSL_tls_unique_cb_doc},
1959#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001960 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001961};
1962
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001963static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001964 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001965 "_ssl._SSLSocket", /*tp_name*/
1966 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001967 0, /*tp_itemsize*/
1968 /* methods */
1969 (destructor)PySSL_dealloc, /*tp_dealloc*/
1970 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001971 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001972 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001973 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001974 0, /*tp_repr*/
1975 0, /*tp_as_number*/
1976 0, /*tp_as_sequence*/
1977 0, /*tp_as_mapping*/
1978 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001979 0, /*tp_call*/
1980 0, /*tp_str*/
1981 0, /*tp_getattro*/
1982 0, /*tp_setattro*/
1983 0, /*tp_as_buffer*/
1984 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1985 0, /*tp_doc*/
1986 0, /*tp_traverse*/
1987 0, /*tp_clear*/
1988 0, /*tp_richcompare*/
1989 0, /*tp_weaklistoffset*/
1990 0, /*tp_iter*/
1991 0, /*tp_iternext*/
1992 PySSLMethods, /*tp_methods*/
1993 0, /*tp_members*/
1994 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001995};
1996
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001997
1998/*
1999 * _SSLContext objects
2000 */
2001
2002static PyObject *
2003context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2004{
2005 char *kwlist[] = {"protocol", NULL};
2006 PySSLContext *self;
2007 int proto_version = PY_SSL_VERSION_SSL23;
2008 long options;
2009 SSL_CTX *ctx = NULL;
2010
2011 if (!PyArg_ParseTupleAndKeywords(
2012 args, kwds, "i:_SSLContext", kwlist,
2013 &proto_version))
2014 return NULL;
2015
2016 PySSL_BEGIN_ALLOW_THREADS
2017 if (proto_version == PY_SSL_VERSION_TLS1)
2018 ctx = SSL_CTX_new(TLSv1_method());
2019#if HAVE_TLSv1_2
2020 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2021 ctx = SSL_CTX_new(TLSv1_1_method());
2022 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2023 ctx = SSL_CTX_new(TLSv1_2_method());
2024#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05002025#ifndef OPENSSL_NO_SSL3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002026 else if (proto_version == PY_SSL_VERSION_SSL3)
2027 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Peterson60766c42014-12-05 21:59:35 -05002028#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002029#ifndef OPENSSL_NO_SSL2
2030 else if (proto_version == PY_SSL_VERSION_SSL2)
2031 ctx = SSL_CTX_new(SSLv2_method());
2032#endif
2033 else if (proto_version == PY_SSL_VERSION_SSL23)
2034 ctx = SSL_CTX_new(SSLv23_method());
2035 else
2036 proto_version = -1;
2037 PySSL_END_ALLOW_THREADS
2038
2039 if (proto_version == -1) {
2040 PyErr_SetString(PyExc_ValueError,
2041 "invalid protocol version");
2042 return NULL;
2043 }
2044 if (ctx == NULL) {
2045 PyErr_SetString(PySSLErrorObject,
2046 "failed to allocate SSL context");
2047 return NULL;
2048 }
2049
2050 assert(type != NULL && type->tp_alloc != NULL);
2051 self = (PySSLContext *) type->tp_alloc(type, 0);
2052 if (self == NULL) {
2053 SSL_CTX_free(ctx);
2054 return NULL;
2055 }
2056 self->ctx = ctx;
2057#ifdef OPENSSL_NPN_NEGOTIATED
2058 self->npn_protocols = NULL;
2059#endif
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002060#ifdef HAVE_ALPN
2061 self->alpn_protocols = NULL;
2062#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002063#ifndef OPENSSL_NO_TLSEXT
2064 self->set_hostname = NULL;
2065#endif
2066 /* Don't check host name by default */
2067 self->check_hostname = 0;
2068 /* Defaults */
2069 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2070 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2071 if (proto_version != PY_SSL_VERSION_SSL2)
2072 options |= SSL_OP_NO_SSLv2;
2073 SSL_CTX_set_options(self->ctx, options);
2074
2075#ifndef OPENSSL_NO_ECDH
2076 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2077 prime256v1 by default. This is Apache mod_ssl's initialization
2078 policy, so we should be safe. */
2079#if defined(SSL_CTX_set_ecdh_auto)
2080 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2081#else
2082 {
2083 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2084 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2085 EC_KEY_free(key);
2086 }
2087#endif
2088#endif
2089
2090#define SID_CTX "Python"
2091 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2092 sizeof(SID_CTX));
2093#undef SID_CTX
2094
2095 return (PyObject *)self;
2096}
2097
2098static int
2099context_traverse(PySSLContext *self, visitproc visit, void *arg)
2100{
2101#ifndef OPENSSL_NO_TLSEXT
2102 Py_VISIT(self->set_hostname);
2103#endif
2104 return 0;
2105}
2106
2107static int
2108context_clear(PySSLContext *self)
2109{
2110#ifndef OPENSSL_NO_TLSEXT
2111 Py_CLEAR(self->set_hostname);
2112#endif
2113 return 0;
2114}
2115
2116static void
2117context_dealloc(PySSLContext *self)
2118{
2119 context_clear(self);
2120 SSL_CTX_free(self->ctx);
2121#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002122 PyMem_FREE(self->npn_protocols);
2123#endif
2124#ifdef HAVE_ALPN
2125 PyMem_FREE(self->alpn_protocols);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002126#endif
2127 Py_TYPE(self)->tp_free(self);
2128}
2129
2130static PyObject *
2131set_ciphers(PySSLContext *self, PyObject *args)
2132{
2133 int ret;
2134 const char *cipherlist;
2135
2136 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2137 return NULL;
2138 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2139 if (ret == 0) {
2140 /* Clearing the error queue is necessary on some OpenSSL versions,
2141 otherwise the error will be reported again when another SSL call
2142 is done. */
2143 ERR_clear_error();
2144 PyErr_SetString(PySSLErrorObject,
2145 "No cipher can be selected.");
2146 return NULL;
2147 }
2148 Py_RETURN_NONE;
2149}
2150
Benjamin Petersona99e48c2015-01-28 12:06:39 -05002151#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002152static int
Benjamin Petersonaa707582015-01-23 17:30:26 -05002153do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2154 const unsigned char *server_protocols, unsigned int server_protocols_len,
2155 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002156{
Benjamin Petersonaa707582015-01-23 17:30:26 -05002157 int ret;
2158 if (client_protocols == NULL) {
2159 client_protocols = (unsigned char *)"";
2160 client_protocols_len = 0;
2161 }
2162 if (server_protocols == NULL) {
2163 server_protocols = (unsigned char *)"";
2164 server_protocols_len = 0;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002165 }
2166
Benjamin Petersonaa707582015-01-23 17:30:26 -05002167 ret = SSL_select_next_proto(out, outlen,
2168 server_protocols, server_protocols_len,
2169 client_protocols, client_protocols_len);
2170 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2171 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002172
2173 return SSL_TLSEXT_ERR_OK;
2174}
2175
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002176/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2177static int
2178_advertiseNPN_cb(SSL *s,
2179 const unsigned char **data, unsigned int *len,
2180 void *args)
2181{
2182 PySSLContext *ssl_ctx = (PySSLContext *) args;
2183
2184 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002185 *data = (unsigned char *)"";
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002186 *len = 0;
2187 } else {
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002188 *data = ssl_ctx->npn_protocols;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002189 *len = ssl_ctx->npn_protocols_len;
2190 }
2191
2192 return SSL_TLSEXT_ERR_OK;
2193}
2194/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2195static int
2196_selectNPN_cb(SSL *s,
2197 unsigned char **out, unsigned char *outlen,
2198 const unsigned char *server, unsigned int server_len,
2199 void *args)
2200{
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002201 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002202 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002203 ctx->npn_protocols, ctx->npn_protocols_len);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002204}
2205#endif
2206
2207static PyObject *
2208_set_npn_protocols(PySSLContext *self, PyObject *args)
2209{
2210#ifdef OPENSSL_NPN_NEGOTIATED
2211 Py_buffer protos;
2212
2213 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2214 return NULL;
2215
2216 if (self->npn_protocols != NULL) {
2217 PyMem_Free(self->npn_protocols);
2218 }
2219
2220 self->npn_protocols = PyMem_Malloc(protos.len);
2221 if (self->npn_protocols == NULL) {
2222 PyBuffer_Release(&protos);
2223 return PyErr_NoMemory();
2224 }
2225 memcpy(self->npn_protocols, protos.buf, protos.len);
2226 self->npn_protocols_len = (int) protos.len;
2227
2228 /* set both server and client callbacks, because the context can
2229 * be used to create both types of sockets */
2230 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2231 _advertiseNPN_cb,
2232 self);
2233 SSL_CTX_set_next_proto_select_cb(self->ctx,
2234 _selectNPN_cb,
2235 self);
2236
2237 PyBuffer_Release(&protos);
2238 Py_RETURN_NONE;
2239#else
2240 PyErr_SetString(PyExc_NotImplementedError,
2241 "The NPN extension requires OpenSSL 1.0.1 or later.");
2242 return NULL;
2243#endif
2244}
2245
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002246#ifdef HAVE_ALPN
2247static int
2248_selectALPN_cb(SSL *s,
2249 const unsigned char **out, unsigned char *outlen,
2250 const unsigned char *client_protocols, unsigned int client_protocols_len,
2251 void *args)
2252{
2253 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Petersonaa707582015-01-23 17:30:26 -05002254 return do_protocol_selection(1, (unsigned char **)out, outlen,
2255 ctx->alpn_protocols, ctx->alpn_protocols_len,
2256 client_protocols, client_protocols_len);
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05002257}
2258#endif
2259
2260static PyObject *
2261_set_alpn_protocols(PySSLContext *self, PyObject *args)
2262{
2263#ifdef HAVE_ALPN
2264 Py_buffer protos;
2265
2266 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2267 return NULL;
2268
2269 PyMem_FREE(self->alpn_protocols);
2270 self->alpn_protocols = PyMem_Malloc(protos.len);
2271 if (!self->alpn_protocols)
2272 return PyErr_NoMemory();
2273 memcpy(self->alpn_protocols, protos.buf, protos.len);
2274 self->alpn_protocols_len = protos.len;
2275 PyBuffer_Release(&protos);
2276
2277 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2278 return PyErr_NoMemory();
2279 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2280
2281 PyBuffer_Release(&protos);
2282 Py_RETURN_NONE;
2283#else
2284 PyErr_SetString(PyExc_NotImplementedError,
2285 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2286 return NULL;
2287#endif
2288}
2289
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002290static PyObject *
2291get_verify_mode(PySSLContext *self, void *c)
2292{
2293 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2294 case SSL_VERIFY_NONE:
2295 return PyLong_FromLong(PY_SSL_CERT_NONE);
2296 case SSL_VERIFY_PEER:
2297 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2298 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2299 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2300 }
2301 PyErr_SetString(PySSLErrorObject,
2302 "invalid return value from SSL_CTX_get_verify_mode");
2303 return NULL;
2304}
2305
2306static int
2307set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2308{
2309 int n, mode;
2310 if (!PyArg_Parse(arg, "i", &n))
2311 return -1;
2312 if (n == PY_SSL_CERT_NONE)
2313 mode = SSL_VERIFY_NONE;
2314 else if (n == PY_SSL_CERT_OPTIONAL)
2315 mode = SSL_VERIFY_PEER;
2316 else if (n == PY_SSL_CERT_REQUIRED)
2317 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2318 else {
2319 PyErr_SetString(PyExc_ValueError,
2320 "invalid value for verify_mode");
2321 return -1;
2322 }
2323 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2324 PyErr_SetString(PyExc_ValueError,
2325 "Cannot set verify_mode to CERT_NONE when "
2326 "check_hostname is enabled.");
2327 return -1;
2328 }
2329 SSL_CTX_set_verify(self->ctx, mode, NULL);
2330 return 0;
2331}
2332
2333#ifdef HAVE_OPENSSL_VERIFY_PARAM
2334static PyObject *
2335get_verify_flags(PySSLContext *self, void *c)
2336{
2337 X509_STORE *store;
2338 unsigned long flags;
2339
2340 store = SSL_CTX_get_cert_store(self->ctx);
2341 flags = X509_VERIFY_PARAM_get_flags(store->param);
2342 return PyLong_FromUnsignedLong(flags);
2343}
2344
2345static int
2346set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2347{
2348 X509_STORE *store;
2349 unsigned long new_flags, flags, set, clear;
2350
2351 if (!PyArg_Parse(arg, "k", &new_flags))
2352 return -1;
2353 store = SSL_CTX_get_cert_store(self->ctx);
2354 flags = X509_VERIFY_PARAM_get_flags(store->param);
2355 clear = flags & ~new_flags;
2356 set = ~flags & new_flags;
2357 if (clear) {
2358 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2359 _setSSLError(NULL, 0, __FILE__, __LINE__);
2360 return -1;
2361 }
2362 }
2363 if (set) {
2364 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2365 _setSSLError(NULL, 0, __FILE__, __LINE__);
2366 return -1;
2367 }
2368 }
2369 return 0;
2370}
2371#endif
2372
2373static PyObject *
2374get_options(PySSLContext *self, void *c)
2375{
2376 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2377}
2378
2379static int
2380set_options(PySSLContext *self, PyObject *arg, void *c)
2381{
2382 long new_opts, opts, set, clear;
2383 if (!PyArg_Parse(arg, "l", &new_opts))
2384 return -1;
2385 opts = SSL_CTX_get_options(self->ctx);
2386 clear = opts & ~new_opts;
2387 set = ~opts & new_opts;
2388 if (clear) {
2389#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2390 SSL_CTX_clear_options(self->ctx, clear);
2391#else
2392 PyErr_SetString(PyExc_ValueError,
2393 "can't clear options before OpenSSL 0.9.8m");
2394 return -1;
2395#endif
2396 }
2397 if (set)
2398 SSL_CTX_set_options(self->ctx, set);
2399 return 0;
2400}
2401
2402static PyObject *
2403get_check_hostname(PySSLContext *self, void *c)
2404{
2405 return PyBool_FromLong(self->check_hostname);
2406}
2407
2408static int
2409set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2410{
2411 PyObject *py_check_hostname;
2412 int check_hostname;
2413 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2414 return -1;
2415
2416 check_hostname = PyObject_IsTrue(py_check_hostname);
2417 if (check_hostname < 0)
2418 return -1;
2419 if (check_hostname &&
2420 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2421 PyErr_SetString(PyExc_ValueError,
2422 "check_hostname needs a SSL context with either "
2423 "CERT_OPTIONAL or CERT_REQUIRED");
2424 return -1;
2425 }
2426 self->check_hostname = check_hostname;
2427 return 0;
2428}
2429
2430
2431typedef struct {
2432 PyThreadState *thread_state;
2433 PyObject *callable;
2434 char *password;
2435 int size;
2436 int error;
2437} _PySSLPasswordInfo;
2438
2439static int
2440_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2441 const char *bad_type_error)
2442{
2443 /* Set the password and size fields of a _PySSLPasswordInfo struct
2444 from a unicode, bytes, or byte array object.
2445 The password field will be dynamically allocated and must be freed
2446 by the caller */
2447 PyObject *password_bytes = NULL;
2448 const char *data = NULL;
2449 Py_ssize_t size;
2450
2451 if (PyUnicode_Check(password)) {
2452 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2453 if (!password_bytes) {
2454 goto error;
2455 }
2456 data = PyBytes_AS_STRING(password_bytes);
2457 size = PyBytes_GET_SIZE(password_bytes);
2458 } else if (PyBytes_Check(password)) {
2459 data = PyBytes_AS_STRING(password);
2460 size = PyBytes_GET_SIZE(password);
2461 } else if (PyByteArray_Check(password)) {
2462 data = PyByteArray_AS_STRING(password);
2463 size = PyByteArray_GET_SIZE(password);
2464 } else {
2465 PyErr_SetString(PyExc_TypeError, bad_type_error);
2466 goto error;
2467 }
2468
2469 if (size > (Py_ssize_t)INT_MAX) {
2470 PyErr_Format(PyExc_ValueError,
2471 "password cannot be longer than %d bytes", INT_MAX);
2472 goto error;
2473 }
2474
2475 PyMem_Free(pw_info->password);
2476 pw_info->password = PyMem_Malloc(size);
2477 if (!pw_info->password) {
2478 PyErr_SetString(PyExc_MemoryError,
2479 "unable to allocate password buffer");
2480 goto error;
2481 }
2482 memcpy(pw_info->password, data, size);
2483 pw_info->size = (int)size;
2484
2485 Py_XDECREF(password_bytes);
2486 return 1;
2487
2488error:
2489 Py_XDECREF(password_bytes);
2490 return 0;
2491}
2492
2493static int
2494_password_callback(char *buf, int size, int rwflag, void *userdata)
2495{
2496 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2497 PyObject *fn_ret = NULL;
2498
2499 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2500
2501 if (pw_info->callable) {
2502 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2503 if (!fn_ret) {
2504 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2505 core python API, so we could use it to add a frame here */
2506 goto error;
2507 }
2508
2509 if (!_pwinfo_set(pw_info, fn_ret,
2510 "password callback must return a string")) {
2511 goto error;
2512 }
2513 Py_CLEAR(fn_ret);
2514 }
2515
2516 if (pw_info->size > size) {
2517 PyErr_Format(PyExc_ValueError,
2518 "password cannot be longer than %d bytes", size);
2519 goto error;
2520 }
2521
2522 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2523 memcpy(buf, pw_info->password, pw_info->size);
2524 return pw_info->size;
2525
2526error:
2527 Py_XDECREF(fn_ret);
2528 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2529 pw_info->error = 1;
2530 return -1;
2531}
2532
2533static PyObject *
2534load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2535{
2536 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
Benjamin Peterson93c41332014-11-03 21:12:05 -05002537 PyObject *keyfile = NULL, *keyfile_bytes = NULL, *password = NULL;
2538 char *certfile_bytes = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002539 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2540 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2541 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2542 int r;
2543
2544 errno = 0;
2545 ERR_clear_error();
2546 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002547 "et|OO:load_cert_chain", kwlist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002548 Py_FileSystemDefaultEncoding, &certfile_bytes,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002549 &keyfile, &password))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002550 return NULL;
Benjamin Peterson93c41332014-11-03 21:12:05 -05002551
2552 if (keyfile && keyfile != Py_None) {
2553 if (PyString_Check(keyfile)) {
2554 Py_INCREF(keyfile);
2555 keyfile_bytes = keyfile;
2556 } else {
2557 PyObject *u = PyUnicode_FromObject(keyfile);
2558 if (!u)
2559 goto error;
2560 keyfile_bytes = PyUnicode_AsEncodedString(
2561 u, Py_FileSystemDefaultEncoding, NULL);
2562 Py_DECREF(u);
2563 if (!keyfile_bytes)
2564 goto error;
2565 }
2566 }
2567
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002568 if (password && password != Py_None) {
2569 if (PyCallable_Check(password)) {
2570 pw_info.callable = password;
2571 } else if (!_pwinfo_set(&pw_info, password,
2572 "password should be a string or callable")) {
2573 goto error;
2574 }
2575 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2576 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2577 }
2578 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2579 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2580 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2581 if (r != 1) {
2582 if (pw_info.error) {
2583 ERR_clear_error();
2584 /* the password callback has already set the error information */
2585 }
2586 else if (errno != 0) {
2587 ERR_clear_error();
2588 PyErr_SetFromErrno(PyExc_IOError);
2589 }
2590 else {
2591 _setSSLError(NULL, 0, __FILE__, __LINE__);
2592 }
2593 goto error;
2594 }
2595 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2596 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Benjamin Peterson93c41332014-11-03 21:12:05 -05002597 keyfile_bytes ? PyBytes_AS_STRING(keyfile_bytes) : certfile_bytes,
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002598 SSL_FILETYPE_PEM);
2599 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2600 if (r != 1) {
2601 if (pw_info.error) {
2602 ERR_clear_error();
2603 /* the password callback has already set the error information */
2604 }
2605 else if (errno != 0) {
2606 ERR_clear_error();
2607 PyErr_SetFromErrno(PyExc_IOError);
2608 }
2609 else {
2610 _setSSLError(NULL, 0, __FILE__, __LINE__);
2611 }
2612 goto error;
2613 }
2614 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2615 r = SSL_CTX_check_private_key(self->ctx);
2616 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2617 if (r != 1) {
2618 _setSSLError(NULL, 0, __FILE__, __LINE__);
2619 goto error;
2620 }
2621 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2622 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2623 PyMem_Free(pw_info.password);
2624 Py_RETURN_NONE;
2625
2626error:
2627 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2628 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Benjamin Peterson93c41332014-11-03 21:12:05 -05002629 Py_XDECREF(keyfile_bytes);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002630 PyMem_Free(pw_info.password);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002631 PyMem_Free(certfile_bytes);
2632 return NULL;
2633}
2634
2635/* internal helper function, returns -1 on error
2636 */
2637static int
2638_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2639 int filetype)
2640{
2641 BIO *biobuf = NULL;
2642 X509_STORE *store;
2643 int retval = 0, err, loaded = 0;
2644
2645 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2646
2647 if (len <= 0) {
2648 PyErr_SetString(PyExc_ValueError,
2649 "Empty certificate data");
2650 return -1;
2651 } else if (len > INT_MAX) {
2652 PyErr_SetString(PyExc_OverflowError,
2653 "Certificate data is too long.");
2654 return -1;
2655 }
2656
2657 biobuf = BIO_new_mem_buf(data, (int)len);
2658 if (biobuf == NULL) {
2659 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2660 return -1;
2661 }
2662
2663 store = SSL_CTX_get_cert_store(self->ctx);
2664 assert(store != NULL);
2665
2666 while (1) {
2667 X509 *cert = NULL;
2668 int r;
2669
2670 if (filetype == SSL_FILETYPE_ASN1) {
2671 cert = d2i_X509_bio(biobuf, NULL);
2672 } else {
2673 cert = PEM_read_bio_X509(biobuf, NULL,
2674 self->ctx->default_passwd_callback,
2675 self->ctx->default_passwd_callback_userdata);
2676 }
2677 if (cert == NULL) {
2678 break;
2679 }
2680 r = X509_STORE_add_cert(store, cert);
2681 X509_free(cert);
2682 if (!r) {
2683 err = ERR_peek_last_error();
2684 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2685 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2686 /* cert already in hash table, not an error */
2687 ERR_clear_error();
2688 } else {
2689 break;
2690 }
2691 }
2692 loaded++;
2693 }
2694
2695 err = ERR_peek_last_error();
2696 if ((filetype == SSL_FILETYPE_ASN1) &&
2697 (loaded > 0) &&
2698 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2699 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2700 /* EOF ASN1 file, not an error */
2701 ERR_clear_error();
2702 retval = 0;
2703 } else if ((filetype == SSL_FILETYPE_PEM) &&
2704 (loaded > 0) &&
2705 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2706 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2707 /* EOF PEM file, not an error */
2708 ERR_clear_error();
2709 retval = 0;
2710 } else {
2711 _setSSLError(NULL, 0, __FILE__, __LINE__);
2712 retval = -1;
2713 }
2714
2715 BIO_free(biobuf);
2716 return retval;
2717}
2718
2719
2720static PyObject *
2721load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2722{
2723 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2724 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2725 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2726 const char *cafile_buf = NULL, *capath_buf = NULL;
2727 int r = 0, ok = 1;
2728
2729 errno = 0;
2730 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2731 "|OOO:load_verify_locations", kwlist,
2732 &cafile, &capath, &cadata))
2733 return NULL;
2734
2735 if (cafile == Py_None)
2736 cafile = NULL;
2737 if (capath == Py_None)
2738 capath = NULL;
2739 if (cadata == Py_None)
2740 cadata = NULL;
2741
2742 if (cafile == NULL && capath == NULL && cadata == NULL) {
2743 PyErr_SetString(PyExc_TypeError,
2744 "cafile, capath and cadata cannot be all omitted");
2745 goto error;
2746 }
2747
2748 if (cafile) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002749 if (PyString_Check(cafile)) {
2750 Py_INCREF(cafile);
2751 cafile_bytes = cafile;
2752 } else {
2753 PyObject *u = PyUnicode_FromObject(cafile);
2754 if (!u)
2755 goto error;
2756 cafile_bytes = PyUnicode_AsEncodedString(
2757 u, Py_FileSystemDefaultEncoding, NULL);
2758 Py_DECREF(u);
2759 if (!cafile_bytes)
2760 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002761 }
2762 }
2763 if (capath) {
Benjamin Peterson876473e2014-08-28 09:33:21 -04002764 if (PyString_Check(capath)) {
2765 Py_INCREF(capath);
2766 capath_bytes = capath;
2767 } else {
2768 PyObject *u = PyUnicode_FromObject(capath);
2769 if (!u)
2770 goto error;
2771 capath_bytes = PyUnicode_AsEncodedString(
2772 u, Py_FileSystemDefaultEncoding, NULL);
2773 Py_DECREF(u);
2774 if (!capath_bytes)
2775 goto error;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002776 }
2777 }
2778
2779 /* validata cadata type and load cadata */
2780 if (cadata) {
2781 Py_buffer buf;
2782 PyObject *cadata_ascii = NULL;
2783
2784 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2785 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2786 PyBuffer_Release(&buf);
2787 PyErr_SetString(PyExc_TypeError,
2788 "cadata should be a contiguous buffer with "
2789 "a single dimension");
2790 goto error;
2791 }
2792 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2793 PyBuffer_Release(&buf);
2794 if (r == -1) {
2795 goto error;
2796 }
2797 } else {
2798 PyErr_Clear();
2799 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2800 if (cadata_ascii == NULL) {
2801 PyErr_SetString(PyExc_TypeError,
2802 "cadata should be a ASCII string or a "
2803 "bytes-like object");
2804 goto error;
2805 }
2806 r = _add_ca_certs(self,
2807 PyBytes_AS_STRING(cadata_ascii),
2808 PyBytes_GET_SIZE(cadata_ascii),
2809 SSL_FILETYPE_PEM);
2810 Py_DECREF(cadata_ascii);
2811 if (r == -1) {
2812 goto error;
2813 }
2814 }
2815 }
2816
2817 /* load cafile or capath */
2818 if (cafile_bytes || capath_bytes) {
2819 if (cafile)
2820 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2821 if (capath)
2822 capath_buf = PyBytes_AS_STRING(capath_bytes);
2823 PySSL_BEGIN_ALLOW_THREADS
2824 r = SSL_CTX_load_verify_locations(
2825 self->ctx,
2826 cafile_buf,
2827 capath_buf);
2828 PySSL_END_ALLOW_THREADS
2829 if (r != 1) {
2830 ok = 0;
2831 if (errno != 0) {
2832 ERR_clear_error();
2833 PyErr_SetFromErrno(PyExc_IOError);
2834 }
2835 else {
2836 _setSSLError(NULL, 0, __FILE__, __LINE__);
2837 }
2838 goto error;
2839 }
2840 }
2841 goto end;
2842
2843 error:
2844 ok = 0;
2845 end:
2846 Py_XDECREF(cafile_bytes);
2847 Py_XDECREF(capath_bytes);
2848 if (ok) {
2849 Py_RETURN_NONE;
2850 } else {
2851 return NULL;
2852 }
2853}
2854
2855static PyObject *
2856load_dh_params(PySSLContext *self, PyObject *filepath)
2857{
2858 BIO *bio;
2859 DH *dh;
2860 char *path = PyBytes_AsString(filepath);
2861 if (!path) {
2862 return NULL;
2863 }
2864
2865 bio = BIO_new_file(path, "r");
2866 if (bio == NULL) {
2867 ERR_clear_error();
2868 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2869 return NULL;
2870 }
2871 errno = 0;
2872 PySSL_BEGIN_ALLOW_THREADS
2873 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2874 BIO_free(bio);
2875 PySSL_END_ALLOW_THREADS
2876 if (dh == NULL) {
2877 if (errno != 0) {
2878 ERR_clear_error();
2879 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2880 }
2881 else {
2882 _setSSLError(NULL, 0, __FILE__, __LINE__);
2883 }
2884 return NULL;
2885 }
2886 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2887 _setSSLError(NULL, 0, __FILE__, __LINE__);
2888 DH_free(dh);
2889 Py_RETURN_NONE;
2890}
2891
2892static PyObject *
2893context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2894{
2895 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2896 PySocketSockObject *sock;
2897 int server_side = 0;
2898 char *hostname = NULL;
2899 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2900
2901 /* server_hostname is either None (or absent), or to be encoded
2902 using the idna encoding. */
2903 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2904 PySocketModule.Sock_Type,
2905 &sock, &server_side,
2906 Py_TYPE(Py_None), &hostname_obj,
2907 &ssl_sock)) {
2908 PyErr_Clear();
2909 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2910 PySocketModule.Sock_Type,
2911 &sock, &server_side,
2912 "idna", &hostname, &ssl_sock))
2913 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002914 }
2915
2916 res = (PyObject *) newPySSLSocket(self, sock, server_side,
2917 hostname, ssl_sock);
2918 if (hostname != NULL)
2919 PyMem_Free(hostname);
2920 return res;
2921}
2922
2923static PyObject *
2924session_stats(PySSLContext *self, PyObject *unused)
2925{
2926 int r;
2927 PyObject *value, *stats = PyDict_New();
2928 if (!stats)
2929 return NULL;
2930
2931#define ADD_STATS(SSL_NAME, KEY_NAME) \
2932 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2933 if (value == NULL) \
2934 goto error; \
2935 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2936 Py_DECREF(value); \
2937 if (r < 0) \
2938 goto error;
2939
2940 ADD_STATS(number, "number");
2941 ADD_STATS(connect, "connect");
2942 ADD_STATS(connect_good, "connect_good");
2943 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2944 ADD_STATS(accept, "accept");
2945 ADD_STATS(accept_good, "accept_good");
2946 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2947 ADD_STATS(accept, "accept");
2948 ADD_STATS(hits, "hits");
2949 ADD_STATS(misses, "misses");
2950 ADD_STATS(timeouts, "timeouts");
2951 ADD_STATS(cache_full, "cache_full");
2952
2953#undef ADD_STATS
2954
2955 return stats;
2956
2957error:
2958 Py_DECREF(stats);
2959 return NULL;
2960}
2961
2962static PyObject *
2963set_default_verify_paths(PySSLContext *self, PyObject *unused)
2964{
2965 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2966 _setSSLError(NULL, 0, __FILE__, __LINE__);
2967 return NULL;
2968 }
2969 Py_RETURN_NONE;
2970}
2971
2972#ifndef OPENSSL_NO_ECDH
2973static PyObject *
2974set_ecdh_curve(PySSLContext *self, PyObject *name)
2975{
2976 char *name_bytes;
2977 int nid;
2978 EC_KEY *key;
2979
2980 name_bytes = PyBytes_AsString(name);
2981 if (!name_bytes) {
2982 return NULL;
2983 }
2984 nid = OBJ_sn2nid(name_bytes);
2985 if (nid == 0) {
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002986 PyObject *r = PyObject_Repr(name);
2987 if (!r)
2988 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002989 PyErr_Format(PyExc_ValueError,
Benjamin Peterson7ed3e292014-08-20 21:37:01 -05002990 "unknown elliptic curve name %s", PyString_AS_STRING(r));
2991 Py_DECREF(r);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05002992 return NULL;
2993 }
2994 key = EC_KEY_new_by_curve_name(nid);
2995 if (key == NULL) {
2996 _setSSLError(NULL, 0, __FILE__, __LINE__);
2997 return NULL;
2998 }
2999 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3000 EC_KEY_free(key);
3001 Py_RETURN_NONE;
3002}
3003#endif
3004
3005#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3006static int
3007_servername_callback(SSL *s, int *al, void *args)
3008{
3009 int ret;
3010 PySSLContext *ssl_ctx = (PySSLContext *) args;
3011 PySSLSocket *ssl;
3012 PyObject *servername_o;
3013 PyObject *servername_idna;
3014 PyObject *result;
3015 /* The high-level ssl.SSLSocket object */
3016 PyObject *ssl_socket;
3017 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3018#ifdef WITH_THREAD
3019 PyGILState_STATE gstate = PyGILState_Ensure();
3020#endif
3021
3022 if (ssl_ctx->set_hostname == NULL) {
3023 /* remove race condition in this the call back while if removing the
3024 * callback is in progress */
3025#ifdef WITH_THREAD
3026 PyGILState_Release(gstate);
3027#endif
3028 return SSL_TLSEXT_ERR_OK;
3029 }
3030
3031 ssl = SSL_get_app_data(s);
3032 assert(PySSLSocket_Check(ssl));
Benjamin Peterson2f334562014-10-01 23:53:01 -04003033 if (ssl->ssl_sock == NULL) {
3034 ssl_socket = Py_None;
3035 } else {
3036 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
3037 Py_INCREF(ssl_socket);
3038 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003039 if (ssl_socket == Py_None) {
3040 goto error;
3041 }
3042
3043 if (servername == NULL) {
3044 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3045 Py_None, ssl_ctx, NULL);
3046 }
3047 else {
3048 servername_o = PyBytes_FromString(servername);
3049 if (servername_o == NULL) {
3050 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3051 goto error;
3052 }
3053 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3054 if (servername_idna == NULL) {
3055 PyErr_WriteUnraisable(servername_o);
3056 Py_DECREF(servername_o);
3057 goto error;
3058 }
3059 Py_DECREF(servername_o);
3060 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3061 servername_idna, ssl_ctx, NULL);
3062 Py_DECREF(servername_idna);
3063 }
3064 Py_DECREF(ssl_socket);
3065
3066 if (result == NULL) {
3067 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3068 *al = SSL_AD_HANDSHAKE_FAILURE;
3069 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3070 }
3071 else {
3072 if (result != Py_None) {
3073 *al = (int) PyLong_AsLong(result);
3074 if (PyErr_Occurred()) {
3075 PyErr_WriteUnraisable(result);
3076 *al = SSL_AD_INTERNAL_ERROR;
3077 }
3078 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3079 }
3080 else {
3081 ret = SSL_TLSEXT_ERR_OK;
3082 }
3083 Py_DECREF(result);
3084 }
3085
3086#ifdef WITH_THREAD
3087 PyGILState_Release(gstate);
3088#endif
3089 return ret;
3090
3091error:
3092 Py_DECREF(ssl_socket);
3093 *al = SSL_AD_INTERNAL_ERROR;
3094 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3095#ifdef WITH_THREAD
3096 PyGILState_Release(gstate);
3097#endif
3098 return ret;
3099}
3100#endif
3101
3102PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3103"set_servername_callback(method)\n\
3104\n\
3105This sets a callback that will be called when a server name is provided by\n\
3106the SSL/TLS client in the SNI extension.\n\
3107\n\
3108If the argument is None then the callback is disabled. The method is called\n\
3109with the SSLSocket, the server name as a string, and the SSLContext object.\n\
3110See RFC 6066 for details of the SNI extension.");
3111
3112static PyObject *
3113set_servername_callback(PySSLContext *self, PyObject *args)
3114{
3115#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3116 PyObject *cb;
3117
3118 if (!PyArg_ParseTuple(args, "O", &cb))
3119 return NULL;
3120
3121 Py_CLEAR(self->set_hostname);
3122 if (cb == Py_None) {
3123 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3124 }
3125 else {
3126 if (!PyCallable_Check(cb)) {
3127 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3128 PyErr_SetString(PyExc_TypeError,
3129 "not a callable object");
3130 return NULL;
3131 }
3132 Py_INCREF(cb);
3133 self->set_hostname = cb;
3134 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3135 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3136 }
3137 Py_RETURN_NONE;
3138#else
3139 PyErr_SetString(PyExc_NotImplementedError,
3140 "The TLS extension servername callback, "
3141 "SSL_CTX_set_tlsext_servername_callback, "
3142 "is not in the current OpenSSL library.");
3143 return NULL;
3144#endif
3145}
3146
3147PyDoc_STRVAR(PySSL_get_stats_doc,
3148"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3149\n\
3150Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3151CA extension and certificate revocation lists inside the context's cert\n\
3152store.\n\
3153NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3154been used at least once.");
3155
3156static PyObject *
3157cert_store_stats(PySSLContext *self)
3158{
3159 X509_STORE *store;
3160 X509_OBJECT *obj;
3161 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3162
3163 store = SSL_CTX_get_cert_store(self->ctx);
3164 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3165 obj = sk_X509_OBJECT_value(store->objs, i);
3166 switch (obj->type) {
3167 case X509_LU_X509:
3168 x509++;
3169 if (X509_check_ca(obj->data.x509)) {
3170 ca++;
3171 }
3172 break;
3173 case X509_LU_CRL:
3174 crl++;
3175 break;
3176 case X509_LU_PKEY:
3177 pkey++;
3178 break;
3179 default:
3180 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3181 * As far as I can tell they are internal states and never
3182 * stored in a cert store */
3183 break;
3184 }
3185 }
3186 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3187 "x509_ca", ca);
3188}
3189
3190PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3191"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3192\n\
3193Returns a list of dicts with information of loaded CA certs. If the\n\
3194optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3195NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3196been used at least once.");
3197
3198static PyObject *
3199get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3200{
3201 char *kwlist[] = {"binary_form", NULL};
3202 X509_STORE *store;
3203 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3204 int i;
3205 int binary_mode = 0;
3206
3207 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3208 kwlist, &py_binary_mode)) {
3209 return NULL;
3210 }
3211 binary_mode = PyObject_IsTrue(py_binary_mode);
3212 if (binary_mode < 0) {
3213 return NULL;
3214 }
3215
3216 if ((rlist = PyList_New(0)) == NULL) {
3217 return NULL;
3218 }
3219
3220 store = SSL_CTX_get_cert_store(self->ctx);
3221 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3222 X509_OBJECT *obj;
3223 X509 *cert;
3224
3225 obj = sk_X509_OBJECT_value(store->objs, i);
3226 if (obj->type != X509_LU_X509) {
3227 /* not a x509 cert */
3228 continue;
3229 }
3230 /* CA for any purpose */
3231 cert = obj->data.x509;
3232 if (!X509_check_ca(cert)) {
3233 continue;
3234 }
3235 if (binary_mode) {
3236 ci = _certificate_to_der(cert);
3237 } else {
3238 ci = _decode_certificate(cert);
3239 }
3240 if (ci == NULL) {
3241 goto error;
3242 }
3243 if (PyList_Append(rlist, ci) == -1) {
3244 goto error;
3245 }
3246 Py_CLEAR(ci);
3247 }
3248 return rlist;
3249
3250 error:
3251 Py_XDECREF(ci);
3252 Py_XDECREF(rlist);
3253 return NULL;
3254}
3255
3256
3257static PyGetSetDef context_getsetlist[] = {
3258 {"check_hostname", (getter) get_check_hostname,
3259 (setter) set_check_hostname, NULL},
3260 {"options", (getter) get_options,
3261 (setter) set_options, NULL},
3262#ifdef HAVE_OPENSSL_VERIFY_PARAM
3263 {"verify_flags", (getter) get_verify_flags,
3264 (setter) set_verify_flags, NULL},
3265#endif
3266 {"verify_mode", (getter) get_verify_mode,
3267 (setter) set_verify_mode, NULL},
3268 {NULL}, /* sentinel */
3269};
3270
3271static struct PyMethodDef context_methods[] = {
3272 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3273 METH_VARARGS | METH_KEYWORDS, NULL},
3274 {"set_ciphers", (PyCFunction) set_ciphers,
3275 METH_VARARGS, NULL},
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05003276 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3277 METH_VARARGS, NULL},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003278 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3279 METH_VARARGS, NULL},
3280 {"load_cert_chain", (PyCFunction) load_cert_chain,
3281 METH_VARARGS | METH_KEYWORDS, NULL},
3282 {"load_dh_params", (PyCFunction) load_dh_params,
3283 METH_O, NULL},
3284 {"load_verify_locations", (PyCFunction) load_verify_locations,
3285 METH_VARARGS | METH_KEYWORDS, NULL},
3286 {"session_stats", (PyCFunction) session_stats,
3287 METH_NOARGS, NULL},
3288 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3289 METH_NOARGS, NULL},
3290#ifndef OPENSSL_NO_ECDH
3291 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3292 METH_O, NULL},
3293#endif
3294 {"set_servername_callback", (PyCFunction) set_servername_callback,
3295 METH_VARARGS, PySSL_set_servername_callback_doc},
3296 {"cert_store_stats", (PyCFunction) cert_store_stats,
3297 METH_NOARGS, PySSL_get_stats_doc},
3298 {"get_ca_certs", (PyCFunction) get_ca_certs,
3299 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3300 {NULL, NULL} /* sentinel */
3301};
3302
3303static PyTypeObject PySSLContext_Type = {
3304 PyVarObject_HEAD_INIT(NULL, 0)
3305 "_ssl._SSLContext", /*tp_name*/
3306 sizeof(PySSLContext), /*tp_basicsize*/
3307 0, /*tp_itemsize*/
3308 (destructor)context_dealloc, /*tp_dealloc*/
3309 0, /*tp_print*/
3310 0, /*tp_getattr*/
3311 0, /*tp_setattr*/
3312 0, /*tp_reserved*/
3313 0, /*tp_repr*/
3314 0, /*tp_as_number*/
3315 0, /*tp_as_sequence*/
3316 0, /*tp_as_mapping*/
3317 0, /*tp_hash*/
3318 0, /*tp_call*/
3319 0, /*tp_str*/
3320 0, /*tp_getattro*/
3321 0, /*tp_setattro*/
3322 0, /*tp_as_buffer*/
3323 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3324 0, /*tp_doc*/
3325 (traverseproc) context_traverse, /*tp_traverse*/
3326 (inquiry) context_clear, /*tp_clear*/
3327 0, /*tp_richcompare*/
3328 0, /*tp_weaklistoffset*/
3329 0, /*tp_iter*/
3330 0, /*tp_iternext*/
3331 context_methods, /*tp_methods*/
3332 0, /*tp_members*/
3333 context_getsetlist, /*tp_getset*/
3334 0, /*tp_base*/
3335 0, /*tp_dict*/
3336 0, /*tp_descr_get*/
3337 0, /*tp_descr_set*/
3338 0, /*tp_dictoffset*/
3339 0, /*tp_init*/
3340 0, /*tp_alloc*/
3341 context_new, /*tp_new*/
3342};
3343
3344
3345
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003346#ifdef HAVE_OPENSSL_RAND
3347
3348/* helper routines for seeding the SSL PRNG */
3349static PyObject *
3350PySSL_RAND_add(PyObject *self, PyObject *args)
3351{
3352 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003353 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003354 double entropy;
3355
3356 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003357 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003358 do {
3359 if (len >= INT_MAX) {
3360 written = INT_MAX;
3361 } else {
3362 written = len;
3363 }
3364 RAND_add(buf, (int)written, entropy);
3365 buf += written;
3366 len -= written;
3367 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003368 Py_INCREF(Py_None);
3369 return Py_None;
3370}
3371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003372PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003373"RAND_add(string, entropy)\n\
3374\n\
3375Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003376bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003377
3378static PyObject *
3379PySSL_RAND_status(PyObject *self)
3380{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003381 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003382}
3383
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003384PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003385"RAND_status() -> 0 or 1\n\
3386\n\
3387Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3388It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003389using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003390
Victor Stinner7c906672015-01-06 13:53:37 +01003391#endif /* HAVE_OPENSSL_RAND */
3392
3393
3394#ifdef HAVE_RAND_EGD
3395
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003396static PyObject *
3397PySSL_RAND_egd(PyObject *self, PyObject *arg)
3398{
3399 int bytes;
3400
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003401 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003402 return PyErr_Format(PyExc_TypeError,
3403 "RAND_egd() expected string, found %s",
3404 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003405 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003406 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003407 PyErr_SetString(PySSLErrorObject,
3408 "EGD connection failed or EGD did not return "
3409 "enough data to seed the PRNG");
3410 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003411 }
3412 return PyInt_FromLong(bytes);
3413}
3414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003415PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003416"RAND_egd(path) -> bytes\n\
3417\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003418Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3419Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003420fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003421
Victor Stinner7c906672015-01-06 13:53:37 +01003422#endif /* HAVE_RAND_EGD */
Christian Heimes0d604cf2013-08-21 13:26:05 +02003423
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003424
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003425PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3426"get_default_verify_paths() -> tuple\n\
3427\n\
3428Return search paths and environment vars that are used by SSLContext's\n\
3429set_default_verify_paths() to load default CAs. The values are\n\
3430'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3431
3432static PyObject *
3433PySSL_get_default_verify_paths(PyObject *self)
3434{
3435 PyObject *ofile_env = NULL;
3436 PyObject *ofile = NULL;
3437 PyObject *odir_env = NULL;
3438 PyObject *odir = NULL;
3439
3440#define convert(info, target) { \
3441 const char *tmp = (info); \
3442 target = NULL; \
3443 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3444 else { target = PyBytes_FromString(tmp); } \
3445 if (!target) goto error; \
3446 } while(0)
3447
3448 convert(X509_get_default_cert_file_env(), ofile_env);
3449 convert(X509_get_default_cert_file(), ofile);
3450 convert(X509_get_default_cert_dir_env(), odir_env);
3451 convert(X509_get_default_cert_dir(), odir);
3452#undef convert
3453
3454 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3455
3456 error:
3457 Py_XDECREF(ofile_env);
3458 Py_XDECREF(ofile);
3459 Py_XDECREF(odir_env);
3460 Py_XDECREF(odir);
3461 return NULL;
3462}
3463
3464static PyObject*
3465asn1obj2py(ASN1_OBJECT *obj)
3466{
3467 int nid;
3468 const char *ln, *sn;
3469 char buf[100];
3470 Py_ssize_t buflen;
3471
3472 nid = OBJ_obj2nid(obj);
3473 if (nid == NID_undef) {
3474 PyErr_Format(PyExc_ValueError, "Unknown object");
3475 return NULL;
3476 }
3477 sn = OBJ_nid2sn(nid);
3478 ln = OBJ_nid2ln(nid);
3479 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3480 if (buflen < 0) {
3481 _setSSLError(NULL, 0, __FILE__, __LINE__);
3482 return NULL;
3483 }
3484 if (buflen) {
3485 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3486 } else {
3487 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3488 }
3489}
3490
3491PyDoc_STRVAR(PySSL_txt2obj_doc,
3492"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3493\n\
3494Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3495objects are looked up by OID. With name=True short and long name are also\n\
3496matched.");
3497
3498static PyObject*
3499PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3500{
3501 char *kwlist[] = {"txt", "name", NULL};
3502 PyObject *result = NULL;
3503 char *txt;
3504 PyObject *pyname = Py_None;
3505 int name = 0;
3506 ASN1_OBJECT *obj;
3507
3508 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3509 kwlist, &txt, &pyname)) {
3510 return NULL;
3511 }
3512 name = PyObject_IsTrue(pyname);
3513 if (name < 0)
3514 return NULL;
3515 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3516 if (obj == NULL) {
3517 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3518 return NULL;
3519 }
3520 result = asn1obj2py(obj);
3521 ASN1_OBJECT_free(obj);
3522 return result;
3523}
3524
3525PyDoc_STRVAR(PySSL_nid2obj_doc,
3526"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3527\n\
3528Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3529
3530static PyObject*
3531PySSL_nid2obj(PyObject *self, PyObject *args)
3532{
3533 PyObject *result = NULL;
3534 int nid;
3535 ASN1_OBJECT *obj;
3536
3537 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3538 return NULL;
3539 }
3540 if (nid < NID_undef) {
3541 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3542 return NULL;
3543 }
3544 obj = OBJ_nid2obj(nid);
3545 if (obj == NULL) {
3546 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3547 return NULL;
3548 }
3549 result = asn1obj2py(obj);
3550 ASN1_OBJECT_free(obj);
3551 return result;
3552}
3553
3554#ifdef _MSC_VER
3555
3556static PyObject*
3557certEncodingType(DWORD encodingType)
3558{
3559 static PyObject *x509_asn = NULL;
3560 static PyObject *pkcs_7_asn = NULL;
3561
3562 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003563 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003564 if (x509_asn == NULL)
3565 return NULL;
3566 }
3567 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003568 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003569 if (pkcs_7_asn == NULL)
3570 return NULL;
3571 }
3572 switch(encodingType) {
3573 case X509_ASN_ENCODING:
3574 Py_INCREF(x509_asn);
3575 return x509_asn;
3576 case PKCS_7_ASN_ENCODING:
3577 Py_INCREF(pkcs_7_asn);
3578 return pkcs_7_asn;
3579 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003580 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003581 }
3582}
3583
3584static PyObject*
3585parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3586{
3587 CERT_ENHKEY_USAGE *usage;
3588 DWORD size, error, i;
3589 PyObject *retval;
3590
3591 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3592 error = GetLastError();
3593 if (error == CRYPT_E_NOT_FOUND) {
3594 Py_RETURN_TRUE;
3595 }
3596 return PyErr_SetFromWindowsErr(error);
3597 }
3598
3599 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3600 if (usage == NULL) {
3601 return PyErr_NoMemory();
3602 }
3603
3604 /* Now get the actual enhanced usage property */
3605 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3606 PyMem_Free(usage);
3607 error = GetLastError();
3608 if (error == CRYPT_E_NOT_FOUND) {
3609 Py_RETURN_TRUE;
3610 }
3611 return PyErr_SetFromWindowsErr(error);
3612 }
3613 retval = PySet_New(NULL);
3614 if (retval == NULL) {
3615 goto error;
3616 }
3617 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3618 if (usage->rgpszUsageIdentifier[i]) {
3619 PyObject *oid;
3620 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003621 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003622 if (oid == NULL) {
3623 Py_CLEAR(retval);
3624 goto error;
3625 }
3626 err = PySet_Add(retval, oid);
3627 Py_DECREF(oid);
3628 if (err == -1) {
3629 Py_CLEAR(retval);
3630 goto error;
3631 }
3632 }
3633 }
3634 error:
3635 PyMem_Free(usage);
3636 return retval;
3637}
3638
3639PyDoc_STRVAR(PySSL_enum_certificates_doc,
3640"enum_certificates(store_name) -> []\n\
3641\n\
3642Retrieve certificates from Windows' cert store. store_name may be one of\n\
3643'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3644The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3645encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3646PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3647boolean True.");
3648
3649static PyObject *
3650PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3651{
3652 char *kwlist[] = {"store_name", NULL};
3653 char *store_name;
3654 HCERTSTORE hStore = NULL;
3655 PCCERT_CONTEXT pCertCtx = NULL;
3656 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3657 PyObject *result = NULL;
3658
3659 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3660 kwlist, &store_name)) {
3661 return NULL;
3662 }
3663 result = PyList_New(0);
3664 if (result == NULL) {
3665 return NULL;
3666 }
3667 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3668 if (hStore == NULL) {
3669 Py_DECREF(result);
3670 return PyErr_SetFromWindowsErr(GetLastError());
3671 }
3672
3673 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3674 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3675 pCertCtx->cbCertEncoded);
3676 if (!cert) {
3677 Py_CLEAR(result);
3678 break;
3679 }
3680 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3681 Py_CLEAR(result);
3682 break;
3683 }
3684 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3685 if (keyusage == Py_True) {
3686 Py_DECREF(keyusage);
3687 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3688 }
3689 if (keyusage == NULL) {
3690 Py_CLEAR(result);
3691 break;
3692 }
3693 if ((tup = PyTuple_New(3)) == NULL) {
3694 Py_CLEAR(result);
3695 break;
3696 }
3697 PyTuple_SET_ITEM(tup, 0, cert);
3698 cert = NULL;
3699 PyTuple_SET_ITEM(tup, 1, enc);
3700 enc = NULL;
3701 PyTuple_SET_ITEM(tup, 2, keyusage);
3702 keyusage = NULL;
3703 if (PyList_Append(result, tup) < 0) {
3704 Py_CLEAR(result);
3705 break;
3706 }
3707 Py_CLEAR(tup);
3708 }
3709 if (pCertCtx) {
3710 /* loop ended with an error, need to clean up context manually */
3711 CertFreeCertificateContext(pCertCtx);
3712 }
3713
3714 /* In error cases cert, enc and tup may not be NULL */
3715 Py_XDECREF(cert);
3716 Py_XDECREF(enc);
3717 Py_XDECREF(keyusage);
3718 Py_XDECREF(tup);
3719
3720 if (!CertCloseStore(hStore, 0)) {
3721 /* This error case might shadow another exception.*/
3722 Py_XDECREF(result);
3723 return PyErr_SetFromWindowsErr(GetLastError());
3724 }
3725 return result;
3726}
3727
3728PyDoc_STRVAR(PySSL_enum_crls_doc,
3729"enum_crls(store_name) -> []\n\
3730\n\
3731Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3732'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3733The function returns a list of (bytes, encoding_type) tuples. The\n\
3734encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3735PKCS_7_ASN_ENCODING.");
3736
3737static PyObject *
3738PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3739{
3740 char *kwlist[] = {"store_name", NULL};
3741 char *store_name;
3742 HCERTSTORE hStore = NULL;
3743 PCCRL_CONTEXT pCrlCtx = NULL;
3744 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3745 PyObject *result = NULL;
3746
3747 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3748 kwlist, &store_name)) {
3749 return NULL;
3750 }
3751 result = PyList_New(0);
3752 if (result == NULL) {
3753 return NULL;
3754 }
3755 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3756 if (hStore == NULL) {
3757 Py_DECREF(result);
3758 return PyErr_SetFromWindowsErr(GetLastError());
3759 }
3760
3761 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3762 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3763 pCrlCtx->cbCrlEncoded);
3764 if (!crl) {
3765 Py_CLEAR(result);
3766 break;
3767 }
3768 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3769 Py_CLEAR(result);
3770 break;
3771 }
3772 if ((tup = PyTuple_New(2)) == NULL) {
3773 Py_CLEAR(result);
3774 break;
3775 }
3776 PyTuple_SET_ITEM(tup, 0, crl);
3777 crl = NULL;
3778 PyTuple_SET_ITEM(tup, 1, enc);
3779 enc = NULL;
3780
3781 if (PyList_Append(result, tup) < 0) {
3782 Py_CLEAR(result);
3783 break;
3784 }
3785 Py_CLEAR(tup);
3786 }
3787 if (pCrlCtx) {
3788 /* loop ended with an error, need to clean up context manually */
3789 CertFreeCRLContext(pCrlCtx);
3790 }
3791
3792 /* In error cases cert, enc and tup may not be NULL */
3793 Py_XDECREF(crl);
3794 Py_XDECREF(enc);
3795 Py_XDECREF(tup);
3796
3797 if (!CertCloseStore(hStore, 0)) {
3798 /* This error case might shadow another exception.*/
3799 Py_XDECREF(result);
3800 return PyErr_SetFromWindowsErr(GetLastError());
3801 }
3802 return result;
3803}
3804
3805#endif /* _MSC_VER */
3806
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003807/* List of functions exported by this module. */
3808
3809static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003810 {"_test_decode_cert", PySSL_test_decode_certificate,
3811 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003812#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003813 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3814 PySSL_RAND_add_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003815 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3816 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003817#endif
Victor Stinner7c906672015-01-06 13:53:37 +01003818#ifdef HAVE_RAND_EGD
3819 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
3820 PySSL_RAND_egd_doc},
3821#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003822 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3823 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3824#ifdef _MSC_VER
3825 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3826 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3827 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3828 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3829#endif
3830 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3831 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3832 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3833 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003834 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003835};
3836
3837
Bill Janssen98d19da2007-09-10 21:51:02 +00003838#ifdef WITH_THREAD
3839
3840/* an implementation of OpenSSL threading operations in terms
3841 of the Python C thread library */
3842
3843static PyThread_type_lock *_ssl_locks = NULL;
3844
Christian Heimes10107812013-08-19 17:36:29 +02003845#if OPENSSL_VERSION_NUMBER >= 0x10000000
3846/* use new CRYPTO_THREADID API. */
3847static void
3848_ssl_threadid_callback(CRYPTO_THREADID *id)
3849{
3850 CRYPTO_THREADID_set_numeric(id,
3851 (unsigned long)PyThread_get_thread_ident());
3852}
3853#else
3854/* deprecated CRYPTO_set_id_callback() API. */
3855static unsigned long
3856_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003857 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003858}
Christian Heimes10107812013-08-19 17:36:29 +02003859#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003860
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003861static void _ssl_thread_locking_function
3862 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003863 /* this function is needed to perform locking on shared data
3864 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003865 structures that will be implicitly shared whenever multiple
3866 threads use OpenSSL.) Multi-threaded applications will
3867 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003868
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003869 locking_function() must be able to handle up to
3870 CRYPTO_num_locks() different mutex locks. It sets the n-th
3871 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003872
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003873 file and line are the file number of the function setting the
3874 lock. They can be useful for debugging.
3875 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003876
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003877 if ((_ssl_locks == NULL) ||
3878 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3879 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003880
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003881 if (mode & CRYPTO_LOCK) {
3882 PyThread_acquire_lock(_ssl_locks[n], 1);
3883 } else {
3884 PyThread_release_lock(_ssl_locks[n]);
3885 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003886}
3887
3888static int _setup_ssl_threads(void) {
3889
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003890 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003891
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003892 if (_ssl_locks == NULL) {
3893 _ssl_locks_count = CRYPTO_num_locks();
3894 _ssl_locks = (PyThread_type_lock *)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003895 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003896 if (_ssl_locks == NULL)
3897 return 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003898 memset(_ssl_locks, 0,
3899 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003900 for (i = 0; i < _ssl_locks_count; i++) {
3901 _ssl_locks[i] = PyThread_allocate_lock();
3902 if (_ssl_locks[i] == NULL) {
3903 unsigned int j;
3904 for (j = 0; j < i; j++) {
3905 PyThread_free_lock(_ssl_locks[j]);
3906 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003907 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003908 return 0;
3909 }
3910 }
3911 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02003912#if OPENSSL_VERSION_NUMBER >= 0x10000000
3913 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3914#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003915 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02003916#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003917 }
3918 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00003919}
3920
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003921#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00003922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003923PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003924"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003925for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003926
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003927
3928
3929
3930static void
3931parse_openssl_version(unsigned long libver,
3932 unsigned int *major, unsigned int *minor,
3933 unsigned int *fix, unsigned int *patch,
3934 unsigned int *status)
3935{
3936 *status = libver & 0xF;
3937 libver >>= 4;
3938 *patch = libver & 0xFF;
3939 libver >>= 8;
3940 *fix = libver & 0xFF;
3941 libver >>= 8;
3942 *minor = libver & 0xFF;
3943 libver >>= 8;
3944 *major = libver & 0xFF;
3945}
3946
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003947PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003948init_ssl(void)
3949{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003950 PyObject *m, *d, *r;
3951 unsigned long libver;
3952 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003953 struct py_ssl_error_code *errcode;
3954 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003955
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003956 if (PyType_Ready(&PySSLContext_Type) < 0)
3957 return;
3958 if (PyType_Ready(&PySSLSocket_Type) < 0)
3959 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003960
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003961 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
3962 if (m == NULL)
3963 return;
3964 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003965
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003966 /* Load _socket module and its C API */
3967 if (PySocketModule_ImportModuleAndAPI())
3968 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003969
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003970 /* Init OpenSSL */
3971 SSL_load_error_strings();
3972 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00003973#ifdef WITH_THREAD
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003974 /* note that this will start threading if not already started */
3975 if (!_setup_ssl_threads()) {
3976 return;
3977 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003978#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003979 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003980
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003981 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003982 PySSLErrorObject = PyErr_NewExceptionWithDoc(
3983 "ssl.SSLError", SSLError_doc,
3984 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003985 if (PySSLErrorObject == NULL)
3986 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003987 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
3988
3989 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3990 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3991 PySSLErrorObject, NULL);
3992 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3993 "ssl.SSLWantReadError", SSLWantReadError_doc,
3994 PySSLErrorObject, NULL);
3995 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3996 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3997 PySSLErrorObject, NULL);
3998 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3999 "ssl.SSLSyscallError", SSLSyscallError_doc,
4000 PySSLErrorObject, NULL);
4001 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4002 "ssl.SSLEOFError", SSLEOFError_doc,
4003 PySSLErrorObject, NULL);
4004 if (PySSLZeroReturnErrorObject == NULL
4005 || PySSLWantReadErrorObject == NULL
4006 || PySSLWantWriteErrorObject == NULL
4007 || PySSLSyscallErrorObject == NULL
4008 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004009 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004010
4011 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
4012 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
4013 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
4014 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
4015 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
4016
4017 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4018 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4019 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4020 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4021 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4022 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
4023 return;
4024 if (PyDict_SetItemString(d, "_SSLContext",
4025 (PyObject *)&PySSLContext_Type) != 0)
4026 return;
4027 if (PyDict_SetItemString(d, "_SSLSocket",
4028 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004029 return;
4030 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4031 PY_SSL_ERROR_ZERO_RETURN);
4032 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4033 PY_SSL_ERROR_WANT_READ);
4034 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4035 PY_SSL_ERROR_WANT_WRITE);
4036 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4037 PY_SSL_ERROR_WANT_X509_LOOKUP);
4038 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4039 PY_SSL_ERROR_SYSCALL);
4040 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4041 PY_SSL_ERROR_SSL);
4042 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4043 PY_SSL_ERROR_WANT_CONNECT);
4044 /* non ssl.h errorcodes */
4045 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4046 PY_SSL_ERROR_EOF);
4047 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4048 PY_SSL_ERROR_INVALID_ERROR_CODE);
4049 /* cert requirements */
4050 PyModule_AddIntConstant(m, "CERT_NONE",
4051 PY_SSL_CERT_NONE);
4052 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4053 PY_SSL_CERT_OPTIONAL);
4054 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4055 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004056 /* CRL verification for verification_flags */
4057 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4058 0);
4059 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4060 X509_V_FLAG_CRL_CHECK);
4061 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4062 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4063 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4064 X509_V_FLAG_X509_STRICT);
4065
4066 /* Alert Descriptions from ssl.h */
4067 /* note RESERVED constants no longer intended for use have been removed */
4068 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4069
4070#define ADD_AD_CONSTANT(s) \
4071 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4072 SSL_AD_##s)
4073
4074 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4075 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4076 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4077 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4078 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4079 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4080 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4081 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4082 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4083 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4084 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4085 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4086 ADD_AD_CONSTANT(UNKNOWN_CA);
4087 ADD_AD_CONSTANT(ACCESS_DENIED);
4088 ADD_AD_CONSTANT(DECODE_ERROR);
4089 ADD_AD_CONSTANT(DECRYPT_ERROR);
4090 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4091 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4092 ADD_AD_CONSTANT(INTERNAL_ERROR);
4093 ADD_AD_CONSTANT(USER_CANCELLED);
4094 ADD_AD_CONSTANT(NO_RENEGOTIATION);
4095 /* Not all constants are in old OpenSSL versions */
4096#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4097 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4098#endif
4099#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4100 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4101#endif
4102#ifdef SSL_AD_UNRECOGNIZED_NAME
4103 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4104#endif
4105#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4106 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4107#endif
4108#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4109 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4110#endif
4111#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4112 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4113#endif
4114
4115#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004116
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004117 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02004118#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004119 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4120 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02004121#endif
Benjamin Peterson60766c42014-12-05 21:59:35 -05004122#ifndef OPENSSL_NO_SSL3
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004123 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4124 PY_SSL_VERSION_SSL3);
Benjamin Peterson60766c42014-12-05 21:59:35 -05004125#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004126 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4127 PY_SSL_VERSION_SSL23);
4128 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4129 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004130#if HAVE_TLSv1_2
4131 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4132 PY_SSL_VERSION_TLS1_1);
4133 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4134 PY_SSL_VERSION_TLS1_2);
4135#endif
4136
4137 /* protocol options */
4138 PyModule_AddIntConstant(m, "OP_ALL",
4139 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4140 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4141 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4142 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
4143#if HAVE_TLSv1_2
4144 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4145 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4146#endif
4147 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4148 SSL_OP_CIPHER_SERVER_PREFERENCE);
4149 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4150#ifdef SSL_OP_SINGLE_ECDH_USE
4151 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4152#endif
4153#ifdef SSL_OP_NO_COMPRESSION
4154 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4155 SSL_OP_NO_COMPRESSION);
4156#endif
4157
4158#if HAVE_SNI
4159 r = Py_True;
4160#else
4161 r = Py_False;
4162#endif
4163 Py_INCREF(r);
4164 PyModule_AddObject(m, "HAS_SNI", r);
4165
4166#if HAVE_OPENSSL_FINISHED
4167 r = Py_True;
4168#else
4169 r = Py_False;
4170#endif
4171 Py_INCREF(r);
4172 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4173
4174#ifdef OPENSSL_NO_ECDH
4175 r = Py_False;
4176#else
4177 r = Py_True;
4178#endif
4179 Py_INCREF(r);
4180 PyModule_AddObject(m, "HAS_ECDH", r);
4181
4182#ifdef OPENSSL_NPN_NEGOTIATED
4183 r = Py_True;
4184#else
4185 r = Py_False;
4186#endif
4187 Py_INCREF(r);
4188 PyModule_AddObject(m, "HAS_NPN", r);
4189
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05004190#ifdef HAVE_ALPN
4191 r = Py_True;
4192#else
4193 r = Py_False;
4194#endif
4195 Py_INCREF(r);
4196 PyModule_AddObject(m, "HAS_ALPN", r);
4197
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004198 /* Mappings for error codes */
4199 err_codes_to_names = PyDict_New();
4200 err_names_to_codes = PyDict_New();
4201 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4202 return;
4203 errcode = error_codes;
4204 while (errcode->mnemonic != NULL) {
4205 PyObject *mnemo, *key;
4206 mnemo = PyUnicode_FromString(errcode->mnemonic);
4207 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4208 if (mnemo == NULL || key == NULL)
4209 return;
4210 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4211 return;
4212 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4213 return;
4214 Py_DECREF(key);
4215 Py_DECREF(mnemo);
4216 errcode++;
4217 }
4218 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4219 return;
4220 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4221 return;
4222
4223 lib_codes_to_names = PyDict_New();
4224 if (lib_codes_to_names == NULL)
4225 return;
4226 libcode = library_codes;
4227 while (libcode->library != NULL) {
4228 PyObject *mnemo, *key;
4229 key = PyLong_FromLong(libcode->code);
4230 mnemo = PyUnicode_FromString(libcode->library);
4231 if (key == NULL || mnemo == NULL)
4232 return;
4233 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4234 return;
4235 Py_DECREF(key);
4236 Py_DECREF(mnemo);
4237 libcode++;
4238 }
4239 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4240 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004241
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004242 /* OpenSSL version */
4243 /* SSLeay() gives us the version of the library linked against,
4244 which could be different from the headers version.
4245 */
4246 libver = SSLeay();
4247 r = PyLong_FromUnsignedLong(libver);
4248 if (r == NULL)
4249 return;
4250 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4251 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004252 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004253 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4254 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4255 return;
4256 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4257 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4258 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004259
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004260 libver = OPENSSL_VERSION_NUMBER;
4261 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4262 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4263 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4264 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004265}